LoopRotationUtils.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. //===----------------- LoopRotationUtils.cpp -----------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file provides utilities to convert a loop into a loop with bottom test.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/LoopRotationUtils.h"
  14. #include "llvm/ADT/Statistic.h"
  15. #include "llvm/Analysis/AliasAnalysis.h"
  16. #include "llvm/Analysis/AssumptionCache.h"
  17. #include "llvm/Analysis/BasicAliasAnalysis.h"
  18. #include "llvm/Analysis/CodeMetrics.h"
  19. #include "llvm/Analysis/GlobalsModRef.h"
  20. #include "llvm/Analysis/InstructionSimplify.h"
  21. #include "llvm/Analysis/LoopPass.h"
  22. #include "llvm/Analysis/ScalarEvolution.h"
  23. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  24. #include "llvm/Analysis/TargetTransformInfo.h"
  25. #include "llvm/Analysis/ValueTracking.h"
  26. #include "llvm/IR/CFG.h"
  27. #include "llvm/IR/DebugInfoMetadata.h"
  28. #include "llvm/IR/DomTreeUpdater.h"
  29. #include "llvm/IR/Dominators.h"
  30. #include "llvm/IR/Function.h"
  31. #include "llvm/IR/IntrinsicInst.h"
  32. #include "llvm/IR/Module.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/Debug.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  37. #include "llvm/Transforms/Utils/Local.h"
  38. #include "llvm/Transforms/Utils/LoopUtils.h"
  39. #include "llvm/Transforms/Utils/SSAUpdater.h"
  40. #include "llvm/Transforms/Utils/ValueMapper.h"
  41. using namespace llvm;
  42. #define DEBUG_TYPE "loop-rotate"
  43. STATISTIC(NumRotated, "Number of loops rotated");
  44. namespace {
  45. /// A simple loop rotation transformation.
  46. class LoopRotate {
  47. const unsigned MaxHeaderSize;
  48. LoopInfo *LI;
  49. const TargetTransformInfo *TTI;
  50. AssumptionCache *AC;
  51. DominatorTree *DT;
  52. ScalarEvolution *SE;
  53. const SimplifyQuery &SQ;
  54. bool RotationOnly;
  55. bool IsUtilMode;
  56. public:
  57. LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
  58. const TargetTransformInfo *TTI, AssumptionCache *AC,
  59. DominatorTree *DT, ScalarEvolution *SE, const SimplifyQuery &SQ,
  60. bool RotationOnly, bool IsUtilMode)
  61. : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
  62. SQ(SQ), RotationOnly(RotationOnly), IsUtilMode(IsUtilMode) {}
  63. bool processLoop(Loop *L);
  64. private:
  65. bool rotateLoop(Loop *L, bool SimplifiedLatch);
  66. bool simplifyLoopLatch(Loop *L);
  67. };
  68. } // end anonymous namespace
  69. /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
  70. /// old header into the preheader. If there were uses of the values produced by
  71. /// these instruction that were outside of the loop, we have to insert PHI nodes
  72. /// to merge the two values. Do this now.
  73. static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
  74. BasicBlock *OrigPreheader,
  75. ValueToValueMapTy &ValueMap,
  76. SmallVectorImpl<PHINode*> *InsertedPHIs) {
  77. // Remove PHI node entries that are no longer live.
  78. BasicBlock::iterator I, E = OrigHeader->end();
  79. for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
  80. PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
  81. // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
  82. // as necessary.
  83. SSAUpdater SSA(InsertedPHIs);
  84. for (I = OrigHeader->begin(); I != E; ++I) {
  85. Value *OrigHeaderVal = &*I;
  86. // If there are no uses of the value (e.g. because it returns void), there
  87. // is nothing to rewrite.
  88. if (OrigHeaderVal->use_empty())
  89. continue;
  90. Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
  91. // The value now exits in two versions: the initial value in the preheader
  92. // and the loop "next" value in the original header.
  93. SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
  94. SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
  95. SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
  96. // Visit each use of the OrigHeader instruction.
  97. for (Value::use_iterator UI = OrigHeaderVal->use_begin(),
  98. UE = OrigHeaderVal->use_end();
  99. UI != UE;) {
  100. // Grab the use before incrementing the iterator.
  101. Use &U = *UI;
  102. // Increment the iterator before removing the use from the list.
  103. ++UI;
  104. // SSAUpdater can't handle a non-PHI use in the same block as an
  105. // earlier def. We can easily handle those cases manually.
  106. Instruction *UserInst = cast<Instruction>(U.getUser());
  107. if (!isa<PHINode>(UserInst)) {
  108. BasicBlock *UserBB = UserInst->getParent();
  109. // The original users in the OrigHeader are already using the
  110. // original definitions.
  111. if (UserBB == OrigHeader)
  112. continue;
  113. // Users in the OrigPreHeader need to use the value to which the
  114. // original definitions are mapped.
  115. if (UserBB == OrigPreheader) {
  116. U = OrigPreHeaderVal;
  117. continue;
  118. }
  119. }
  120. // Anything else can be handled by SSAUpdater.
  121. SSA.RewriteUse(U);
  122. }
  123. // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
  124. // intrinsics.
  125. SmallVector<DbgValueInst *, 1> DbgValues;
  126. llvm::findDbgValues(DbgValues, OrigHeaderVal);
  127. for (auto &DbgValue : DbgValues) {
  128. // The original users in the OrigHeader are already using the original
  129. // definitions.
  130. BasicBlock *UserBB = DbgValue->getParent();
  131. if (UserBB == OrigHeader)
  132. continue;
  133. // Users in the OrigPreHeader need to use the value to which the
  134. // original definitions are mapped and anything else can be handled by
  135. // the SSAUpdater. To avoid adding PHINodes, check if the value is
  136. // available in UserBB, if not substitute undef.
  137. Value *NewVal;
  138. if (UserBB == OrigPreheader)
  139. NewVal = OrigPreHeaderVal;
  140. else if (SSA.HasValueForBlock(UserBB))
  141. NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
  142. else
  143. NewVal = UndefValue::get(OrigHeaderVal->getType());
  144. DbgValue->setOperand(0,
  145. MetadataAsValue::get(OrigHeaderVal->getContext(),
  146. ValueAsMetadata::get(NewVal)));
  147. }
  148. }
  149. }
  150. // Look for a phi which is only used outside the loop (via a LCSSA phi)
  151. // in the exit from the header. This means that rotating the loop can
  152. // remove the phi.
  153. static bool shouldRotateLoopExitingLatch(Loop *L) {
  154. BasicBlock *Header = L->getHeader();
  155. BasicBlock *HeaderExit = Header->getTerminator()->getSuccessor(0);
  156. if (L->contains(HeaderExit))
  157. HeaderExit = Header->getTerminator()->getSuccessor(1);
  158. for (auto &Phi : Header->phis()) {
  159. // Look for uses of this phi in the loop/via exits other than the header.
  160. if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
  161. return cast<Instruction>(U)->getParent() != HeaderExit;
  162. }))
  163. continue;
  164. return true;
  165. }
  166. return false;
  167. }
  168. /// Rotate loop LP. Return true if the loop is rotated.
  169. ///
  170. /// \param SimplifiedLatch is true if the latch was just folded into the final
  171. /// loop exit. In this case we may want to rotate even though the new latch is
  172. /// now an exiting branch. This rotation would have happened had the latch not
  173. /// been simplified. However, if SimplifiedLatch is false, then we avoid
  174. /// rotating loops in which the latch exits to avoid excessive or endless
  175. /// rotation. LoopRotate should be repeatable and converge to a canonical
  176. /// form. This property is satisfied because simplifying the loop latch can only
  177. /// happen once across multiple invocations of the LoopRotate pass.
  178. bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
  179. // If the loop has only one block then there is not much to rotate.
  180. if (L->getBlocks().size() == 1)
  181. return false;
  182. BasicBlock *OrigHeader = L->getHeader();
  183. BasicBlock *OrigLatch = L->getLoopLatch();
  184. BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
  185. if (!BI || BI->isUnconditional())
  186. return false;
  187. // If the loop header is not one of the loop exiting blocks then
  188. // either this loop is already rotated or it is not
  189. // suitable for loop rotation transformations.
  190. if (!L->isLoopExiting(OrigHeader))
  191. return false;
  192. // If the loop latch already contains a branch that leaves the loop then the
  193. // loop is already rotated.
  194. if (!OrigLatch)
  195. return false;
  196. // Rotate if either the loop latch does *not* exit the loop, or if the loop
  197. // latch was just simplified. Or if we think it will be profitable.
  198. if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
  199. !shouldRotateLoopExitingLatch(L))
  200. return false;
  201. // Check size of original header and reject loop if it is very big or we can't
  202. // duplicate blocks inside it.
  203. {
  204. SmallPtrSet<const Value *, 32> EphValues;
  205. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  206. CodeMetrics Metrics;
  207. Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues);
  208. if (Metrics.notDuplicatable) {
  209. LLVM_DEBUG(
  210. dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
  211. << " instructions: ";
  212. L->dump());
  213. return false;
  214. }
  215. if (Metrics.convergent) {
  216. LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
  217. "instructions: ";
  218. L->dump());
  219. return false;
  220. }
  221. if (Metrics.NumInsts > MaxHeaderSize)
  222. return false;
  223. }
  224. // Now, this loop is suitable for rotation.
  225. BasicBlock *OrigPreheader = L->getLoopPreheader();
  226. // If the loop could not be converted to canonical form, it must have an
  227. // indirectbr in it, just give up.
  228. if (!OrigPreheader || !L->hasDedicatedExits())
  229. return false;
  230. // Anything ScalarEvolution may know about this loop or the PHI nodes
  231. // in its header will soon be invalidated. We should also invalidate
  232. // all outer loops because insertion and deletion of blocks that happens
  233. // during the rotation may violate invariants related to backedge taken
  234. // infos in them.
  235. if (SE)
  236. SE->forgetTopmostLoop(L);
  237. LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
  238. // Find new Loop header. NewHeader is a Header's one and only successor
  239. // that is inside loop. Header's other successor is outside the
  240. // loop. Otherwise loop is not suitable for rotation.
  241. BasicBlock *Exit = BI->getSuccessor(0);
  242. BasicBlock *NewHeader = BI->getSuccessor(1);
  243. if (L->contains(Exit))
  244. std::swap(Exit, NewHeader);
  245. assert(NewHeader && "Unable to determine new loop header");
  246. assert(L->contains(NewHeader) && !L->contains(Exit) &&
  247. "Unable to determine loop header and exit blocks");
  248. // This code assumes that the new header has exactly one predecessor.
  249. // Remove any single-entry PHI nodes in it.
  250. assert(NewHeader->getSinglePredecessor() &&
  251. "New header doesn't have one pred!");
  252. FoldSingleEntryPHINodes(NewHeader);
  253. // Begin by walking OrigHeader and populating ValueMap with an entry for
  254. // each Instruction.
  255. BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
  256. ValueToValueMapTy ValueMap;
  257. // For PHI nodes, the value available in OldPreHeader is just the
  258. // incoming value from OldPreHeader.
  259. for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
  260. ValueMap[PN] = PN->getIncomingValueForBlock(OrigPreheader);
  261. // For the rest of the instructions, either hoist to the OrigPreheader if
  262. // possible or create a clone in the OldPreHeader if not.
  263. TerminatorInst *LoopEntryBranch = OrigPreheader->getTerminator();
  264. // Record all debug intrinsics preceding LoopEntryBranch to avoid duplication.
  265. using DbgIntrinsicHash =
  266. std::pair<std::pair<Value *, DILocalVariable *>, DIExpression *>;
  267. auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
  268. return {{D->getVariableLocation(), D->getVariable()}, D->getExpression()};
  269. };
  270. SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
  271. for (auto I = std::next(OrigPreheader->rbegin()), E = OrigPreheader->rend();
  272. I != E; ++I) {
  273. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&*I))
  274. DbgIntrinsics.insert(makeHash(DII));
  275. else
  276. break;
  277. }
  278. while (I != E) {
  279. Instruction *Inst = &*I++;
  280. // If the instruction's operands are invariant and it doesn't read or write
  281. // memory, then it is safe to hoist. Doing this doesn't change the order of
  282. // execution in the preheader, but does prevent the instruction from
  283. // executing in each iteration of the loop. This means it is safe to hoist
  284. // something that might trap, but isn't safe to hoist something that reads
  285. // memory (without proving that the loop doesn't write).
  286. if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
  287. !Inst->mayWriteToMemory() && !isa<TerminatorInst>(Inst) &&
  288. !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
  289. Inst->moveBefore(LoopEntryBranch);
  290. continue;
  291. }
  292. // Otherwise, create a duplicate of the instruction.
  293. Instruction *C = Inst->clone();
  294. // Eagerly remap the operands of the instruction.
  295. RemapInstruction(C, ValueMap,
  296. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  297. // Avoid inserting the same intrinsic twice.
  298. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
  299. if (DbgIntrinsics.count(makeHash(DII))) {
  300. C->deleteValue();
  301. continue;
  302. }
  303. // With the operands remapped, see if the instruction constant folds or is
  304. // otherwise simplifyable. This commonly occurs because the entry from PHI
  305. // nodes allows icmps and other instructions to fold.
  306. Value *V = SimplifyInstruction(C, SQ);
  307. if (V && LI->replacementPreservesLCSSAForm(C, V)) {
  308. // If so, then delete the temporary instruction and stick the folded value
  309. // in the map.
  310. ValueMap[Inst] = V;
  311. if (!C->mayHaveSideEffects()) {
  312. C->deleteValue();
  313. C = nullptr;
  314. }
  315. } else {
  316. ValueMap[Inst] = C;
  317. }
  318. if (C) {
  319. // Otherwise, stick the new instruction into the new block!
  320. C->setName(Inst->getName());
  321. C->insertBefore(LoopEntryBranch);
  322. if (auto *II = dyn_cast<IntrinsicInst>(C))
  323. if (II->getIntrinsicID() == Intrinsic::assume)
  324. AC->registerAssumption(II);
  325. }
  326. }
  327. // Along with all the other instructions, we just cloned OrigHeader's
  328. // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
  329. // successors by duplicating their incoming values for OrigHeader.
  330. for (BasicBlock *SuccBB : successors(OrigHeader))
  331. for (BasicBlock::iterator BI = SuccBB->begin();
  332. PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  333. PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
  334. // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
  335. // OrigPreHeader's old terminator (the original branch into the loop), and
  336. // remove the corresponding incoming values from the PHI nodes in OrigHeader.
  337. LoopEntryBranch->eraseFromParent();
  338. SmallVector<PHINode*, 2> InsertedPHIs;
  339. // If there were any uses of instructions in the duplicated block outside the
  340. // loop, update them, inserting PHI nodes as required
  341. RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap,
  342. &InsertedPHIs);
  343. // Attach dbg.value intrinsics to the new phis if that phi uses a value that
  344. // previously had debug metadata attached. This keeps the debug info
  345. // up-to-date in the loop body.
  346. if (!InsertedPHIs.empty())
  347. insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
  348. // NewHeader is now the header of the loop.
  349. L->moveToHeader(NewHeader);
  350. assert(L->getHeader() == NewHeader && "Latch block is our new header");
  351. // Inform DT about changes to the CFG.
  352. if (DT) {
  353. // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
  354. // the DT about the removed edge to the OrigHeader (that got removed).
  355. SmallVector<DominatorTree::UpdateType, 3> Updates;
  356. Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
  357. Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
  358. Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
  359. DT->applyUpdates(Updates);
  360. }
  361. // At this point, we've finished our major CFG changes. As part of cloning
  362. // the loop into the preheader we've simplified instructions and the
  363. // duplicated conditional branch may now be branching on a constant. If it is
  364. // branching on a constant and if that constant means that we enter the loop,
  365. // then we fold away the cond branch to an uncond branch. This simplifies the
  366. // loop in cases important for nested loops, and it also means we don't have
  367. // to split as many edges.
  368. BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
  369. assert(PHBI->isConditional() && "Should be clone of BI condbr!");
  370. if (!isa<ConstantInt>(PHBI->getCondition()) ||
  371. PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
  372. NewHeader) {
  373. // The conditional branch can't be folded, handle the general case.
  374. // Split edges as necessary to preserve LoopSimplify form.
  375. // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
  376. // thus is not a preheader anymore.
  377. // Split the edge to form a real preheader.
  378. BasicBlock *NewPH = SplitCriticalEdge(
  379. OrigPreheader, NewHeader,
  380. CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
  381. NewPH->setName(NewHeader->getName() + ".lr.ph");
  382. // Preserve canonical loop form, which means that 'Exit' should have only
  383. // one predecessor. Note that Exit could be an exit block for multiple
  384. // nested loops, causing both of the edges to now be critical and need to
  385. // be split.
  386. SmallVector<BasicBlock *, 4> ExitPreds(pred_begin(Exit), pred_end(Exit));
  387. bool SplitLatchEdge = false;
  388. for (BasicBlock *ExitPred : ExitPreds) {
  389. // We only need to split loop exit edges.
  390. Loop *PredLoop = LI->getLoopFor(ExitPred);
  391. if (!PredLoop || PredLoop->contains(Exit))
  392. continue;
  393. if (isa<IndirectBrInst>(ExitPred->getTerminator()))
  394. continue;
  395. SplitLatchEdge |= L->getLoopLatch() == ExitPred;
  396. BasicBlock *ExitSplit = SplitCriticalEdge(
  397. ExitPred, Exit,
  398. CriticalEdgeSplittingOptions(DT, LI).setPreserveLCSSA());
  399. ExitSplit->moveBefore(Exit);
  400. }
  401. assert(SplitLatchEdge &&
  402. "Despite splitting all preds, failed to split latch exit?");
  403. } else {
  404. // We can fold the conditional branch in the preheader, this makes things
  405. // simpler. The first step is to remove the extra edge to the Exit block.
  406. Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
  407. BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
  408. NewBI->setDebugLoc(PHBI->getDebugLoc());
  409. PHBI->eraseFromParent();
  410. // With our CFG finalized, update DomTree if it is available.
  411. if (DT) DT->deleteEdge(OrigPreheader, Exit);
  412. }
  413. assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
  414. assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
  415. // Now that the CFG and DomTree are in a consistent state again, try to merge
  416. // the OrigHeader block into OrigLatch. This will succeed if they are
  417. // connected by an unconditional branch. This is just a cleanup so the
  418. // emitted code isn't too gross in this common case.
  419. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  420. MergeBlockIntoPredecessor(OrigHeader, &DTU, LI);
  421. LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
  422. ++NumRotated;
  423. return true;
  424. }
  425. /// Determine whether the instructions in this range may be safely and cheaply
  426. /// speculated. This is not an important enough situation to develop complex
  427. /// heuristics. We handle a single arithmetic instruction along with any type
  428. /// conversions.
  429. static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
  430. BasicBlock::iterator End, Loop *L) {
  431. bool seenIncrement = false;
  432. bool MultiExitLoop = false;
  433. if (!L->getExitingBlock())
  434. MultiExitLoop = true;
  435. for (BasicBlock::iterator I = Begin; I != End; ++I) {
  436. if (!isSafeToSpeculativelyExecute(&*I))
  437. return false;
  438. if (isa<DbgInfoIntrinsic>(I))
  439. continue;
  440. switch (I->getOpcode()) {
  441. default:
  442. return false;
  443. case Instruction::GetElementPtr:
  444. // GEPs are cheap if all indices are constant.
  445. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  446. return false;
  447. // fall-thru to increment case
  448. LLVM_FALLTHROUGH;
  449. case Instruction::Add:
  450. case Instruction::Sub:
  451. case Instruction::And:
  452. case Instruction::Or:
  453. case Instruction::Xor:
  454. case Instruction::Shl:
  455. case Instruction::LShr:
  456. case Instruction::AShr: {
  457. Value *IVOpnd =
  458. !isa<Constant>(I->getOperand(0))
  459. ? I->getOperand(0)
  460. : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
  461. if (!IVOpnd)
  462. return false;
  463. // If increment operand is used outside of the loop, this speculation
  464. // could cause extra live range interference.
  465. if (MultiExitLoop) {
  466. for (User *UseI : IVOpnd->users()) {
  467. auto *UserInst = cast<Instruction>(UseI);
  468. if (!L->contains(UserInst))
  469. return false;
  470. }
  471. }
  472. if (seenIncrement)
  473. return false;
  474. seenIncrement = true;
  475. break;
  476. }
  477. case Instruction::Trunc:
  478. case Instruction::ZExt:
  479. case Instruction::SExt:
  480. // ignore type conversions
  481. break;
  482. }
  483. }
  484. return true;
  485. }
  486. /// Fold the loop tail into the loop exit by speculating the loop tail
  487. /// instructions. Typically, this is a single post-increment. In the case of a
  488. /// simple 2-block loop, hoisting the increment can be much better than
  489. /// duplicating the entire loop header. In the case of loops with early exits,
  490. /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
  491. /// canonical form so downstream passes can handle it.
  492. ///
  493. /// I don't believe this invalidates SCEV.
  494. bool LoopRotate::simplifyLoopLatch(Loop *L) {
  495. BasicBlock *Latch = L->getLoopLatch();
  496. if (!Latch || Latch->hasAddressTaken())
  497. return false;
  498. BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
  499. if (!Jmp || !Jmp->isUnconditional())
  500. return false;
  501. BasicBlock *LastExit = Latch->getSinglePredecessor();
  502. if (!LastExit || !L->isLoopExiting(LastExit))
  503. return false;
  504. BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
  505. if (!BI)
  506. return false;
  507. if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
  508. return false;
  509. LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
  510. << LastExit->getName() << "\n");
  511. // Hoist the instructions from Latch into LastExit.
  512. LastExit->getInstList().splice(BI->getIterator(), Latch->getInstList(),
  513. Latch->begin(), Jmp->getIterator());
  514. unsigned FallThruPath = BI->getSuccessor(0) == Latch ? 0 : 1;
  515. BasicBlock *Header = Jmp->getSuccessor(0);
  516. assert(Header == L->getHeader() && "expected a backward branch");
  517. // Remove Latch from the CFG so that LastExit becomes the new Latch.
  518. BI->setSuccessor(FallThruPath, Header);
  519. Latch->replaceSuccessorsPhiUsesWith(LastExit);
  520. Jmp->eraseFromParent();
  521. // Nuke the Latch block.
  522. assert(Latch->empty() && "unable to evacuate Latch");
  523. LI->removeBlock(Latch);
  524. if (DT)
  525. DT->eraseNode(Latch);
  526. Latch->eraseFromParent();
  527. return true;
  528. }
  529. /// Rotate \c L, and return true if any modification was made.
  530. bool LoopRotate::processLoop(Loop *L) {
  531. // Save the loop metadata.
  532. MDNode *LoopMD = L->getLoopID();
  533. bool SimplifiedLatch = false;
  534. // Simplify the loop latch before attempting to rotate the header
  535. // upward. Rotation may not be needed if the loop tail can be folded into the
  536. // loop exit.
  537. if (!RotationOnly)
  538. SimplifiedLatch = simplifyLoopLatch(L);
  539. bool MadeChange = rotateLoop(L, SimplifiedLatch);
  540. assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
  541. "Loop latch should be exiting after loop-rotate.");
  542. // Restore the loop metadata.
  543. // NB! We presume LoopRotation DOESN'T ADD its own metadata.
  544. if ((MadeChange || SimplifiedLatch) && LoopMD)
  545. L->setLoopID(LoopMD);
  546. return MadeChange || SimplifiedLatch;
  547. }
  548. /// The utility to convert a loop into a loop with bottom test.
  549. bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
  550. AssumptionCache *AC, DominatorTree *DT,
  551. ScalarEvolution *SE, const SimplifyQuery &SQ,
  552. bool RotationOnly = true,
  553. unsigned Threshold = unsigned(-1),
  554. bool IsUtilMode = true) {
  555. LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, SQ, RotationOnly, IsUtilMode);
  556. return LR.processLoop(L);
  557. }