LoopRotationUtils.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. //===----------------- LoopRotationUtils.cpp -----------------------------===//
  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. //
  9. // This file provides utilities to convert a loop into a loop with bottom test.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Transforms/Utils/LoopRotationUtils.h"
  13. #include "llvm/ADT/Statistic.h"
  14. #include "llvm/Analysis/AssumptionCache.h"
  15. #include "llvm/Analysis/CodeMetrics.h"
  16. #include "llvm/Analysis/DomTreeUpdater.h"
  17. #include "llvm/Analysis/InstructionSimplify.h"
  18. #include "llvm/Analysis/LoopInfo.h"
  19. #include "llvm/Analysis/MemorySSA.h"
  20. #include "llvm/Analysis/MemorySSAUpdater.h"
  21. #include "llvm/Analysis/ScalarEvolution.h"
  22. #include "llvm/Analysis/ValueTracking.h"
  23. #include "llvm/IR/CFG.h"
  24. #include "llvm/IR/DebugInfo.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/IntrinsicInst.h"
  27. #include "llvm/Support/CommandLine.h"
  28. #include "llvm/Support/Debug.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  31. #include "llvm/Transforms/Utils/Cloning.h"
  32. #include "llvm/Transforms/Utils/Local.h"
  33. #include "llvm/Transforms/Utils/SSAUpdater.h"
  34. #include "llvm/Transforms/Utils/ValueMapper.h"
  35. using namespace llvm;
  36. #define DEBUG_TYPE "loop-rotate"
  37. STATISTIC(NumNotRotatedDueToHeaderSize,
  38. "Number of loops not rotated due to the header size");
  39. STATISTIC(NumInstrsHoisted,
  40. "Number of instructions hoisted into loop preheader");
  41. STATISTIC(NumInstrsDuplicated,
  42. "Number of instructions cloned into loop preheader");
  43. STATISTIC(NumRotated, "Number of loops rotated");
  44. static cl::opt<bool>
  45. MultiRotate("loop-rotate-multi", cl::init(false), cl::Hidden,
  46. cl::desc("Allow loop rotation multiple times in order to reach "
  47. "a better latch exit"));
  48. namespace {
  49. /// A simple loop rotation transformation.
  50. class LoopRotate {
  51. const unsigned MaxHeaderSize;
  52. LoopInfo *LI;
  53. const TargetTransformInfo *TTI;
  54. AssumptionCache *AC;
  55. DominatorTree *DT;
  56. ScalarEvolution *SE;
  57. MemorySSAUpdater *MSSAU;
  58. const SimplifyQuery &SQ;
  59. bool RotationOnly;
  60. bool IsUtilMode;
  61. bool PrepareForLTO;
  62. public:
  63. LoopRotate(unsigned MaxHeaderSize, LoopInfo *LI,
  64. const TargetTransformInfo *TTI, AssumptionCache *AC,
  65. DominatorTree *DT, ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
  66. const SimplifyQuery &SQ, bool RotationOnly, bool IsUtilMode,
  67. bool PrepareForLTO)
  68. : MaxHeaderSize(MaxHeaderSize), LI(LI), TTI(TTI), AC(AC), DT(DT), SE(SE),
  69. MSSAU(MSSAU), SQ(SQ), RotationOnly(RotationOnly),
  70. IsUtilMode(IsUtilMode), PrepareForLTO(PrepareForLTO) {}
  71. bool processLoop(Loop *L);
  72. private:
  73. bool rotateLoop(Loop *L, bool SimplifiedLatch);
  74. bool simplifyLoopLatch(Loop *L);
  75. };
  76. } // end anonymous namespace
  77. /// Insert (K, V) pair into the ValueToValueMap, and verify the key did not
  78. /// previously exist in the map, and the value was inserted.
  79. static void InsertNewValueIntoMap(ValueToValueMapTy &VM, Value *K, Value *V) {
  80. bool Inserted = VM.insert({K, V}).second;
  81. assert(Inserted);
  82. (void)Inserted;
  83. }
  84. /// RewriteUsesOfClonedInstructions - We just cloned the instructions from the
  85. /// old header into the preheader. If there were uses of the values produced by
  86. /// these instruction that were outside of the loop, we have to insert PHI nodes
  87. /// to merge the two values. Do this now.
  88. static void RewriteUsesOfClonedInstructions(BasicBlock *OrigHeader,
  89. BasicBlock *OrigPreheader,
  90. ValueToValueMapTy &ValueMap,
  91. ScalarEvolution *SE,
  92. SmallVectorImpl<PHINode*> *InsertedPHIs) {
  93. // Remove PHI node entries that are no longer live.
  94. BasicBlock::iterator I, E = OrigHeader->end();
  95. for (I = OrigHeader->begin(); PHINode *PN = dyn_cast<PHINode>(I); ++I)
  96. PN->removeIncomingValue(PN->getBasicBlockIndex(OrigPreheader));
  97. // Now fix up users of the instructions in OrigHeader, inserting PHI nodes
  98. // as necessary.
  99. SSAUpdater SSA(InsertedPHIs);
  100. for (I = OrigHeader->begin(); I != E; ++I) {
  101. Value *OrigHeaderVal = &*I;
  102. // If there are no uses of the value (e.g. because it returns void), there
  103. // is nothing to rewrite.
  104. if (OrigHeaderVal->use_empty())
  105. continue;
  106. Value *OrigPreHeaderVal = ValueMap.lookup(OrigHeaderVal);
  107. // The value now exits in two versions: the initial value in the preheader
  108. // and the loop "next" value in the original header.
  109. SSA.Initialize(OrigHeaderVal->getType(), OrigHeaderVal->getName());
  110. // Force re-computation of OrigHeaderVal, as some users now need to use the
  111. // new PHI node.
  112. if (SE)
  113. SE->forgetValue(OrigHeaderVal);
  114. SSA.AddAvailableValue(OrigHeader, OrigHeaderVal);
  115. SSA.AddAvailableValue(OrigPreheader, OrigPreHeaderVal);
  116. // Visit each use of the OrigHeader instruction.
  117. for (Use &U : llvm::make_early_inc_range(OrigHeaderVal->uses())) {
  118. // SSAUpdater can't handle a non-PHI use in the same block as an
  119. // earlier def. We can easily handle those cases manually.
  120. Instruction *UserInst = cast<Instruction>(U.getUser());
  121. if (!isa<PHINode>(UserInst)) {
  122. BasicBlock *UserBB = UserInst->getParent();
  123. // The original users in the OrigHeader are already using the
  124. // original definitions.
  125. if (UserBB == OrigHeader)
  126. continue;
  127. // Users in the OrigPreHeader need to use the value to which the
  128. // original definitions are mapped.
  129. if (UserBB == OrigPreheader) {
  130. U = OrigPreHeaderVal;
  131. continue;
  132. }
  133. }
  134. // Anything else can be handled by SSAUpdater.
  135. SSA.RewriteUse(U);
  136. }
  137. // Replace MetadataAsValue(ValueAsMetadata(OrigHeaderVal)) uses in debug
  138. // intrinsics.
  139. SmallVector<DbgValueInst *, 1> DbgValues;
  140. llvm::findDbgValues(DbgValues, OrigHeaderVal);
  141. for (auto &DbgValue : DbgValues) {
  142. // The original users in the OrigHeader are already using the original
  143. // definitions.
  144. BasicBlock *UserBB = DbgValue->getParent();
  145. if (UserBB == OrigHeader)
  146. continue;
  147. // Users in the OrigPreHeader need to use the value to which the
  148. // original definitions are mapped and anything else can be handled by
  149. // the SSAUpdater. To avoid adding PHINodes, check if the value is
  150. // available in UserBB, if not substitute undef.
  151. Value *NewVal;
  152. if (UserBB == OrigPreheader)
  153. NewVal = OrigPreHeaderVal;
  154. else if (SSA.HasValueForBlock(UserBB))
  155. NewVal = SSA.GetValueInMiddleOfBlock(UserBB);
  156. else
  157. NewVal = UndefValue::get(OrigHeaderVal->getType());
  158. DbgValue->replaceVariableLocationOp(OrigHeaderVal, NewVal);
  159. }
  160. }
  161. }
  162. // Assuming both header and latch are exiting, look for a phi which is only
  163. // used outside the loop (via a LCSSA phi) in the exit from the header.
  164. // This means that rotating the loop can remove the phi.
  165. static bool profitableToRotateLoopExitingLatch(Loop *L) {
  166. BasicBlock *Header = L->getHeader();
  167. BranchInst *BI = dyn_cast<BranchInst>(Header->getTerminator());
  168. assert(BI && BI->isConditional() && "need header with conditional exit");
  169. BasicBlock *HeaderExit = BI->getSuccessor(0);
  170. if (L->contains(HeaderExit))
  171. HeaderExit = BI->getSuccessor(1);
  172. for (auto &Phi : Header->phis()) {
  173. // Look for uses of this phi in the loop/via exits other than the header.
  174. if (llvm::any_of(Phi.users(), [HeaderExit](const User *U) {
  175. return cast<Instruction>(U)->getParent() != HeaderExit;
  176. }))
  177. continue;
  178. return true;
  179. }
  180. return false;
  181. }
  182. // Check that latch exit is deoptimizing (which means - very unlikely to happen)
  183. // and there is another exit from the loop which is non-deoptimizing.
  184. // If we rotate latch to that exit our loop has a better chance of being fully
  185. // canonical.
  186. //
  187. // It can give false positives in some rare cases.
  188. static bool canRotateDeoptimizingLatchExit(Loop *L) {
  189. BasicBlock *Latch = L->getLoopLatch();
  190. assert(Latch && "need latch");
  191. BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
  192. // Need normal exiting latch.
  193. if (!BI || !BI->isConditional())
  194. return false;
  195. BasicBlock *Exit = BI->getSuccessor(1);
  196. if (L->contains(Exit))
  197. Exit = BI->getSuccessor(0);
  198. // Latch exit is non-deoptimizing, no need to rotate.
  199. if (!Exit->getPostdominatingDeoptimizeCall())
  200. return false;
  201. SmallVector<BasicBlock *, 4> Exits;
  202. L->getUniqueExitBlocks(Exits);
  203. if (!Exits.empty()) {
  204. // There is at least one non-deoptimizing exit.
  205. //
  206. // Note, that BasicBlock::getPostdominatingDeoptimizeCall is not exact,
  207. // as it can conservatively return false for deoptimizing exits with
  208. // complex enough control flow down to deoptimize call.
  209. //
  210. // That means here we can report success for a case where
  211. // all exits are deoptimizing but one of them has complex enough
  212. // control flow (e.g. with loops).
  213. //
  214. // That should be a very rare case and false positives for this function
  215. // have compile-time effect only.
  216. return any_of(Exits, [](const BasicBlock *BB) {
  217. return !BB->getPostdominatingDeoptimizeCall();
  218. });
  219. }
  220. return false;
  221. }
  222. /// Rotate loop LP. Return true if the loop is rotated.
  223. ///
  224. /// \param SimplifiedLatch is true if the latch was just folded into the final
  225. /// loop exit. In this case we may want to rotate even though the new latch is
  226. /// now an exiting branch. This rotation would have happened had the latch not
  227. /// been simplified. However, if SimplifiedLatch is false, then we avoid
  228. /// rotating loops in which the latch exits to avoid excessive or endless
  229. /// rotation. LoopRotate should be repeatable and converge to a canonical
  230. /// form. This property is satisfied because simplifying the loop latch can only
  231. /// happen once across multiple invocations of the LoopRotate pass.
  232. ///
  233. /// If -loop-rotate-multi is enabled we can do multiple rotations in one go
  234. /// so to reach a suitable (non-deoptimizing) exit.
  235. bool LoopRotate::rotateLoop(Loop *L, bool SimplifiedLatch) {
  236. // If the loop has only one block then there is not much to rotate.
  237. if (L->getBlocks().size() == 1)
  238. return false;
  239. bool Rotated = false;
  240. do {
  241. BasicBlock *OrigHeader = L->getHeader();
  242. BasicBlock *OrigLatch = L->getLoopLatch();
  243. BranchInst *BI = dyn_cast<BranchInst>(OrigHeader->getTerminator());
  244. if (!BI || BI->isUnconditional())
  245. return Rotated;
  246. // If the loop header is not one of the loop exiting blocks then
  247. // either this loop is already rotated or it is not
  248. // suitable for loop rotation transformations.
  249. if (!L->isLoopExiting(OrigHeader))
  250. return Rotated;
  251. // If the loop latch already contains a branch that leaves the loop then the
  252. // loop is already rotated.
  253. if (!OrigLatch)
  254. return Rotated;
  255. // Rotate if either the loop latch does *not* exit the loop, or if the loop
  256. // latch was just simplified. Or if we think it will be profitable.
  257. if (L->isLoopExiting(OrigLatch) && !SimplifiedLatch && IsUtilMode == false &&
  258. !profitableToRotateLoopExitingLatch(L) &&
  259. !canRotateDeoptimizingLatchExit(L))
  260. return Rotated;
  261. // Check size of original header and reject loop if it is very big or we can't
  262. // duplicate blocks inside it.
  263. {
  264. SmallPtrSet<const Value *, 32> EphValues;
  265. CodeMetrics::collectEphemeralValues(L, AC, EphValues);
  266. CodeMetrics Metrics;
  267. Metrics.analyzeBasicBlock(OrigHeader, *TTI, EphValues, PrepareForLTO);
  268. if (Metrics.notDuplicatable) {
  269. LLVM_DEBUG(
  270. dbgs() << "LoopRotation: NOT rotating - contains non-duplicatable"
  271. << " instructions: ";
  272. L->dump());
  273. return Rotated;
  274. }
  275. if (Metrics.convergent) {
  276. LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains convergent "
  277. "instructions: ";
  278. L->dump());
  279. return Rotated;
  280. }
  281. if (!Metrics.NumInsts.isValid()) {
  282. LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains instructions"
  283. " with invalid cost: ";
  284. L->dump());
  285. return Rotated;
  286. }
  287. if (Metrics.NumInsts > MaxHeaderSize) {
  288. LLVM_DEBUG(dbgs() << "LoopRotation: NOT rotating - contains "
  289. << Metrics.NumInsts
  290. << " instructions, which is more than the threshold ("
  291. << MaxHeaderSize << " instructions): ";
  292. L->dump());
  293. ++NumNotRotatedDueToHeaderSize;
  294. return Rotated;
  295. }
  296. // When preparing for LTO, avoid rotating loops with calls that could be
  297. // inlined during the LTO stage.
  298. if (PrepareForLTO && Metrics.NumInlineCandidates > 0)
  299. return Rotated;
  300. }
  301. // Now, this loop is suitable for rotation.
  302. BasicBlock *OrigPreheader = L->getLoopPreheader();
  303. // If the loop could not be converted to canonical form, it must have an
  304. // indirectbr in it, just give up.
  305. if (!OrigPreheader || !L->hasDedicatedExits())
  306. return Rotated;
  307. // Anything ScalarEvolution may know about this loop or the PHI nodes
  308. // in its header will soon be invalidated. We should also invalidate
  309. // all outer loops because insertion and deletion of blocks that happens
  310. // during the rotation may violate invariants related to backedge taken
  311. // infos in them.
  312. if (SE) {
  313. SE->forgetTopmostLoop(L);
  314. // We may hoist some instructions out of loop. In case if they were cached
  315. // as "loop variant" or "loop computable", these caches must be dropped.
  316. // We also may fold basic blocks, so cached block dispositions also need
  317. // to be dropped.
  318. SE->forgetBlockAndLoopDispositions();
  319. }
  320. LLVM_DEBUG(dbgs() << "LoopRotation: rotating "; L->dump());
  321. if (MSSAU && VerifyMemorySSA)
  322. MSSAU->getMemorySSA()->verifyMemorySSA();
  323. // Find new Loop header. NewHeader is a Header's one and only successor
  324. // that is inside loop. Header's other successor is outside the
  325. // loop. Otherwise loop is not suitable for rotation.
  326. BasicBlock *Exit = BI->getSuccessor(0);
  327. BasicBlock *NewHeader = BI->getSuccessor(1);
  328. if (L->contains(Exit))
  329. std::swap(Exit, NewHeader);
  330. assert(NewHeader && "Unable to determine new loop header");
  331. assert(L->contains(NewHeader) && !L->contains(Exit) &&
  332. "Unable to determine loop header and exit blocks");
  333. // This code assumes that the new header has exactly one predecessor.
  334. // Remove any single-entry PHI nodes in it.
  335. assert(NewHeader->getSinglePredecessor() &&
  336. "New header doesn't have one pred!");
  337. FoldSingleEntryPHINodes(NewHeader);
  338. // Begin by walking OrigHeader and populating ValueMap with an entry for
  339. // each Instruction.
  340. BasicBlock::iterator I = OrigHeader->begin(), E = OrigHeader->end();
  341. ValueToValueMapTy ValueMap, ValueMapMSSA;
  342. // For PHI nodes, the value available in OldPreHeader is just the
  343. // incoming value from OldPreHeader.
  344. for (; PHINode *PN = dyn_cast<PHINode>(I); ++I)
  345. InsertNewValueIntoMap(ValueMap, PN,
  346. PN->getIncomingValueForBlock(OrigPreheader));
  347. // For the rest of the instructions, either hoist to the OrigPreheader if
  348. // possible or create a clone in the OldPreHeader if not.
  349. Instruction *LoopEntryBranch = OrigPreheader->getTerminator();
  350. // Record all debug intrinsics preceding LoopEntryBranch to avoid
  351. // duplication.
  352. using DbgIntrinsicHash =
  353. std::pair<std::pair<hash_code, DILocalVariable *>, DIExpression *>;
  354. auto makeHash = [](DbgVariableIntrinsic *D) -> DbgIntrinsicHash {
  355. auto VarLocOps = D->location_ops();
  356. return {{hash_combine_range(VarLocOps.begin(), VarLocOps.end()),
  357. D->getVariable()},
  358. D->getExpression()};
  359. };
  360. SmallDenseSet<DbgIntrinsicHash, 8> DbgIntrinsics;
  361. for (Instruction &I : llvm::drop_begin(llvm::reverse(*OrigPreheader))) {
  362. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(&I))
  363. DbgIntrinsics.insert(makeHash(DII));
  364. else
  365. break;
  366. }
  367. // Remember the local noalias scope declarations in the header. After the
  368. // rotation, they must be duplicated and the scope must be cloned. This
  369. // avoids unwanted interaction across iterations.
  370. SmallVector<NoAliasScopeDeclInst *, 6> NoAliasDeclInstructions;
  371. for (Instruction &I : *OrigHeader)
  372. if (auto *Decl = dyn_cast<NoAliasScopeDeclInst>(&I))
  373. NoAliasDeclInstructions.push_back(Decl);
  374. while (I != E) {
  375. Instruction *Inst = &*I++;
  376. // If the instruction's operands are invariant and it doesn't read or write
  377. // memory, then it is safe to hoist. Doing this doesn't change the order of
  378. // execution in the preheader, but does prevent the instruction from
  379. // executing in each iteration of the loop. This means it is safe to hoist
  380. // something that might trap, but isn't safe to hoist something that reads
  381. // memory (without proving that the loop doesn't write).
  382. if (L->hasLoopInvariantOperands(Inst) && !Inst->mayReadFromMemory() &&
  383. !Inst->mayWriteToMemory() && !Inst->isTerminator() &&
  384. !isa<DbgInfoIntrinsic>(Inst) && !isa<AllocaInst>(Inst)) {
  385. Inst->moveBefore(LoopEntryBranch);
  386. ++NumInstrsHoisted;
  387. continue;
  388. }
  389. // Otherwise, create a duplicate of the instruction.
  390. Instruction *C = Inst->clone();
  391. ++NumInstrsDuplicated;
  392. // Eagerly remap the operands of the instruction.
  393. RemapInstruction(C, ValueMap,
  394. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  395. // Avoid inserting the same intrinsic twice.
  396. if (auto *DII = dyn_cast<DbgVariableIntrinsic>(C))
  397. if (DbgIntrinsics.count(makeHash(DII))) {
  398. C->deleteValue();
  399. continue;
  400. }
  401. // With the operands remapped, see if the instruction constant folds or is
  402. // otherwise simplifyable. This commonly occurs because the entry from PHI
  403. // nodes allows icmps and other instructions to fold.
  404. Value *V = simplifyInstruction(C, SQ);
  405. if (V && LI->replacementPreservesLCSSAForm(C, V)) {
  406. // If so, then delete the temporary instruction and stick the folded value
  407. // in the map.
  408. InsertNewValueIntoMap(ValueMap, Inst, V);
  409. if (!C->mayHaveSideEffects()) {
  410. C->deleteValue();
  411. C = nullptr;
  412. }
  413. } else {
  414. InsertNewValueIntoMap(ValueMap, Inst, C);
  415. }
  416. if (C) {
  417. // Otherwise, stick the new instruction into the new block!
  418. C->setName(Inst->getName());
  419. C->insertBefore(LoopEntryBranch);
  420. if (auto *II = dyn_cast<AssumeInst>(C))
  421. AC->registerAssumption(II);
  422. // MemorySSA cares whether the cloned instruction was inserted or not, and
  423. // not whether it can be remapped to a simplified value.
  424. if (MSSAU)
  425. InsertNewValueIntoMap(ValueMapMSSA, Inst, C);
  426. }
  427. }
  428. if (!NoAliasDeclInstructions.empty()) {
  429. // There are noalias scope declarations:
  430. // (general):
  431. // Original: OrigPre { OrigHeader NewHeader ... Latch }
  432. // after: (OrigPre+OrigHeader') { NewHeader ... Latch OrigHeader }
  433. //
  434. // with D: llvm.experimental.noalias.scope.decl,
  435. // U: !noalias or !alias.scope depending on D
  436. // ... { D U1 U2 } can transform into:
  437. // (0) : ... { D U1 U2 } // no relevant rotation for this part
  438. // (1) : ... D' { U1 U2 D } // D is part of OrigHeader
  439. // (2) : ... D' U1' { U2 D U1 } // D, U1 are part of OrigHeader
  440. //
  441. // We now want to transform:
  442. // (1) -> : ... D' { D U1 U2 D'' }
  443. // (2) -> : ... D' U1' { D U2 D'' U1'' }
  444. // D: original llvm.experimental.noalias.scope.decl
  445. // D', U1': duplicate with replaced scopes
  446. // D'', U1'': different duplicate with replaced scopes
  447. // This ensures a safe fallback to 'may_alias' introduced by the rotate,
  448. // as U1'' and U1' scopes will not be compatible wrt to the local restrict
  449. // Clone the llvm.experimental.noalias.decl again for the NewHeader.
  450. Instruction *NewHeaderInsertionPoint = &(*NewHeader->getFirstNonPHI());
  451. for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions) {
  452. LLVM_DEBUG(dbgs() << " Cloning llvm.experimental.noalias.scope.decl:"
  453. << *NAD << "\n");
  454. Instruction *NewNAD = NAD->clone();
  455. NewNAD->insertBefore(NewHeaderInsertionPoint);
  456. }
  457. // Scopes must now be duplicated, once for OrigHeader and once for
  458. // OrigPreHeader'.
  459. {
  460. auto &Context = NewHeader->getContext();
  461. SmallVector<MDNode *, 8> NoAliasDeclScopes;
  462. for (NoAliasScopeDeclInst *NAD : NoAliasDeclInstructions)
  463. NoAliasDeclScopes.push_back(NAD->getScopeList());
  464. LLVM_DEBUG(dbgs() << " Updating OrigHeader scopes\n");
  465. cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, {OrigHeader}, Context,
  466. "h.rot");
  467. LLVM_DEBUG(OrigHeader->dump());
  468. // Keep the compile time impact low by only adapting the inserted block
  469. // of instructions in the OrigPreHeader. This might result in slightly
  470. // more aliasing between these instructions and those that were already
  471. // present, but it will be much faster when the original PreHeader is
  472. // large.
  473. LLVM_DEBUG(dbgs() << " Updating part of OrigPreheader scopes\n");
  474. auto *FirstDecl =
  475. cast<Instruction>(ValueMap[*NoAliasDeclInstructions.begin()]);
  476. auto *LastInst = &OrigPreheader->back();
  477. cloneAndAdaptNoAliasScopes(NoAliasDeclScopes, FirstDecl, LastInst,
  478. Context, "pre.rot");
  479. LLVM_DEBUG(OrigPreheader->dump());
  480. LLVM_DEBUG(dbgs() << " Updated NewHeader:\n");
  481. LLVM_DEBUG(NewHeader->dump());
  482. }
  483. }
  484. // Along with all the other instructions, we just cloned OrigHeader's
  485. // terminator into OrigPreHeader. Fix up the PHI nodes in each of OrigHeader's
  486. // successors by duplicating their incoming values for OrigHeader.
  487. for (BasicBlock *SuccBB : successors(OrigHeader))
  488. for (BasicBlock::iterator BI = SuccBB->begin();
  489. PHINode *PN = dyn_cast<PHINode>(BI); ++BI)
  490. PN->addIncoming(PN->getIncomingValueForBlock(OrigHeader), OrigPreheader);
  491. // Now that OrigPreHeader has a clone of OrigHeader's terminator, remove
  492. // OrigPreHeader's old terminator (the original branch into the loop), and
  493. // remove the corresponding incoming values from the PHI nodes in OrigHeader.
  494. LoopEntryBranch->eraseFromParent();
  495. // Update MemorySSA before the rewrite call below changes the 1:1
  496. // instruction:cloned_instruction_or_value mapping.
  497. if (MSSAU) {
  498. InsertNewValueIntoMap(ValueMapMSSA, OrigHeader, OrigPreheader);
  499. MSSAU->updateForClonedBlockIntoPred(OrigHeader, OrigPreheader,
  500. ValueMapMSSA);
  501. }
  502. SmallVector<PHINode*, 2> InsertedPHIs;
  503. // If there were any uses of instructions in the duplicated block outside the
  504. // loop, update them, inserting PHI nodes as required
  505. RewriteUsesOfClonedInstructions(OrigHeader, OrigPreheader, ValueMap, SE,
  506. &InsertedPHIs);
  507. // Attach dbg.value intrinsics to the new phis if that phi uses a value that
  508. // previously had debug metadata attached. This keeps the debug info
  509. // up-to-date in the loop body.
  510. if (!InsertedPHIs.empty())
  511. insertDebugValuesForPHIs(OrigHeader, InsertedPHIs);
  512. // NewHeader is now the header of the loop.
  513. L->moveToHeader(NewHeader);
  514. assert(L->getHeader() == NewHeader && "Latch block is our new header");
  515. // Inform DT about changes to the CFG.
  516. if (DT) {
  517. // The OrigPreheader branches to the NewHeader and Exit now. Then, inform
  518. // the DT about the removed edge to the OrigHeader (that got removed).
  519. SmallVector<DominatorTree::UpdateType, 3> Updates;
  520. Updates.push_back({DominatorTree::Insert, OrigPreheader, Exit});
  521. Updates.push_back({DominatorTree::Insert, OrigPreheader, NewHeader});
  522. Updates.push_back({DominatorTree::Delete, OrigPreheader, OrigHeader});
  523. if (MSSAU) {
  524. MSSAU->applyUpdates(Updates, *DT, /*UpdateDT=*/true);
  525. if (VerifyMemorySSA)
  526. MSSAU->getMemorySSA()->verifyMemorySSA();
  527. } else {
  528. DT->applyUpdates(Updates);
  529. }
  530. }
  531. // At this point, we've finished our major CFG changes. As part of cloning
  532. // the loop into the preheader we've simplified instructions and the
  533. // duplicated conditional branch may now be branching on a constant. If it is
  534. // branching on a constant and if that constant means that we enter the loop,
  535. // then we fold away the cond branch to an uncond branch. This simplifies the
  536. // loop in cases important for nested loops, and it also means we don't have
  537. // to split as many edges.
  538. BranchInst *PHBI = cast<BranchInst>(OrigPreheader->getTerminator());
  539. assert(PHBI->isConditional() && "Should be clone of BI condbr!");
  540. if (!isa<ConstantInt>(PHBI->getCondition()) ||
  541. PHBI->getSuccessor(cast<ConstantInt>(PHBI->getCondition())->isZero()) !=
  542. NewHeader) {
  543. // The conditional branch can't be folded, handle the general case.
  544. // Split edges as necessary to preserve LoopSimplify form.
  545. // Right now OrigPreHeader has two successors, NewHeader and ExitBlock, and
  546. // thus is not a preheader anymore.
  547. // Split the edge to form a real preheader.
  548. BasicBlock *NewPH = SplitCriticalEdge(
  549. OrigPreheader, NewHeader,
  550. CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
  551. NewPH->setName(NewHeader->getName() + ".lr.ph");
  552. // Preserve canonical loop form, which means that 'Exit' should have only
  553. // one predecessor. Note that Exit could be an exit block for multiple
  554. // nested loops, causing both of the edges to now be critical and need to
  555. // be split.
  556. SmallVector<BasicBlock *, 4> ExitPreds(predecessors(Exit));
  557. bool SplitLatchEdge = false;
  558. for (BasicBlock *ExitPred : ExitPreds) {
  559. // We only need to split loop exit edges.
  560. Loop *PredLoop = LI->getLoopFor(ExitPred);
  561. if (!PredLoop || PredLoop->contains(Exit) ||
  562. isa<IndirectBrInst>(ExitPred->getTerminator()))
  563. continue;
  564. SplitLatchEdge |= L->getLoopLatch() == ExitPred;
  565. BasicBlock *ExitSplit = SplitCriticalEdge(
  566. ExitPred, Exit,
  567. CriticalEdgeSplittingOptions(DT, LI, MSSAU).setPreserveLCSSA());
  568. ExitSplit->moveBefore(Exit);
  569. }
  570. assert(SplitLatchEdge &&
  571. "Despite splitting all preds, failed to split latch exit?");
  572. (void)SplitLatchEdge;
  573. } else {
  574. // We can fold the conditional branch in the preheader, this makes things
  575. // simpler. The first step is to remove the extra edge to the Exit block.
  576. Exit->removePredecessor(OrigPreheader, true /*preserve LCSSA*/);
  577. BranchInst *NewBI = BranchInst::Create(NewHeader, PHBI);
  578. NewBI->setDebugLoc(PHBI->getDebugLoc());
  579. PHBI->eraseFromParent();
  580. // With our CFG finalized, update DomTree if it is available.
  581. if (DT) DT->deleteEdge(OrigPreheader, Exit);
  582. // Update MSSA too, if available.
  583. if (MSSAU)
  584. MSSAU->removeEdge(OrigPreheader, Exit);
  585. }
  586. assert(L->getLoopPreheader() && "Invalid loop preheader after loop rotation");
  587. assert(L->getLoopLatch() && "Invalid loop latch after loop rotation");
  588. if (MSSAU && VerifyMemorySSA)
  589. MSSAU->getMemorySSA()->verifyMemorySSA();
  590. // Now that the CFG and DomTree are in a consistent state again, try to merge
  591. // the OrigHeader block into OrigLatch. This will succeed if they are
  592. // connected by an unconditional branch. This is just a cleanup so the
  593. // emitted code isn't too gross in this common case.
  594. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  595. BasicBlock *PredBB = OrigHeader->getUniquePredecessor();
  596. bool DidMerge = MergeBlockIntoPredecessor(OrigHeader, &DTU, LI, MSSAU);
  597. if (DidMerge)
  598. RemoveRedundantDbgInstrs(PredBB);
  599. if (MSSAU && VerifyMemorySSA)
  600. MSSAU->getMemorySSA()->verifyMemorySSA();
  601. LLVM_DEBUG(dbgs() << "LoopRotation: into "; L->dump());
  602. ++NumRotated;
  603. Rotated = true;
  604. SimplifiedLatch = false;
  605. // Check that new latch is a deoptimizing exit and then repeat rotation if possible.
  606. // Deoptimizing latch exit is not a generally typical case, so we just loop over.
  607. // TODO: if it becomes a performance bottleneck extend rotation algorithm
  608. // to handle multiple rotations in one go.
  609. } while (MultiRotate && canRotateDeoptimizingLatchExit(L));
  610. return true;
  611. }
  612. /// Determine whether the instructions in this range may be safely and cheaply
  613. /// speculated. This is not an important enough situation to develop complex
  614. /// heuristics. We handle a single arithmetic instruction along with any type
  615. /// conversions.
  616. static bool shouldSpeculateInstrs(BasicBlock::iterator Begin,
  617. BasicBlock::iterator End, Loop *L) {
  618. bool seenIncrement = false;
  619. bool MultiExitLoop = false;
  620. if (!L->getExitingBlock())
  621. MultiExitLoop = true;
  622. for (BasicBlock::iterator I = Begin; I != End; ++I) {
  623. if (!isSafeToSpeculativelyExecute(&*I))
  624. return false;
  625. if (isa<DbgInfoIntrinsic>(I))
  626. continue;
  627. switch (I->getOpcode()) {
  628. default:
  629. return false;
  630. case Instruction::GetElementPtr:
  631. // GEPs are cheap if all indices are constant.
  632. if (!cast<GEPOperator>(I)->hasAllConstantIndices())
  633. return false;
  634. // fall-thru to increment case
  635. [[fallthrough]];
  636. case Instruction::Add:
  637. case Instruction::Sub:
  638. case Instruction::And:
  639. case Instruction::Or:
  640. case Instruction::Xor:
  641. case Instruction::Shl:
  642. case Instruction::LShr:
  643. case Instruction::AShr: {
  644. Value *IVOpnd =
  645. !isa<Constant>(I->getOperand(0))
  646. ? I->getOperand(0)
  647. : !isa<Constant>(I->getOperand(1)) ? I->getOperand(1) : nullptr;
  648. if (!IVOpnd)
  649. return false;
  650. // If increment operand is used outside of the loop, this speculation
  651. // could cause extra live range interference.
  652. if (MultiExitLoop) {
  653. for (User *UseI : IVOpnd->users()) {
  654. auto *UserInst = cast<Instruction>(UseI);
  655. if (!L->contains(UserInst))
  656. return false;
  657. }
  658. }
  659. if (seenIncrement)
  660. return false;
  661. seenIncrement = true;
  662. break;
  663. }
  664. case Instruction::Trunc:
  665. case Instruction::ZExt:
  666. case Instruction::SExt:
  667. // ignore type conversions
  668. break;
  669. }
  670. }
  671. return true;
  672. }
  673. /// Fold the loop tail into the loop exit by speculating the loop tail
  674. /// instructions. Typically, this is a single post-increment. In the case of a
  675. /// simple 2-block loop, hoisting the increment can be much better than
  676. /// duplicating the entire loop header. In the case of loops with early exits,
  677. /// rotation will not work anyway, but simplifyLoopLatch will put the loop in
  678. /// canonical form so downstream passes can handle it.
  679. ///
  680. /// I don't believe this invalidates SCEV.
  681. bool LoopRotate::simplifyLoopLatch(Loop *L) {
  682. BasicBlock *Latch = L->getLoopLatch();
  683. if (!Latch || Latch->hasAddressTaken())
  684. return false;
  685. BranchInst *Jmp = dyn_cast<BranchInst>(Latch->getTerminator());
  686. if (!Jmp || !Jmp->isUnconditional())
  687. return false;
  688. BasicBlock *LastExit = Latch->getSinglePredecessor();
  689. if (!LastExit || !L->isLoopExiting(LastExit))
  690. return false;
  691. BranchInst *BI = dyn_cast<BranchInst>(LastExit->getTerminator());
  692. if (!BI)
  693. return false;
  694. if (!shouldSpeculateInstrs(Latch->begin(), Jmp->getIterator(), L))
  695. return false;
  696. LLVM_DEBUG(dbgs() << "Folding loop latch " << Latch->getName() << " into "
  697. << LastExit->getName() << "\n");
  698. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  699. MergeBlockIntoPredecessor(Latch, &DTU, LI, MSSAU, nullptr,
  700. /*PredecessorWithTwoSuccessors=*/true);
  701. if (SE) {
  702. // Merging blocks may remove blocks reference in the block disposition cache. Clear the cache.
  703. SE->forgetBlockAndLoopDispositions();
  704. }
  705. if (MSSAU && VerifyMemorySSA)
  706. MSSAU->getMemorySSA()->verifyMemorySSA();
  707. return true;
  708. }
  709. /// Rotate \c L, and return true if any modification was made.
  710. bool LoopRotate::processLoop(Loop *L) {
  711. // Save the loop metadata.
  712. MDNode *LoopMD = L->getLoopID();
  713. bool SimplifiedLatch = false;
  714. // Simplify the loop latch before attempting to rotate the header
  715. // upward. Rotation may not be needed if the loop tail can be folded into the
  716. // loop exit.
  717. if (!RotationOnly)
  718. SimplifiedLatch = simplifyLoopLatch(L);
  719. bool MadeChange = rotateLoop(L, SimplifiedLatch);
  720. assert((!MadeChange || L->isLoopExiting(L->getLoopLatch())) &&
  721. "Loop latch should be exiting after loop-rotate.");
  722. // Restore the loop metadata.
  723. // NB! We presume LoopRotation DOESN'T ADD its own metadata.
  724. if ((MadeChange || SimplifiedLatch) && LoopMD)
  725. L->setLoopID(LoopMD);
  726. return MadeChange || SimplifiedLatch;
  727. }
  728. /// The utility to convert a loop into a loop with bottom test.
  729. bool llvm::LoopRotation(Loop *L, LoopInfo *LI, const TargetTransformInfo *TTI,
  730. AssumptionCache *AC, DominatorTree *DT,
  731. ScalarEvolution *SE, MemorySSAUpdater *MSSAU,
  732. const SimplifyQuery &SQ, bool RotationOnly = true,
  733. unsigned Threshold = unsigned(-1),
  734. bool IsUtilMode = true, bool PrepareForLTO) {
  735. LoopRotate LR(Threshold, LI, TTI, AC, DT, SE, MSSAU, SQ, RotationOnly,
  736. IsUtilMode, PrepareForLTO);
  737. return LR.processLoop(L);
  738. }