HardwareLoops.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. //===-- HardwareLoops.cpp - Target Independent Hardware Loops --*- C++ -*-===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. /// \file
  9. /// Insert hardware loop intrinsics into loops which are deemed profitable by
  10. /// the target, by querying TargetTransformInfo. A hardware loop comprises of
  11. /// two intrinsics: one, outside the loop, to set the loop iteration count and
  12. /// another, in the exit block, to decrement the counter. The decremented value
  13. /// can either be carried through the loop via a phi or handled in some opaque
  14. /// way by the target.
  15. ///
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/LoopInfo.h"
  20. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  21. #include "llvm/Analysis/ScalarEvolution.h"
  22. #include "llvm/Analysis/TargetLibraryInfo.h"
  23. #include "llvm/Analysis/TargetTransformInfo.h"
  24. #include "llvm/CodeGen/Passes.h"
  25. #include "llvm/IR/BasicBlock.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/Dominators.h"
  28. #include "llvm/IR/IRBuilder.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/IntrinsicInst.h"
  31. #include "llvm/IR/Value.h"
  32. #include "llvm/InitializePasses.h"
  33. #include "llvm/Pass.h"
  34. #include "llvm/PassRegistry.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Transforms/Utils.h"
  38. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  39. #include "llvm/Transforms/Utils/Local.h"
  40. #include "llvm/Transforms/Utils/LoopUtils.h"
  41. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  42. #define DEBUG_TYPE "hardware-loops"
  43. #define HW_LOOPS_NAME "Hardware Loop Insertion"
  44. using namespace llvm;
  45. static cl::opt<bool>
  46. ForceHardwareLoops("force-hardware-loops", cl::Hidden, cl::init(false),
  47. cl::desc("Force hardware loops intrinsics to be inserted"));
  48. static cl::opt<bool>
  49. ForceHardwareLoopPHI(
  50. "force-hardware-loop-phi", cl::Hidden, cl::init(false),
  51. cl::desc("Force hardware loop counter to be updated through a phi"));
  52. static cl::opt<bool>
  53. ForceNestedLoop("force-nested-hardware-loop", cl::Hidden, cl::init(false),
  54. cl::desc("Force allowance of nested hardware loops"));
  55. static cl::opt<unsigned>
  56. LoopDecrement("hardware-loop-decrement", cl::Hidden, cl::init(1),
  57. cl::desc("Set the loop decrement value"));
  58. static cl::opt<unsigned>
  59. CounterBitWidth("hardware-loop-counter-bitwidth", cl::Hidden, cl::init(32),
  60. cl::desc("Set the loop counter bitwidth"));
  61. static cl::opt<bool>
  62. ForceGuardLoopEntry(
  63. "force-hardware-loop-guard", cl::Hidden, cl::init(false),
  64. cl::desc("Force generation of loop guard intrinsic"));
  65. STATISTIC(NumHWLoops, "Number of loops converted to hardware loops");
  66. #ifndef NDEBUG
  67. static void debugHWLoopFailure(const StringRef DebugMsg,
  68. Instruction *I) {
  69. dbgs() << "HWLoops: " << DebugMsg;
  70. if (I)
  71. dbgs() << ' ' << *I;
  72. else
  73. dbgs() << '.';
  74. dbgs() << '\n';
  75. }
  76. #endif
  77. static OptimizationRemarkAnalysis
  78. createHWLoopAnalysis(StringRef RemarkName, Loop *L, Instruction *I) {
  79. Value *CodeRegion = L->getHeader();
  80. DebugLoc DL = L->getStartLoc();
  81. if (I) {
  82. CodeRegion = I->getParent();
  83. // If there is no debug location attached to the instruction, revert back to
  84. // using the loop's.
  85. if (I->getDebugLoc())
  86. DL = I->getDebugLoc();
  87. }
  88. OptimizationRemarkAnalysis R(DEBUG_TYPE, RemarkName, DL, CodeRegion);
  89. R << "hardware-loop not created: ";
  90. return R;
  91. }
  92. namespace {
  93. void reportHWLoopFailure(const StringRef Msg, const StringRef ORETag,
  94. OptimizationRemarkEmitter *ORE, Loop *TheLoop, Instruction *I = nullptr) {
  95. LLVM_DEBUG(debugHWLoopFailure(Msg, I));
  96. ORE->emit(createHWLoopAnalysis(ORETag, TheLoop, I) << Msg);
  97. }
  98. using TTI = TargetTransformInfo;
  99. class HardwareLoops : public FunctionPass {
  100. public:
  101. static char ID;
  102. HardwareLoops() : FunctionPass(ID) {
  103. initializeHardwareLoopsPass(*PassRegistry::getPassRegistry());
  104. }
  105. bool runOnFunction(Function &F) override;
  106. void getAnalysisUsage(AnalysisUsage &AU) const override {
  107. AU.addRequired<LoopInfoWrapperPass>();
  108. AU.addPreserved<LoopInfoWrapperPass>();
  109. AU.addRequired<DominatorTreeWrapperPass>();
  110. AU.addPreserved<DominatorTreeWrapperPass>();
  111. AU.addRequired<ScalarEvolutionWrapperPass>();
  112. AU.addRequired<AssumptionCacheTracker>();
  113. AU.addRequired<TargetTransformInfoWrapperPass>();
  114. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  115. }
  116. // Try to convert the given Loop into a hardware loop.
  117. bool TryConvertLoop(Loop *L);
  118. // Given that the target believes the loop to be profitable, try to
  119. // convert it.
  120. bool TryConvertLoop(HardwareLoopInfo &HWLoopInfo);
  121. private:
  122. ScalarEvolution *SE = nullptr;
  123. LoopInfo *LI = nullptr;
  124. const DataLayout *DL = nullptr;
  125. OptimizationRemarkEmitter *ORE = nullptr;
  126. const TargetTransformInfo *TTI = nullptr;
  127. DominatorTree *DT = nullptr;
  128. bool PreserveLCSSA = false;
  129. AssumptionCache *AC = nullptr;
  130. TargetLibraryInfo *LibInfo = nullptr;
  131. Module *M = nullptr;
  132. bool MadeChange = false;
  133. };
  134. class HardwareLoop {
  135. // Expand the trip count scev into a value that we can use.
  136. Value *InitLoopCount();
  137. // Insert the set_loop_iteration intrinsic.
  138. Value *InsertIterationSetup(Value *LoopCountInit);
  139. // Insert the loop_decrement intrinsic.
  140. void InsertLoopDec();
  141. // Insert the loop_decrement_reg intrinsic.
  142. Instruction *InsertLoopRegDec(Value *EltsRem);
  143. // If the target requires the counter value to be updated in the loop,
  144. // insert a phi to hold the value. The intended purpose is for use by
  145. // loop_decrement_reg.
  146. PHINode *InsertPHICounter(Value *NumElts, Value *EltsRem);
  147. // Create a new cmp, that checks the returned value of loop_decrement*,
  148. // and update the exit branch to use it.
  149. void UpdateBranch(Value *EltsRem);
  150. public:
  151. HardwareLoop(HardwareLoopInfo &Info, ScalarEvolution &SE,
  152. const DataLayout &DL,
  153. OptimizationRemarkEmitter *ORE) :
  154. SE(SE), DL(DL), ORE(ORE), L(Info.L), M(L->getHeader()->getModule()),
  155. ExitCount(Info.ExitCount),
  156. CountType(Info.CountType),
  157. ExitBranch(Info.ExitBranch),
  158. LoopDecrement(Info.LoopDecrement),
  159. UsePHICounter(Info.CounterInReg),
  160. UseLoopGuard(Info.PerformEntryTest) { }
  161. void Create();
  162. private:
  163. ScalarEvolution &SE;
  164. const DataLayout &DL;
  165. OptimizationRemarkEmitter *ORE = nullptr;
  166. Loop *L = nullptr;
  167. Module *M = nullptr;
  168. const SCEV *ExitCount = nullptr;
  169. Type *CountType = nullptr;
  170. BranchInst *ExitBranch = nullptr;
  171. Value *LoopDecrement = nullptr;
  172. bool UsePHICounter = false;
  173. bool UseLoopGuard = false;
  174. BasicBlock *BeginBB = nullptr;
  175. };
  176. }
  177. char HardwareLoops::ID = 0;
  178. bool HardwareLoops::runOnFunction(Function &F) {
  179. if (skipFunction(F))
  180. return false;
  181. LLVM_DEBUG(dbgs() << "HWLoops: Running on " << F.getName() << "\n");
  182. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  183. SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  184. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  185. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  186. DL = &F.getParent()->getDataLayout();
  187. ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  188. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  189. LibInfo = TLIP ? &TLIP->getTLI(F) : nullptr;
  190. PreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
  191. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  192. M = F.getParent();
  193. for (Loop *L : *LI)
  194. if (L->isOutermost())
  195. TryConvertLoop(L);
  196. return MadeChange;
  197. }
  198. // Return true if the search should stop, which will be when an inner loop is
  199. // converted and the parent loop doesn't support containing a hardware loop.
  200. bool HardwareLoops::TryConvertLoop(Loop *L) {
  201. // Process nested loops first.
  202. bool AnyChanged = false;
  203. for (Loop *SL : *L)
  204. AnyChanged |= TryConvertLoop(SL);
  205. if (AnyChanged) {
  206. reportHWLoopFailure("nested hardware-loops not supported", "HWLoopNested",
  207. ORE, L);
  208. return true; // Stop search.
  209. }
  210. LLVM_DEBUG(dbgs() << "HWLoops: Loop " << L->getHeader()->getName() << "\n");
  211. HardwareLoopInfo HWLoopInfo(L);
  212. if (!HWLoopInfo.canAnalyze(*LI)) {
  213. reportHWLoopFailure("cannot analyze loop, irreducible control flow",
  214. "HWLoopCannotAnalyze", ORE, L);
  215. return false;
  216. }
  217. if (!ForceHardwareLoops &&
  218. !TTI->isHardwareLoopProfitable(L, *SE, *AC, LibInfo, HWLoopInfo)) {
  219. reportHWLoopFailure("it's not profitable to create a hardware-loop",
  220. "HWLoopNotProfitable", ORE, L);
  221. return false;
  222. }
  223. // Allow overriding of the counter width and loop decrement value.
  224. if (CounterBitWidth.getNumOccurrences())
  225. HWLoopInfo.CountType =
  226. IntegerType::get(M->getContext(), CounterBitWidth);
  227. if (LoopDecrement.getNumOccurrences())
  228. HWLoopInfo.LoopDecrement =
  229. ConstantInt::get(HWLoopInfo.CountType, LoopDecrement);
  230. MadeChange |= TryConvertLoop(HWLoopInfo);
  231. return MadeChange && (!HWLoopInfo.IsNestingLegal && !ForceNestedLoop);
  232. }
  233. bool HardwareLoops::TryConvertLoop(HardwareLoopInfo &HWLoopInfo) {
  234. Loop *L = HWLoopInfo.L;
  235. LLVM_DEBUG(dbgs() << "HWLoops: Try to convert profitable loop: " << *L);
  236. if (!HWLoopInfo.isHardwareLoopCandidate(*SE, *LI, *DT, ForceNestedLoop,
  237. ForceHardwareLoopPHI)) {
  238. // TODO: there can be many reasons a loop is not considered a
  239. // candidate, so we should let isHardwareLoopCandidate fill in the
  240. // reason and then report a better message here.
  241. reportHWLoopFailure("loop is not a candidate", "HWLoopNoCandidate", ORE, L);
  242. return false;
  243. }
  244. assert(
  245. (HWLoopInfo.ExitBlock && HWLoopInfo.ExitBranch && HWLoopInfo.ExitCount) &&
  246. "Hardware Loop must have set exit info.");
  247. BasicBlock *Preheader = L->getLoopPreheader();
  248. // If we don't have a preheader, then insert one.
  249. if (!Preheader)
  250. Preheader = InsertPreheaderForLoop(L, DT, LI, nullptr, PreserveLCSSA);
  251. if (!Preheader)
  252. return false;
  253. HardwareLoop HWLoop(HWLoopInfo, *SE, *DL, ORE);
  254. HWLoop.Create();
  255. ++NumHWLoops;
  256. return true;
  257. }
  258. void HardwareLoop::Create() {
  259. LLVM_DEBUG(dbgs() << "HWLoops: Converting loop..\n");
  260. Value *LoopCountInit = InitLoopCount();
  261. if (!LoopCountInit) {
  262. reportHWLoopFailure("could not safely create a loop count expression",
  263. "HWLoopNotSafe", ORE, L);
  264. return;
  265. }
  266. Value *Setup = InsertIterationSetup(LoopCountInit);
  267. if (UsePHICounter || ForceHardwareLoopPHI) {
  268. Instruction *LoopDec = InsertLoopRegDec(LoopCountInit);
  269. Value *EltsRem = InsertPHICounter(Setup, LoopDec);
  270. LoopDec->setOperand(0, EltsRem);
  271. UpdateBranch(LoopDec);
  272. } else
  273. InsertLoopDec();
  274. // Run through the basic blocks of the loop and see if any of them have dead
  275. // PHIs that can be removed.
  276. for (auto *I : L->blocks())
  277. DeleteDeadPHIs(I);
  278. }
  279. static bool CanGenerateTest(Loop *L, Value *Count) {
  280. BasicBlock *Preheader = L->getLoopPreheader();
  281. if (!Preheader->getSinglePredecessor())
  282. return false;
  283. BasicBlock *Pred = Preheader->getSinglePredecessor();
  284. if (!isa<BranchInst>(Pred->getTerminator()))
  285. return false;
  286. auto *BI = cast<BranchInst>(Pred->getTerminator());
  287. if (BI->isUnconditional() || !isa<ICmpInst>(BI->getCondition()))
  288. return false;
  289. // Check that the icmp is checking for equality of Count and zero and that
  290. // a non-zero value results in entering the loop.
  291. auto ICmp = cast<ICmpInst>(BI->getCondition());
  292. LLVM_DEBUG(dbgs() << " - Found condition: " << *ICmp << "\n");
  293. if (!ICmp->isEquality())
  294. return false;
  295. auto IsCompareZero = [](ICmpInst *ICmp, Value *Count, unsigned OpIdx) {
  296. if (auto *Const = dyn_cast<ConstantInt>(ICmp->getOperand(OpIdx)))
  297. return Const->isZero() && ICmp->getOperand(OpIdx ^ 1) == Count;
  298. return false;
  299. };
  300. // Check if Count is a zext.
  301. Value *CountBefZext =
  302. isa<ZExtInst>(Count) ? cast<ZExtInst>(Count)->getOperand(0) : nullptr;
  303. if (!IsCompareZero(ICmp, Count, 0) && !IsCompareZero(ICmp, Count, 1) &&
  304. !IsCompareZero(ICmp, CountBefZext, 0) &&
  305. !IsCompareZero(ICmp, CountBefZext, 1))
  306. return false;
  307. unsigned SuccIdx = ICmp->getPredicate() == ICmpInst::ICMP_NE ? 0 : 1;
  308. if (BI->getSuccessor(SuccIdx) != Preheader)
  309. return false;
  310. return true;
  311. }
  312. Value *HardwareLoop::InitLoopCount() {
  313. LLVM_DEBUG(dbgs() << "HWLoops: Initialising loop counter value:\n");
  314. // Can we replace a conditional branch with an intrinsic that sets the
  315. // loop counter and tests that is not zero?
  316. SCEVExpander SCEVE(SE, DL, "loopcnt");
  317. if (!ExitCount->getType()->isPointerTy() &&
  318. ExitCount->getType() != CountType)
  319. ExitCount = SE.getZeroExtendExpr(ExitCount, CountType);
  320. ExitCount = SE.getAddExpr(ExitCount, SE.getOne(CountType));
  321. // If we're trying to use the 'test and set' form of the intrinsic, we need
  322. // to replace a conditional branch that is controlling entry to the loop. It
  323. // is likely (guaranteed?) that the preheader has an unconditional branch to
  324. // the loop header, so also check if it has a single predecessor.
  325. if (SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, ExitCount,
  326. SE.getZero(ExitCount->getType()))) {
  327. LLVM_DEBUG(dbgs() << " - Attempting to use test.set counter.\n");
  328. UseLoopGuard |= ForceGuardLoopEntry;
  329. } else
  330. UseLoopGuard = false;
  331. BasicBlock *BB = L->getLoopPreheader();
  332. if (UseLoopGuard && BB->getSinglePredecessor() &&
  333. cast<BranchInst>(BB->getTerminator())->isUnconditional()) {
  334. BasicBlock *Predecessor = BB->getSinglePredecessor();
  335. // If it's not safe to create a while loop then don't force it and create a
  336. // do-while loop instead
  337. if (!SCEVE.isSafeToExpandAt(ExitCount, Predecessor->getTerminator()))
  338. UseLoopGuard = false;
  339. else
  340. BB = Predecessor;
  341. }
  342. if (!SCEVE.isSafeToExpandAt(ExitCount, BB->getTerminator())) {
  343. LLVM_DEBUG(dbgs() << "- Bailing, unsafe to expand ExitCount "
  344. << *ExitCount << "\n");
  345. return nullptr;
  346. }
  347. Value *Count = SCEVE.expandCodeFor(ExitCount, CountType,
  348. BB->getTerminator());
  349. // FIXME: We've expanded Count where we hope to insert the counter setting
  350. // intrinsic. But, in the case of the 'test and set' form, we may fallback to
  351. // the just 'set' form and in which case the insertion block is most likely
  352. // different. It means there will be instruction(s) in a block that possibly
  353. // aren't needed. The isLoopEntryGuardedByCond is trying to avoid this issue,
  354. // but it's doesn't appear to work in all cases.
  355. UseLoopGuard = UseLoopGuard && CanGenerateTest(L, Count);
  356. BeginBB = UseLoopGuard ? BB : L->getLoopPreheader();
  357. LLVM_DEBUG(dbgs() << " - Loop Count: " << *Count << "\n"
  358. << " - Expanded Count in " << BB->getName() << "\n"
  359. << " - Will insert set counter intrinsic into: "
  360. << BeginBB->getName() << "\n");
  361. return Count;
  362. }
  363. Value* HardwareLoop::InsertIterationSetup(Value *LoopCountInit) {
  364. IRBuilder<> Builder(BeginBB->getTerminator());
  365. Type *Ty = LoopCountInit->getType();
  366. bool UsePhi = UsePHICounter || ForceHardwareLoopPHI;
  367. Intrinsic::ID ID = UseLoopGuard
  368. ? (UsePhi ? Intrinsic::test_start_loop_iterations
  369. : Intrinsic::test_set_loop_iterations)
  370. : (UsePhi ? Intrinsic::start_loop_iterations
  371. : Intrinsic::set_loop_iterations);
  372. Function *LoopIter = Intrinsic::getDeclaration(M, ID, Ty);
  373. Value *LoopSetup = Builder.CreateCall(LoopIter, LoopCountInit);
  374. // Use the return value of the intrinsic to control the entry of the loop.
  375. if (UseLoopGuard) {
  376. assert((isa<BranchInst>(BeginBB->getTerminator()) &&
  377. cast<BranchInst>(BeginBB->getTerminator())->isConditional()) &&
  378. "Expected conditional branch");
  379. Value *SetCount =
  380. UsePhi ? Builder.CreateExtractValue(LoopSetup, 1) : LoopSetup;
  381. auto *LoopGuard = cast<BranchInst>(BeginBB->getTerminator());
  382. LoopGuard->setCondition(SetCount);
  383. if (LoopGuard->getSuccessor(0) != L->getLoopPreheader())
  384. LoopGuard->swapSuccessors();
  385. }
  386. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop counter: " << *LoopSetup
  387. << "\n");
  388. if (UsePhi && UseLoopGuard)
  389. LoopSetup = Builder.CreateExtractValue(LoopSetup, 0);
  390. return !UsePhi ? LoopCountInit : LoopSetup;
  391. }
  392. void HardwareLoop::InsertLoopDec() {
  393. IRBuilder<> CondBuilder(ExitBranch);
  394. Function *DecFunc =
  395. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement,
  396. LoopDecrement->getType());
  397. Value *Ops[] = { LoopDecrement };
  398. Value *NewCond = CondBuilder.CreateCall(DecFunc, Ops);
  399. Value *OldCond = ExitBranch->getCondition();
  400. ExitBranch->setCondition(NewCond);
  401. // The false branch must exit the loop.
  402. if (!L->contains(ExitBranch->getSuccessor(0)))
  403. ExitBranch->swapSuccessors();
  404. // The old condition may be dead now, and may have even created a dead PHI
  405. // (the original induction variable).
  406. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  407. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *NewCond << "\n");
  408. }
  409. Instruction* HardwareLoop::InsertLoopRegDec(Value *EltsRem) {
  410. IRBuilder<> CondBuilder(ExitBranch);
  411. Function *DecFunc =
  412. Intrinsic::getDeclaration(M, Intrinsic::loop_decrement_reg,
  413. { EltsRem->getType() });
  414. Value *Ops[] = { EltsRem, LoopDecrement };
  415. Value *Call = CondBuilder.CreateCall(DecFunc, Ops);
  416. LLVM_DEBUG(dbgs() << "HWLoops: Inserted loop dec: " << *Call << "\n");
  417. return cast<Instruction>(Call);
  418. }
  419. PHINode* HardwareLoop::InsertPHICounter(Value *NumElts, Value *EltsRem) {
  420. BasicBlock *Preheader = L->getLoopPreheader();
  421. BasicBlock *Header = L->getHeader();
  422. BasicBlock *Latch = ExitBranch->getParent();
  423. IRBuilder<> Builder(Header->getFirstNonPHI());
  424. PHINode *Index = Builder.CreatePHI(NumElts->getType(), 2);
  425. Index->addIncoming(NumElts, Preheader);
  426. Index->addIncoming(EltsRem, Latch);
  427. LLVM_DEBUG(dbgs() << "HWLoops: PHI Counter: " << *Index << "\n");
  428. return Index;
  429. }
  430. void HardwareLoop::UpdateBranch(Value *EltsRem) {
  431. IRBuilder<> CondBuilder(ExitBranch);
  432. Value *NewCond =
  433. CondBuilder.CreateICmpNE(EltsRem, ConstantInt::get(EltsRem->getType(), 0));
  434. Value *OldCond = ExitBranch->getCondition();
  435. ExitBranch->setCondition(NewCond);
  436. // The false branch must exit the loop.
  437. if (!L->contains(ExitBranch->getSuccessor(0)))
  438. ExitBranch->swapSuccessors();
  439. // The old condition may be dead now, and may have even created a dead PHI
  440. // (the original induction variable).
  441. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  442. }
  443. INITIALIZE_PASS_BEGIN(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  444. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  445. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  446. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  447. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  448. INITIALIZE_PASS_END(HardwareLoops, DEBUG_TYPE, HW_LOOPS_NAME, false, false)
  449. FunctionPass *llvm::createHardwareLoopsPass() { return new HardwareLoops(); }