LoopUtils.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. //===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
  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 defines common loop utility functions.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/LoopUtils.h"
  14. #include "llvm/ADT/ScopeExit.h"
  15. #include "llvm/Analysis/AliasAnalysis.h"
  16. #include "llvm/Analysis/BasicAliasAnalysis.h"
  17. #include "llvm/Analysis/GlobalsModRef.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/Analysis/LoopInfo.h"
  20. #include "llvm/Analysis/LoopPass.h"
  21. #include "llvm/Analysis/MustExecute.h"
  22. #include "llvm/Analysis/ScalarEvolution.h"
  23. #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
  24. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  25. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  26. #include "llvm/Analysis/TargetTransformInfo.h"
  27. #include "llvm/Analysis/ValueTracking.h"
  28. #include "llvm/IR/DIBuilder.h"
  29. #include "llvm/IR/DomTreeUpdater.h"
  30. #include "llvm/IR/Dominators.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/Module.h"
  34. #include "llvm/IR/PatternMatch.h"
  35. #include "llvm/IR/ValueHandle.h"
  36. #include "llvm/Pass.h"
  37. #include "llvm/Support/Debug.h"
  38. #include "llvm/Support/KnownBits.h"
  39. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  40. using namespace llvm;
  41. using namespace llvm::PatternMatch;
  42. #define DEBUG_TYPE "loop-utils"
  43. static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
  44. bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
  45. bool PreserveLCSSA) {
  46. bool Changed = false;
  47. // We re-use a vector for the in-loop predecesosrs.
  48. SmallVector<BasicBlock *, 4> InLoopPredecessors;
  49. auto RewriteExit = [&](BasicBlock *BB) {
  50. assert(InLoopPredecessors.empty() &&
  51. "Must start with an empty predecessors list!");
  52. auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
  53. // See if there are any non-loop predecessors of this exit block and
  54. // keep track of the in-loop predecessors.
  55. bool IsDedicatedExit = true;
  56. for (auto *PredBB : predecessors(BB))
  57. if (L->contains(PredBB)) {
  58. if (isa<IndirectBrInst>(PredBB->getTerminator()))
  59. // We cannot rewrite exiting edges from an indirectbr.
  60. return false;
  61. InLoopPredecessors.push_back(PredBB);
  62. } else {
  63. IsDedicatedExit = false;
  64. }
  65. assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
  66. // Nothing to do if this is already a dedicated exit.
  67. if (IsDedicatedExit)
  68. return false;
  69. auto *NewExitBB = SplitBlockPredecessors(
  70. BB, InLoopPredecessors, ".loopexit", DT, LI, nullptr, PreserveLCSSA);
  71. if (!NewExitBB)
  72. LLVM_DEBUG(
  73. dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
  74. << *L << "\n");
  75. else
  76. LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
  77. << NewExitBB->getName() << "\n");
  78. return true;
  79. };
  80. // Walk the exit blocks directly rather than building up a data structure for
  81. // them, but only visit each one once.
  82. SmallPtrSet<BasicBlock *, 4> Visited;
  83. for (auto *BB : L->blocks())
  84. for (auto *SuccBB : successors(BB)) {
  85. // We're looking for exit blocks so skip in-loop successors.
  86. if (L->contains(SuccBB))
  87. continue;
  88. // Visit each exit block exactly once.
  89. if (!Visited.insert(SuccBB).second)
  90. continue;
  91. Changed |= RewriteExit(SuccBB);
  92. }
  93. return Changed;
  94. }
  95. /// Returns the instructions that use values defined in the loop.
  96. SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
  97. SmallVector<Instruction *, 8> UsedOutside;
  98. for (auto *Block : L->getBlocks())
  99. // FIXME: I believe that this could use copy_if if the Inst reference could
  100. // be adapted into a pointer.
  101. for (auto &Inst : *Block) {
  102. auto Users = Inst.users();
  103. if (any_of(Users, [&](User *U) {
  104. auto *Use = cast<Instruction>(U);
  105. return !L->contains(Use->getParent());
  106. }))
  107. UsedOutside.push_back(&Inst);
  108. }
  109. return UsedOutside;
  110. }
  111. void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
  112. // By definition, all loop passes need the LoopInfo analysis and the
  113. // Dominator tree it depends on. Because they all participate in the loop
  114. // pass manager, they must also preserve these.
  115. AU.addRequired<DominatorTreeWrapperPass>();
  116. AU.addPreserved<DominatorTreeWrapperPass>();
  117. AU.addRequired<LoopInfoWrapperPass>();
  118. AU.addPreserved<LoopInfoWrapperPass>();
  119. // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
  120. // here because users shouldn't directly get them from this header.
  121. extern char &LoopSimplifyID;
  122. extern char &LCSSAID;
  123. AU.addRequiredID(LoopSimplifyID);
  124. AU.addPreservedID(LoopSimplifyID);
  125. AU.addRequiredID(LCSSAID);
  126. AU.addPreservedID(LCSSAID);
  127. // This is used in the LPPassManager to perform LCSSA verification on passes
  128. // which preserve lcssa form
  129. AU.addRequired<LCSSAVerificationPass>();
  130. AU.addPreserved<LCSSAVerificationPass>();
  131. // Loop passes are designed to run inside of a loop pass manager which means
  132. // that any function analyses they require must be required by the first loop
  133. // pass in the manager (so that it is computed before the loop pass manager
  134. // runs) and preserved by all loop pasess in the manager. To make this
  135. // reasonably robust, the set needed for most loop passes is maintained here.
  136. // If your loop pass requires an analysis not listed here, you will need to
  137. // carefully audit the loop pass manager nesting structure that results.
  138. AU.addRequired<AAResultsWrapperPass>();
  139. AU.addPreserved<AAResultsWrapperPass>();
  140. AU.addPreserved<BasicAAWrapperPass>();
  141. AU.addPreserved<GlobalsAAWrapperPass>();
  142. AU.addPreserved<SCEVAAWrapperPass>();
  143. AU.addRequired<ScalarEvolutionWrapperPass>();
  144. AU.addPreserved<ScalarEvolutionWrapperPass>();
  145. }
  146. /// Manually defined generic "LoopPass" dependency initialization. This is used
  147. /// to initialize the exact set of passes from above in \c
  148. /// getLoopAnalysisUsage. It can be used within a loop pass's initialization
  149. /// with:
  150. ///
  151. /// INITIALIZE_PASS_DEPENDENCY(LoopPass)
  152. ///
  153. /// As-if "LoopPass" were a pass.
  154. void llvm::initializeLoopPassPass(PassRegistry &Registry) {
  155. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  156. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  157. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  158. INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
  159. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  160. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  161. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  162. INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
  163. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  164. }
  165. /// Find string metadata for loop
  166. ///
  167. /// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
  168. /// operand or null otherwise. If the string metadata is not found return
  169. /// Optional's not-a-value.
  170. Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
  171. StringRef Name) {
  172. MDNode *MD = findOptionMDForLoop(TheLoop, Name);
  173. if (!MD)
  174. return None;
  175. switch (MD->getNumOperands()) {
  176. case 1:
  177. return nullptr;
  178. case 2:
  179. return &MD->getOperand(1);
  180. default:
  181. llvm_unreachable("loop metadata has 0 or 1 operand");
  182. }
  183. }
  184. static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
  185. StringRef Name) {
  186. MDNode *MD = findOptionMDForLoop(TheLoop, Name);
  187. if (!MD)
  188. return None;
  189. switch (MD->getNumOperands()) {
  190. case 1:
  191. // When the value is absent it is interpreted as 'attribute set'.
  192. return true;
  193. case 2:
  194. return mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get());
  195. }
  196. llvm_unreachable("unexpected number of options");
  197. }
  198. static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
  199. return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
  200. }
  201. llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
  202. StringRef Name) {
  203. const MDOperand *AttrMD =
  204. findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
  205. if (!AttrMD)
  206. return None;
  207. ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
  208. if (!IntMD)
  209. return None;
  210. return IntMD->getSExtValue();
  211. }
  212. Optional<MDNode *> llvm::makeFollowupLoopID(
  213. MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
  214. const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
  215. if (!OrigLoopID) {
  216. if (AlwaysNew)
  217. return nullptr;
  218. return None;
  219. }
  220. assert(OrigLoopID->getOperand(0) == OrigLoopID);
  221. bool InheritAllAttrs = !InheritOptionsExceptPrefix;
  222. bool InheritSomeAttrs =
  223. InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
  224. SmallVector<Metadata *, 8> MDs;
  225. MDs.push_back(nullptr);
  226. bool Changed = false;
  227. if (InheritAllAttrs || InheritSomeAttrs) {
  228. for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
  229. MDNode *Op = cast<MDNode>(Existing.get());
  230. auto InheritThisAttribute = [InheritSomeAttrs,
  231. InheritOptionsExceptPrefix](MDNode *Op) {
  232. if (!InheritSomeAttrs)
  233. return false;
  234. // Skip malformatted attribute metadata nodes.
  235. if (Op->getNumOperands() == 0)
  236. return true;
  237. Metadata *NameMD = Op->getOperand(0).get();
  238. if (!isa<MDString>(NameMD))
  239. return true;
  240. StringRef AttrName = cast<MDString>(NameMD)->getString();
  241. // Do not inherit excluded attributes.
  242. return !AttrName.startswith(InheritOptionsExceptPrefix);
  243. };
  244. if (InheritThisAttribute(Op))
  245. MDs.push_back(Op);
  246. else
  247. Changed = true;
  248. }
  249. } else {
  250. // Modified if we dropped at least one attribute.
  251. Changed = OrigLoopID->getNumOperands() > 1;
  252. }
  253. bool HasAnyFollowup = false;
  254. for (StringRef OptionName : FollowupOptions) {
  255. MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
  256. if (!FollowupNode)
  257. continue;
  258. HasAnyFollowup = true;
  259. for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
  260. MDs.push_back(Option.get());
  261. Changed = true;
  262. }
  263. }
  264. // Attributes of the followup loop not specified explicity, so signal to the
  265. // transformation pass to add suitable attributes.
  266. if (!AlwaysNew && !HasAnyFollowup)
  267. return None;
  268. // If no attributes were added or remove, the previous loop Id can be reused.
  269. if (!AlwaysNew && !Changed)
  270. return OrigLoopID;
  271. // No attributes is equivalent to having no !llvm.loop metadata at all.
  272. if (MDs.size() == 1)
  273. return nullptr;
  274. // Build the new loop ID.
  275. MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
  276. FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
  277. return FollowupLoopID;
  278. }
  279. bool llvm::hasDisableAllTransformsHint(const Loop *L) {
  280. return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
  281. }
  282. TransformationMode llvm::hasUnrollTransformation(Loop *L) {
  283. if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
  284. return TM_SuppressedByUser;
  285. Optional<int> Count =
  286. getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
  287. if (Count.hasValue())
  288. return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
  289. if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
  290. return TM_ForcedByUser;
  291. if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
  292. return TM_ForcedByUser;
  293. if (hasDisableAllTransformsHint(L))
  294. return TM_Disable;
  295. return TM_Unspecified;
  296. }
  297. TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
  298. if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
  299. return TM_SuppressedByUser;
  300. Optional<int> Count =
  301. getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
  302. if (Count.hasValue())
  303. return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
  304. if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
  305. return TM_ForcedByUser;
  306. if (hasDisableAllTransformsHint(L))
  307. return TM_Disable;
  308. return TM_Unspecified;
  309. }
  310. TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
  311. Optional<bool> Enable =
  312. getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
  313. if (Enable == false)
  314. return TM_SuppressedByUser;
  315. Optional<int> VectorizeWidth =
  316. getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
  317. Optional<int> InterleaveCount =
  318. getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
  319. if (Enable == true) {
  320. // 'Forcing' vector width and interleave count to one effectively disables
  321. // this tranformation.
  322. if (VectorizeWidth == 1 && InterleaveCount == 1)
  323. return TM_SuppressedByUser;
  324. return TM_ForcedByUser;
  325. }
  326. if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
  327. return TM_Disable;
  328. if (VectorizeWidth == 1 && InterleaveCount == 1)
  329. return TM_Disable;
  330. if (VectorizeWidth > 1 || InterleaveCount > 1)
  331. return TM_Enable;
  332. if (hasDisableAllTransformsHint(L))
  333. return TM_Disable;
  334. return TM_Unspecified;
  335. }
  336. TransformationMode llvm::hasDistributeTransformation(Loop *L) {
  337. if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
  338. return TM_ForcedByUser;
  339. if (hasDisableAllTransformsHint(L))
  340. return TM_Disable;
  341. return TM_Unspecified;
  342. }
  343. TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
  344. if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
  345. return TM_SuppressedByUser;
  346. if (hasDisableAllTransformsHint(L))
  347. return TM_Disable;
  348. return TM_Unspecified;
  349. }
  350. /// Does a BFS from a given node to all of its children inside a given loop.
  351. /// The returned vector of nodes includes the starting point.
  352. SmallVector<DomTreeNode *, 16>
  353. llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
  354. SmallVector<DomTreeNode *, 16> Worklist;
  355. auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
  356. // Only include subregions in the top level loop.
  357. BasicBlock *BB = DTN->getBlock();
  358. if (CurLoop->contains(BB))
  359. Worklist.push_back(DTN);
  360. };
  361. AddRegionToWorklist(N);
  362. for (size_t I = 0; I < Worklist.size(); I++)
  363. for (DomTreeNode *Child : Worklist[I]->getChildren())
  364. AddRegionToWorklist(Child);
  365. return Worklist;
  366. }
  367. void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
  368. ScalarEvolution *SE = nullptr,
  369. LoopInfo *LI = nullptr) {
  370. assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
  371. auto *Preheader = L->getLoopPreheader();
  372. assert(Preheader && "Preheader should exist!");
  373. // Now that we know the removal is safe, remove the loop by changing the
  374. // branch from the preheader to go to the single exit block.
  375. //
  376. // Because we're deleting a large chunk of code at once, the sequence in which
  377. // we remove things is very important to avoid invalidation issues.
  378. // Tell ScalarEvolution that the loop is deleted. Do this before
  379. // deleting the loop so that ScalarEvolution can look at the loop
  380. // to determine what it needs to clean up.
  381. if (SE)
  382. SE->forgetLoop(L);
  383. auto *ExitBlock = L->getUniqueExitBlock();
  384. assert(ExitBlock && "Should have a unique exit block!");
  385. assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
  386. auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
  387. assert(OldBr && "Preheader must end with a branch");
  388. assert(OldBr->isUnconditional() && "Preheader must have a single successor");
  389. // Connect the preheader to the exit block. Keep the old edge to the header
  390. // around to perform the dominator tree update in two separate steps
  391. // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
  392. // preheader -> header.
  393. //
  394. //
  395. // 0. Preheader 1. Preheader 2. Preheader
  396. // | | | |
  397. // V | V |
  398. // Header <--\ | Header <--\ | Header <--\
  399. // | | | | | | | | | | |
  400. // | V | | | V | | | V |
  401. // | Body --/ | | Body --/ | | Body --/
  402. // V V V V V
  403. // Exit Exit Exit
  404. //
  405. // By doing this is two separate steps we can perform the dominator tree
  406. // update without using the batch update API.
  407. //
  408. // Even when the loop is never executed, we cannot remove the edge from the
  409. // source block to the exit block. Consider the case where the unexecuted loop
  410. // branches back to an outer loop. If we deleted the loop and removed the edge
  411. // coming to this inner loop, this will break the outer loop structure (by
  412. // deleting the backedge of the outer loop). If the outer loop is indeed a
  413. // non-loop, it will be deleted in a future iteration of loop deletion pass.
  414. IRBuilder<> Builder(OldBr);
  415. Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
  416. // Remove the old branch. The conditional branch becomes a new terminator.
  417. OldBr->eraseFromParent();
  418. // Rewrite phis in the exit block to get their inputs from the Preheader
  419. // instead of the exiting block.
  420. for (PHINode &P : ExitBlock->phis()) {
  421. // Set the zero'th element of Phi to be from the preheader and remove all
  422. // other incoming values. Given the loop has dedicated exits, all other
  423. // incoming values must be from the exiting blocks.
  424. int PredIndex = 0;
  425. P.setIncomingBlock(PredIndex, Preheader);
  426. // Removes all incoming values from all other exiting blocks (including
  427. // duplicate values from an exiting block).
  428. // Nuke all entries except the zero'th entry which is the preheader entry.
  429. // NOTE! We need to remove Incoming Values in the reverse order as done
  430. // below, to keep the indices valid for deletion (removeIncomingValues
  431. // updates getNumIncomingValues and shifts all values down into the operand
  432. // being deleted).
  433. for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
  434. P.removeIncomingValue(e - i, false);
  435. assert((P.getNumIncomingValues() == 1 &&
  436. P.getIncomingBlock(PredIndex) == Preheader) &&
  437. "Should have exactly one value and that's from the preheader!");
  438. }
  439. // Disconnect the loop body by branching directly to its exit.
  440. Builder.SetInsertPoint(Preheader->getTerminator());
  441. Builder.CreateBr(ExitBlock);
  442. // Remove the old branch.
  443. Preheader->getTerminator()->eraseFromParent();
  444. DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
  445. if (DT) {
  446. // Update the dominator tree by informing it about the new edge from the
  447. // preheader to the exit.
  448. DTU.insertEdge(Preheader, ExitBlock);
  449. // Inform the dominator tree about the removed edge.
  450. DTU.deleteEdge(Preheader, L->getHeader());
  451. }
  452. // Use a map to unique and a vector to guarantee deterministic ordering.
  453. llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
  454. llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
  455. // Given LCSSA form is satisfied, we should not have users of instructions
  456. // within the dead loop outside of the loop. However, LCSSA doesn't take
  457. // unreachable uses into account. We handle them here.
  458. // We could do it after drop all references (in this case all users in the
  459. // loop will be already eliminated and we have less work to do but according
  460. // to API doc of User::dropAllReferences only valid operation after dropping
  461. // references, is deletion. So let's substitute all usages of
  462. // instruction from the loop with undef value of corresponding type first.
  463. for (auto *Block : L->blocks())
  464. for (Instruction &I : *Block) {
  465. auto *Undef = UndefValue::get(I.getType());
  466. for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
  467. Use &U = *UI;
  468. ++UI;
  469. if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
  470. if (L->contains(Usr->getParent()))
  471. continue;
  472. // If we have a DT then we can check that uses outside a loop only in
  473. // unreachable block.
  474. if (DT)
  475. assert(!DT->isReachableFromEntry(U) &&
  476. "Unexpected user in reachable block");
  477. U.set(Undef);
  478. }
  479. auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
  480. if (!DVI)
  481. continue;
  482. auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
  483. if (Key != DeadDebugSet.end())
  484. continue;
  485. DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
  486. DeadDebugInst.push_back(DVI);
  487. }
  488. // After the loop has been deleted all the values defined and modified
  489. // inside the loop are going to be unavailable.
  490. // Since debug values in the loop have been deleted, inserting an undef
  491. // dbg.value truncates the range of any dbg.value before the loop where the
  492. // loop used to be. This is particularly important for constant values.
  493. DIBuilder DIB(*ExitBlock->getModule());
  494. for (auto *DVI : DeadDebugInst)
  495. DIB.insertDbgValueIntrinsic(
  496. UndefValue::get(Builder.getInt32Ty()), DVI->getVariable(),
  497. DVI->getExpression(), DVI->getDebugLoc(), ExitBlock->getFirstNonPHI());
  498. // Remove the block from the reference counting scheme, so that we can
  499. // delete it freely later.
  500. for (auto *Block : L->blocks())
  501. Block->dropAllReferences();
  502. if (LI) {
  503. // Erase the instructions and the blocks without having to worry
  504. // about ordering because we already dropped the references.
  505. // NOTE: This iteration is safe because erasing the block does not remove
  506. // its entry from the loop's block list. We do that in the next section.
  507. for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
  508. LpI != LpE; ++LpI)
  509. (*LpI)->eraseFromParent();
  510. // Finally, the blocks from loopinfo. This has to happen late because
  511. // otherwise our loop iterators won't work.
  512. SmallPtrSet<BasicBlock *, 8> blocks;
  513. blocks.insert(L->block_begin(), L->block_end());
  514. for (BasicBlock *BB : blocks)
  515. LI->removeBlock(BB);
  516. // The last step is to update LoopInfo now that we've eliminated this loop.
  517. LI->erase(L);
  518. }
  519. }
  520. Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
  521. // Only support loops with a unique exiting block, and a latch.
  522. if (!L->getExitingBlock())
  523. return None;
  524. // Get the branch weights for the loop's backedge.
  525. BranchInst *LatchBR =
  526. dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
  527. if (!LatchBR || LatchBR->getNumSuccessors() != 2)
  528. return None;
  529. assert((LatchBR->getSuccessor(0) == L->getHeader() ||
  530. LatchBR->getSuccessor(1) == L->getHeader()) &&
  531. "At least one edge out of the latch must go to the header");
  532. // To estimate the number of times the loop body was executed, we want to
  533. // know the number of times the backedge was taken, vs. the number of times
  534. // we exited the loop.
  535. uint64_t TrueVal, FalseVal;
  536. if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
  537. return None;
  538. if (!TrueVal || !FalseVal)
  539. return 0;
  540. // Divide the count of the backedge by the count of the edge exiting the loop,
  541. // rounding to nearest.
  542. if (LatchBR->getSuccessor(0) == L->getHeader())
  543. return (TrueVal + (FalseVal / 2)) / FalseVal;
  544. else
  545. return (FalseVal + (TrueVal / 2)) / TrueVal;
  546. }
  547. bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
  548. ScalarEvolution &SE) {
  549. Loop *OuterL = InnerLoop->getParentLoop();
  550. if (!OuterL)
  551. return true;
  552. // Get the backedge taken count for the inner loop
  553. BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
  554. const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
  555. if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
  556. !InnerLoopBECountSC->getType()->isIntegerTy())
  557. return false;
  558. // Get whether count is invariant to the outer loop
  559. ScalarEvolution::LoopDisposition LD =
  560. SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
  561. if (LD != ScalarEvolution::LoopInvariant)
  562. return false;
  563. return true;
  564. }
  565. /// Adds a 'fast' flag to floating point operations.
  566. static Value *addFastMathFlag(Value *V) {
  567. if (isa<FPMathOperator>(V)) {
  568. FastMathFlags Flags;
  569. Flags.setFast();
  570. cast<Instruction>(V)->setFastMathFlags(Flags);
  571. }
  572. return V;
  573. }
  574. Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
  575. RecurrenceDescriptor::MinMaxRecurrenceKind RK,
  576. Value *Left, Value *Right) {
  577. CmpInst::Predicate P = CmpInst::ICMP_NE;
  578. switch (RK) {
  579. default:
  580. llvm_unreachable("Unknown min/max recurrence kind");
  581. case RecurrenceDescriptor::MRK_UIntMin:
  582. P = CmpInst::ICMP_ULT;
  583. break;
  584. case RecurrenceDescriptor::MRK_UIntMax:
  585. P = CmpInst::ICMP_UGT;
  586. break;
  587. case RecurrenceDescriptor::MRK_SIntMin:
  588. P = CmpInst::ICMP_SLT;
  589. break;
  590. case RecurrenceDescriptor::MRK_SIntMax:
  591. P = CmpInst::ICMP_SGT;
  592. break;
  593. case RecurrenceDescriptor::MRK_FloatMin:
  594. P = CmpInst::FCMP_OLT;
  595. break;
  596. case RecurrenceDescriptor::MRK_FloatMax:
  597. P = CmpInst::FCMP_OGT;
  598. break;
  599. }
  600. // We only match FP sequences that are 'fast', so we can unconditionally
  601. // set it on any generated instructions.
  602. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  603. FastMathFlags FMF;
  604. FMF.setFast();
  605. Builder.setFastMathFlags(FMF);
  606. Value *Cmp;
  607. if (RK == RecurrenceDescriptor::MRK_FloatMin ||
  608. RK == RecurrenceDescriptor::MRK_FloatMax)
  609. Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
  610. else
  611. Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
  612. Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
  613. return Select;
  614. }
  615. // Helper to generate an ordered reduction.
  616. Value *
  617. llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
  618. unsigned Op,
  619. RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
  620. ArrayRef<Value *> RedOps) {
  621. unsigned VF = Src->getType()->getVectorNumElements();
  622. // Extract and apply reduction ops in ascending order:
  623. // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
  624. Value *Result = Acc;
  625. for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
  626. Value *Ext =
  627. Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
  628. if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
  629. Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
  630. "bin.rdx");
  631. } else {
  632. assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
  633. "Invalid min/max");
  634. Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
  635. }
  636. if (!RedOps.empty())
  637. propagateIRFlags(Result, RedOps);
  638. }
  639. return Result;
  640. }
  641. // Helper to generate a log2 shuffle reduction.
  642. Value *
  643. llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
  644. RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
  645. ArrayRef<Value *> RedOps) {
  646. unsigned VF = Src->getType()->getVectorNumElements();
  647. // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
  648. // and vector ops, reducing the set of values being computed by half each
  649. // round.
  650. assert(isPowerOf2_32(VF) &&
  651. "Reduction emission only supported for pow2 vectors!");
  652. Value *TmpVec = Src;
  653. SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
  654. for (unsigned i = VF; i != 1; i >>= 1) {
  655. // Move the upper half of the vector to the lower half.
  656. for (unsigned j = 0; j != i / 2; ++j)
  657. ShuffleMask[j] = Builder.getInt32(i / 2 + j);
  658. // Fill the rest of the mask with undef.
  659. std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
  660. UndefValue::get(Builder.getInt32Ty()));
  661. Value *Shuf = Builder.CreateShuffleVector(
  662. TmpVec, UndefValue::get(TmpVec->getType()),
  663. ConstantVector::get(ShuffleMask), "rdx.shuf");
  664. if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
  665. // Floating point operations had to be 'fast' to enable the reduction.
  666. TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
  667. TmpVec, Shuf, "bin.rdx"));
  668. } else {
  669. assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
  670. "Invalid min/max");
  671. TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
  672. }
  673. if (!RedOps.empty())
  674. propagateIRFlags(TmpVec, RedOps);
  675. }
  676. // The result is in the first element of the vector.
  677. return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
  678. }
  679. /// Create a simple vector reduction specified by an opcode and some
  680. /// flags (if generating min/max reductions).
  681. Value *llvm::createSimpleTargetReduction(
  682. IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
  683. Value *Src, TargetTransformInfo::ReductionFlags Flags,
  684. ArrayRef<Value *> RedOps) {
  685. assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
  686. Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
  687. std::function<Value *()> BuildFunc;
  688. using RD = RecurrenceDescriptor;
  689. RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
  690. // TODO: Support creating ordered reductions.
  691. FastMathFlags FMFFast;
  692. FMFFast.setFast();
  693. switch (Opcode) {
  694. case Instruction::Add:
  695. BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
  696. break;
  697. case Instruction::Mul:
  698. BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
  699. break;
  700. case Instruction::And:
  701. BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
  702. break;
  703. case Instruction::Or:
  704. BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
  705. break;
  706. case Instruction::Xor:
  707. BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
  708. break;
  709. case Instruction::FAdd:
  710. BuildFunc = [&]() {
  711. auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
  712. cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
  713. return Rdx;
  714. };
  715. break;
  716. case Instruction::FMul:
  717. BuildFunc = [&]() {
  718. auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
  719. cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
  720. return Rdx;
  721. };
  722. break;
  723. case Instruction::ICmp:
  724. if (Flags.IsMaxOp) {
  725. MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
  726. BuildFunc = [&]() {
  727. return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
  728. };
  729. } else {
  730. MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
  731. BuildFunc = [&]() {
  732. return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
  733. };
  734. }
  735. break;
  736. case Instruction::FCmp:
  737. if (Flags.IsMaxOp) {
  738. MinMaxKind = RD::MRK_FloatMax;
  739. BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
  740. } else {
  741. MinMaxKind = RD::MRK_FloatMin;
  742. BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
  743. }
  744. break;
  745. default:
  746. llvm_unreachable("Unhandled opcode");
  747. break;
  748. }
  749. if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
  750. return BuildFunc();
  751. return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
  752. }
  753. /// Create a vector reduction using a given recurrence descriptor.
  754. Value *llvm::createTargetReduction(IRBuilder<> &B,
  755. const TargetTransformInfo *TTI,
  756. RecurrenceDescriptor &Desc, Value *Src,
  757. bool NoNaN) {
  758. // TODO: Support in-order reductions based on the recurrence descriptor.
  759. using RD = RecurrenceDescriptor;
  760. RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
  761. TargetTransformInfo::ReductionFlags Flags;
  762. Flags.NoNaN = NoNaN;
  763. switch (RecKind) {
  764. case RD::RK_FloatAdd:
  765. return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
  766. case RD::RK_FloatMult:
  767. return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
  768. case RD::RK_IntegerAdd:
  769. return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
  770. case RD::RK_IntegerMult:
  771. return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
  772. case RD::RK_IntegerAnd:
  773. return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
  774. case RD::RK_IntegerOr:
  775. return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
  776. case RD::RK_IntegerXor:
  777. return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
  778. case RD::RK_IntegerMinMax: {
  779. RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
  780. Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
  781. Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
  782. return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
  783. }
  784. case RD::RK_FloatMinMax: {
  785. Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
  786. return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
  787. }
  788. default:
  789. llvm_unreachable("Unhandled RecKind");
  790. }
  791. }
  792. void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
  793. auto *VecOp = dyn_cast<Instruction>(I);
  794. if (!VecOp)
  795. return;
  796. auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
  797. : dyn_cast<Instruction>(OpValue);
  798. if (!Intersection)
  799. return;
  800. const unsigned Opcode = Intersection->getOpcode();
  801. VecOp->copyIRFlags(Intersection);
  802. for (auto *V : VL) {
  803. auto *Instr = dyn_cast<Instruction>(V);
  804. if (!Instr)
  805. continue;
  806. if (OpValue == nullptr || Opcode == Instr->getOpcode())
  807. VecOp->andIRFlags(V);
  808. }
  809. }