blob: 388553b178364e2728f1dbc781e18b8922e849a6 [file] [log] [blame]
Karthik Bhat76aa6622015-04-20 04:38:33 +00001//===-- 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
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000014#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth4a000882017-06-25 22:45:31 +000015#include "llvm/ADT/ScopeExit.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000016#include "llvm/Analysis/AliasAnalysis.h"
17#include "llvm/Analysis/BasicAliasAnalysis.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000018#include "llvm/Analysis/GlobalsModRef.h"
Philip Reamesa21d5f12018-03-15 21:04:28 +000019#include "llvm/Analysis/InstructionSimplify.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000020#include "llvm/Analysis/LoopInfo.h"
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +000021#include "llvm/Analysis/LoopPass.h"
Philip Reames23aed5e2018-03-20 22:45:23 +000022#include "llvm/Analysis/MustExecute.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000023#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000024#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000025#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000026#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000027#include "llvm/Analysis/TargetTransformInfo.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000028#include "llvm/Analysis/ValueTracking.h"
Chijun Sima21a8b602018-08-03 05:08:17 +000029#include "llvm/IR/DomTreeUpdater.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000030#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000031#include "llvm/IR/Instructions.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000032#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000033#include "llvm/IR/PatternMatch.h"
34#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000035#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000036#include "llvm/Support/Debug.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000037#include "llvm/Support/KnownBits.h"
Chandler Carruth4a000882017-06-25 22:45:31 +000038#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000039
40using namespace llvm;
41using namespace llvm::PatternMatch;
42
43#define DEBUG_TYPE "loop-utils"
44
Michael Kruse72448522018-12-12 17:32:52 +000045static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
46
Chandler Carruth4a000882017-06-25 22:45:31 +000047bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
48 bool PreserveLCSSA) {
49 bool Changed = false;
50
51 // We re-use a vector for the in-loop predecesosrs.
52 SmallVector<BasicBlock *, 4> InLoopPredecessors;
53
54 auto RewriteExit = [&](BasicBlock *BB) {
55 assert(InLoopPredecessors.empty() &&
56 "Must start with an empty predecessors list!");
57 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
58
59 // See if there are any non-loop predecessors of this exit block and
60 // keep track of the in-loop predecessors.
61 bool IsDedicatedExit = true;
62 for (auto *PredBB : predecessors(BB))
63 if (L->contains(PredBB)) {
64 if (isa<IndirectBrInst>(PredBB->getTerminator()))
65 // We cannot rewrite exiting edges from an indirectbr.
66 return false;
67
68 InLoopPredecessors.push_back(PredBB);
69 } else {
70 IsDedicatedExit = false;
71 }
72
73 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
74
75 // Nothing to do if this is already a dedicated exit.
76 if (IsDedicatedExit)
77 return false;
78
79 auto *NewExitBB = SplitBlockPredecessors(
Alina Sbirleaab6f84f72018-08-21 23:32:03 +000080 BB, InLoopPredecessors, ".loopexit", DT, LI, nullptr, PreserveLCSSA);
Chandler Carruth4a000882017-06-25 22:45:31 +000081
82 if (!NewExitBB)
Nicola Zaghend34e60c2018-05-14 12:53:11 +000083 LLVM_DEBUG(
84 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
85 << *L << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000086 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +000087 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
88 << NewExitBB->getName() << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000089 return true;
90 };
91
92 // Walk the exit blocks directly rather than building up a data structure for
93 // them, but only visit each one once.
94 SmallPtrSet<BasicBlock *, 4> Visited;
95 for (auto *BB : L->blocks())
96 for (auto *SuccBB : successors(BB)) {
97 // We're looking for exit blocks so skip in-loop successors.
98 if (L->contains(SuccBB))
99 continue;
100
101 // Visit each exit block exactly once.
102 if (!Visited.insert(SuccBB).second)
103 continue;
104
105 Changed |= RewriteExit(SuccBB);
106 }
107
108 return Changed;
109}
110
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000111/// Returns the instructions that use values defined in the loop.
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000112SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
113 SmallVector<Instruction *, 8> UsedOutside;
114
115 for (auto *Block : L->getBlocks())
116 // FIXME: I believe that this could use copy_if if the Inst reference could
117 // be adapted into a pointer.
118 for (auto &Inst : *Block) {
119 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000120 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000121 auto *Use = cast<Instruction>(U);
122 return !L->contains(Use->getParent());
123 }))
124 UsedOutside.push_back(&Inst);
125 }
126
127 return UsedOutside;
128}
Chandler Carruth31088a92016-02-19 10:45:18 +0000129
130void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
131 // By definition, all loop passes need the LoopInfo analysis and the
132 // Dominator tree it depends on. Because they all participate in the loop
133 // pass manager, they must also preserve these.
134 AU.addRequired<DominatorTreeWrapperPass>();
135 AU.addPreserved<DominatorTreeWrapperPass>();
136 AU.addRequired<LoopInfoWrapperPass>();
137 AU.addPreserved<LoopInfoWrapperPass>();
138
139 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
140 // here because users shouldn't directly get them from this header.
141 extern char &LoopSimplifyID;
142 extern char &LCSSAID;
143 AU.addRequiredID(LoopSimplifyID);
144 AU.addPreservedID(LoopSimplifyID);
145 AU.addRequiredID(LCSSAID);
146 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000147 // This is used in the LPPassManager to perform LCSSA verification on passes
148 // which preserve lcssa form
149 AU.addRequired<LCSSAVerificationPass>();
150 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000151
152 // Loop passes are designed to run inside of a loop pass manager which means
153 // that any function analyses they require must be required by the first loop
154 // pass in the manager (so that it is computed before the loop pass manager
155 // runs) and preserved by all loop pasess in the manager. To make this
156 // reasonably robust, the set needed for most loop passes is maintained here.
157 // If your loop pass requires an analysis not listed here, you will need to
158 // carefully audit the loop pass manager nesting structure that results.
159 AU.addRequired<AAResultsWrapperPass>();
160 AU.addPreserved<AAResultsWrapperPass>();
161 AU.addPreserved<BasicAAWrapperPass>();
162 AU.addPreserved<GlobalsAAWrapperPass>();
163 AU.addPreserved<SCEVAAWrapperPass>();
164 AU.addRequired<ScalarEvolutionWrapperPass>();
165 AU.addPreserved<ScalarEvolutionWrapperPass>();
166}
167
168/// Manually defined generic "LoopPass" dependency initialization. This is used
169/// to initialize the exact set of passes from above in \c
170/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
171/// with:
172///
173/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
174///
175/// As-if "LoopPass" were a pass.
176void llvm::initializeLoopPassPass(PassRegistry &Registry) {
177 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
178 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
179 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000180 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000181 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
182 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
183 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
184 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
185 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
186}
Adam Nemet963341c2016-04-21 17:33:17 +0000187
Michael Kruse72448522018-12-12 17:32:52 +0000188static Optional<MDNode *> findOptionMDForLoopID(MDNode *LoopID,
189 StringRef Name) {
Adam Nemetfe3def72016-04-22 19:10:05 +0000190 // Return none if LoopID is false.
Adam Nemet963341c2016-04-21 17:33:17 +0000191 if (!LoopID)
Adam Nemetfe3def72016-04-22 19:10:05 +0000192 return None;
Adam Nemet293be662016-04-21 17:33:20 +0000193
194 // First operand should refer to the loop id itself.
195 assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
196 assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
197
Adam Nemet963341c2016-04-21 17:33:17 +0000198 // Iterate over LoopID operands and look for MDString Metadata
199 for (unsigned i = 1, e = LoopID->getNumOperands(); i < e; ++i) {
200 MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
201 if (!MD)
202 continue;
203 MDString *S = dyn_cast<MDString>(MD->getOperand(0));
204 if (!S)
205 continue;
206 // Return true if MDString holds expected MetaData.
207 if (Name.equals(S->getString()))
Michael Kruse72448522018-12-12 17:32:52 +0000208 return MD;
Adam Nemet963341c2016-04-21 17:33:17 +0000209 }
Adam Nemetfe3def72016-04-22 19:10:05 +0000210 return None;
Adam Nemet963341c2016-04-21 17:33:17 +0000211}
Evgeniy Stepanov122f9842016-06-10 20:03:17 +0000212
Michael Kruse72448522018-12-12 17:32:52 +0000213static Optional<MDNode *> findOptionMDForLoop(const Loop *TheLoop,
214 StringRef Name) {
215 return findOptionMDForLoopID(TheLoop->getLoopID(), Name);
216}
217
218/// Find string metadata for loop
219///
220/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
221/// operand or null otherwise. If the string metadata is not found return
222/// Optional's not-a-value.
223Optional<const MDOperand *> llvm::findStringMetadataForLoop(Loop *TheLoop,
224 StringRef Name) {
225 auto MD = findOptionMDForLoop(TheLoop, Name).getValueOr(nullptr);
226 if (!MD)
227 return None;
228 switch (MD->getNumOperands()) {
229 case 1:
230 return nullptr;
231 case 2:
232 return &MD->getOperand(1);
233 default:
234 llvm_unreachable("loop metadata has 0 or 1 operand");
235 }
236}
237
238static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
239 StringRef Name) {
240 Optional<MDNode *> MD = findOptionMDForLoop(TheLoop, Name);
241 if (!MD.hasValue())
242 return None;
243 MDNode *OptionNode = MD.getValue();
244 if (OptionNode == nullptr)
245 return None;
246 switch (OptionNode->getNumOperands()) {
247 case 1:
248 // When the value is absent it is interpreted as 'attribute set'.
249 return true;
250 case 2:
251 return mdconst::extract_or_null<ConstantInt>(
252 OptionNode->getOperand(1).get());
253 }
254 llvm_unreachable("unexpected number of options");
255}
256
257static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
258 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
259}
260
261llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
262 StringRef Name) {
263 const MDOperand *AttrMD =
264 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
265 if (!AttrMD)
266 return None;
267
268 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
269 if (!IntMD)
270 return None;
271
272 return IntMD->getSExtValue();
273}
274
275Optional<MDNode *> llvm::makeFollowupLoopID(
276 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
277 const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
278 if (!OrigLoopID) {
279 if (AlwaysNew)
280 return nullptr;
281 return None;
282 }
283
284 assert(OrigLoopID->getOperand(0) == OrigLoopID);
285
286 bool InheritAllAttrs = !InheritOptionsExceptPrefix;
287 bool InheritSomeAttrs =
288 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
289 SmallVector<Metadata *, 8> MDs;
290 MDs.push_back(nullptr);
291
292 bool Changed = false;
293 if (InheritAllAttrs || InheritSomeAttrs) {
294 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
295 MDNode *Op = cast<MDNode>(Existing.get());
296
297 auto InheritThisAttribute = [InheritSomeAttrs,
298 InheritOptionsExceptPrefix](MDNode *Op) {
299 if (!InheritSomeAttrs)
300 return false;
301
302 // Skip malformatted attribute metadata nodes.
303 if (Op->getNumOperands() == 0)
304 return true;
305 Metadata *NameMD = Op->getOperand(0).get();
306 if (!isa<MDString>(NameMD))
307 return true;
308 StringRef AttrName = cast<MDString>(NameMD)->getString();
309
310 // Do not inherit excluded attributes.
311 return !AttrName.startswith(InheritOptionsExceptPrefix);
312 };
313
314 if (InheritThisAttribute(Op))
315 MDs.push_back(Op);
316 else
317 Changed = true;
318 }
319 } else {
320 // Modified if we dropped at least one attribute.
321 Changed = OrigLoopID->getNumOperands() > 1;
322 }
323
324 bool HasAnyFollowup = false;
325 for (StringRef OptionName : FollowupOptions) {
326 MDNode *FollowupNode =
327 findOptionMDForLoopID(OrigLoopID, OptionName).getValueOr(nullptr);
328 if (!FollowupNode)
329 continue;
330
331 HasAnyFollowup = true;
332 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
333 MDs.push_back(Option.get());
334 Changed = true;
335 }
336 }
337
338 // Attributes of the followup loop not specified explicity, so signal to the
339 // transformation pass to add suitable attributes.
340 if (!AlwaysNew && !HasAnyFollowup)
341 return None;
342
343 // If no attributes were added or remove, the previous loop Id can be reused.
344 if (!AlwaysNew && !Changed)
345 return OrigLoopID;
346
347 // No attributes is equivalent to having no !llvm.loop metadata at all.
348 if (MDs.size() == 1)
349 return nullptr;
350
351 // Build the new loop ID.
352 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
353 FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
354 return FollowupLoopID;
355}
356
357bool llvm::hasDisableAllTransformsHint(const Loop *L) {
358 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
359}
360
361TransformationMode llvm::hasUnrollTransformation(Loop *L) {
362 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
363 return TM_SuppressedByUser;
364
365 Optional<int> Count =
366 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
367 if (Count.hasValue())
368 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
369
370 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
371 return TM_ForcedByUser;
372
373 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
374 return TM_ForcedByUser;
375
376 if (hasDisableAllTransformsHint(L))
377 return TM_Disable;
378
379 return TM_Unspecified;
380}
381
382TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
383 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
384 return TM_SuppressedByUser;
385
386 Optional<int> Count =
387 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
388 if (Count.hasValue())
389 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
390
391 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
392 return TM_ForcedByUser;
393
394 if (hasDisableAllTransformsHint(L))
395 return TM_Disable;
396
397 return TM_Unspecified;
398}
399
400TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
401 Optional<bool> Enable =
402 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
403
404 if (Enable == false)
405 return TM_SuppressedByUser;
406
407 Optional<int> VectorizeWidth =
408 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
409 Optional<int> InterleaveCount =
410 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
411
412 if (Enable == true) {
413 // 'Forcing' vector width and interleave count to one effectively disables
414 // this tranformation.
415 if (VectorizeWidth == 1 && InterleaveCount == 1)
416 return TM_SuppressedByUser;
417 return TM_ForcedByUser;
418 }
419
420 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
421 return TM_Disable;
422
423 if (VectorizeWidth == 1 && InterleaveCount == 1)
424 return TM_Disable;
425
426 if (VectorizeWidth > 1 || InterleaveCount > 1)
427 return TM_Enable;
428
429 if (hasDisableAllTransformsHint(L))
430 return TM_Disable;
431
432 return TM_Unspecified;
433}
434
435TransformationMode llvm::hasDistributeTransformation(Loop *L) {
436 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
437 return TM_ForcedByUser;
438
439 if (hasDisableAllTransformsHint(L))
440 return TM_Disable;
441
442 return TM_Unspecified;
443}
444
445TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
446 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
447 return TM_SuppressedByUser;
448
449 if (hasDisableAllTransformsHint(L))
450 return TM_Disable;
451
452 return TM_Unspecified;
453}
454
Alina Sbirlea7ed58562017-09-15 00:04:16 +0000455/// Does a BFS from a given node to all of its children inside a given loop.
456/// The returned vector of nodes includes the starting point.
457SmallVector<DomTreeNode *, 16>
458llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
459 SmallVector<DomTreeNode *, 16> Worklist;
460 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
461 // Only include subregions in the top level loop.
462 BasicBlock *BB = DTN->getBlock();
463 if (CurLoop->contains(BB))
464 Worklist.push_back(DTN);
465 };
466
467 AddRegionToWorklist(N);
468
469 for (size_t I = 0; I < Worklist.size(); I++)
470 for (DomTreeNode *Child : Worklist[I]->getChildren())
471 AddRegionToWorklist(Child);
472
473 return Worklist;
474}
475
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000476void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
477 ScalarEvolution *SE = nullptr,
478 LoopInfo *LI = nullptr) {
Hans Wennborg899809d2017-10-04 21:14:07 +0000479 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000480 auto *Preheader = L->getLoopPreheader();
481 assert(Preheader && "Preheader should exist!");
482
483 // Now that we know the removal is safe, remove the loop by changing the
484 // branch from the preheader to go to the single exit block.
485 //
486 // Because we're deleting a large chunk of code at once, the sequence in which
487 // we remove things is very important to avoid invalidation issues.
488
489 // Tell ScalarEvolution that the loop is deleted. Do this before
490 // deleting the loop so that ScalarEvolution can look at the loop
491 // to determine what it needs to clean up.
492 if (SE)
493 SE->forgetLoop(L);
494
495 auto *ExitBlock = L->getUniqueExitBlock();
496 assert(ExitBlock && "Should have a unique exit block!");
497 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
498
499 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
500 assert(OldBr && "Preheader must end with a branch");
501 assert(OldBr->isUnconditional() && "Preheader must have a single successor");
502 // Connect the preheader to the exit block. Keep the old edge to the header
503 // around to perform the dominator tree update in two separate steps
504 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
505 // preheader -> header.
506 //
507 //
508 // 0. Preheader 1. Preheader 2. Preheader
509 // | | | |
510 // V | V |
511 // Header <--\ | Header <--\ | Header <--\
512 // | | | | | | | | | | |
513 // | V | | | V | | | V |
514 // | Body --/ | | Body --/ | | Body --/
515 // V V V V V
516 // Exit Exit Exit
517 //
518 // By doing this is two separate steps we can perform the dominator tree
519 // update without using the batch update API.
520 //
521 // Even when the loop is never executed, we cannot remove the edge from the
522 // source block to the exit block. Consider the case where the unexecuted loop
523 // branches back to an outer loop. If we deleted the loop and removed the edge
524 // coming to this inner loop, this will break the outer loop structure (by
525 // deleting the backedge of the outer loop). If the outer loop is indeed a
526 // non-loop, it will be deleted in a future iteration of loop deletion pass.
527 IRBuilder<> Builder(OldBr);
528 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
529 // Remove the old branch. The conditional branch becomes a new terminator.
530 OldBr->eraseFromParent();
531
532 // Rewrite phis in the exit block to get their inputs from the Preheader
533 // instead of the exiting block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000534 for (PHINode &P : ExitBlock->phis()) {
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000535 // Set the zero'th element of Phi to be from the preheader and remove all
536 // other incoming values. Given the loop has dedicated exits, all other
537 // incoming values must be from the exiting blocks.
538 int PredIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000539 P.setIncomingBlock(PredIndex, Preheader);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000540 // Removes all incoming values from all other exiting blocks (including
541 // duplicate values from an exiting block).
542 // Nuke all entries except the zero'th entry which is the preheader entry.
543 // NOTE! We need to remove Incoming Values in the reverse order as done
544 // below, to keep the indices valid for deletion (removeIncomingValues
545 // updates getNumIncomingValues and shifts all values down into the operand
546 // being deleted).
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000547 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
548 P.removeIncomingValue(e - i, false);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000549
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000550 assert((P.getNumIncomingValues() == 1 &&
551 P.getIncomingBlock(PredIndex) == Preheader) &&
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000552 "Should have exactly one value and that's from the preheader!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000553 }
554
555 // Disconnect the loop body by branching directly to its exit.
556 Builder.SetInsertPoint(Preheader->getTerminator());
557 Builder.CreateBr(ExitBlock);
558 // Remove the old branch.
559 Preheader->getTerminator()->eraseFromParent();
560
Chijun Sima21a8b602018-08-03 05:08:17 +0000561 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000562 if (DT) {
563 // Update the dominator tree by informing it about the new edge from the
564 // preheader to the exit.
Chijun Sima21a8b602018-08-03 05:08:17 +0000565 DTU.insertEdge(Preheader, ExitBlock);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000566 // Inform the dominator tree about the removed edge.
Chijun Sima21a8b602018-08-03 05:08:17 +0000567 DTU.deleteEdge(Preheader, L->getHeader());
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000568 }
569
Serguei Katkova757d652018-01-12 07:24:43 +0000570 // Given LCSSA form is satisfied, we should not have users of instructions
571 // within the dead loop outside of the loop. However, LCSSA doesn't take
572 // unreachable uses into account. We handle them here.
573 // We could do it after drop all references (in this case all users in the
574 // loop will be already eliminated and we have less work to do but according
575 // to API doc of User::dropAllReferences only valid operation after dropping
576 // references, is deletion. So let's substitute all usages of
577 // instruction from the loop with undef value of corresponding type first.
578 for (auto *Block : L->blocks())
579 for (Instruction &I : *Block) {
580 auto *Undef = UndefValue::get(I.getType());
581 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
582 Use &U = *UI;
583 ++UI;
584 if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
585 if (L->contains(Usr->getParent()))
586 continue;
587 // If we have a DT then we can check that uses outside a loop only in
588 // unreachable block.
589 if (DT)
590 assert(!DT->isReachableFromEntry(U) &&
591 "Unexpected user in reachable block");
592 U.set(Undef);
593 }
594 }
595
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000596 // Remove the block from the reference counting scheme, so that we can
597 // delete it freely later.
598 for (auto *Block : L->blocks())
599 Block->dropAllReferences();
600
601 if (LI) {
602 // Erase the instructions and the blocks without having to worry
603 // about ordering because we already dropped the references.
604 // NOTE: This iteration is safe because erasing the block does not remove
605 // its entry from the loop's block list. We do that in the next section.
606 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
607 LpI != LpE; ++LpI)
608 (*LpI)->eraseFromParent();
609
610 // Finally, the blocks from loopinfo. This has to happen late because
611 // otherwise our loop iterators won't work.
612
613 SmallPtrSet<BasicBlock *, 8> blocks;
614 blocks.insert(L->block_begin(), L->block_end());
615 for (BasicBlock *BB : blocks)
616 LI->removeBlock(BB);
617
618 // The last step is to update LoopInfo now that we've eliminated this loop.
619 LI->erase(L);
620 }
621}
622
Dehao Chen41d72a82016-11-17 01:17:02 +0000623Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
624 // Only support loops with a unique exiting block, and a latch.
625 if (!L->getExitingBlock())
626 return None;
627
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000628 // Get the branch weights for the loop's backedge.
Dehao Chen41d72a82016-11-17 01:17:02 +0000629 BranchInst *LatchBR =
630 dyn_cast<BranchInst>(L->getLoopLatch()->getTerminator());
631 if (!LatchBR || LatchBR->getNumSuccessors() != 2)
632 return None;
633
634 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
635 LatchBR->getSuccessor(1) == L->getHeader()) &&
636 "At least one edge out of the latch must go to the header");
637
638 // To estimate the number of times the loop body was executed, we want to
639 // know the number of times the backedge was taken, vs. the number of times
640 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +0000641 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000642 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +0000643 return None;
644
Michael Kupersteinb151a642016-11-30 21:13:57 +0000645 if (!TrueVal || !FalseVal)
646 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +0000647
Michael Kupersteinb151a642016-11-30 21:13:57 +0000648 // Divide the count of the backedge by the count of the edge exiting the loop,
649 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +0000650 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +0000651 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000652 else
Michael Kupersteinb151a642016-11-30 21:13:57 +0000653 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000654}
Amara Emersoncf9daa32017-05-09 10:43:25 +0000655
David Green6cb64782018-08-15 10:59:41 +0000656bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
657 ScalarEvolution &SE) {
David Green395b80c2018-08-11 06:57:28 +0000658 Loop *OuterL = InnerLoop->getParentLoop();
659 if (!OuterL)
660 return true;
661
662 // Get the backedge taken count for the inner loop
663 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
664 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
665 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
666 !InnerLoopBECountSC->getType()->isIntegerTy())
667 return false;
668
669 // Get whether count is invariant to the outer loop
670 ScalarEvolution::LoopDisposition LD =
671 SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
672 if (LD != ScalarEvolution::LoopInvariant)
673 return false;
674
675 return true;
676}
677
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000678/// Adds a 'fast' flag to floating point operations.
Amara Emersoncf9daa32017-05-09 10:43:25 +0000679static Value *addFastMathFlag(Value *V) {
680 if (isa<FPMathOperator>(V)) {
681 FastMathFlags Flags;
Sanjay Patel629c4112017-11-06 16:27:15 +0000682 Flags.setFast();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000683 cast<Instruction>(V)->setFastMathFlags(Flags);
684 }
685 return V;
686}
687
Vikram TV6594dc32018-09-10 05:05:08 +0000688Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
689 RecurrenceDescriptor::MinMaxRecurrenceKind RK,
690 Value *Left, Value *Right) {
691 CmpInst::Predicate P = CmpInst::ICMP_NE;
692 switch (RK) {
693 default:
694 llvm_unreachable("Unknown min/max recurrence kind");
695 case RecurrenceDescriptor::MRK_UIntMin:
696 P = CmpInst::ICMP_ULT;
697 break;
698 case RecurrenceDescriptor::MRK_UIntMax:
699 P = CmpInst::ICMP_UGT;
700 break;
701 case RecurrenceDescriptor::MRK_SIntMin:
702 P = CmpInst::ICMP_SLT;
703 break;
704 case RecurrenceDescriptor::MRK_SIntMax:
705 P = CmpInst::ICMP_SGT;
706 break;
707 case RecurrenceDescriptor::MRK_FloatMin:
708 P = CmpInst::FCMP_OLT;
709 break;
710 case RecurrenceDescriptor::MRK_FloatMax:
711 P = CmpInst::FCMP_OGT;
712 break;
713 }
714
715 // We only match FP sequences that are 'fast', so we can unconditionally
716 // set it on any generated instructions.
717 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
718 FastMathFlags FMF;
719 FMF.setFast();
720 Builder.setFastMathFlags(FMF);
721
722 Value *Cmp;
723 if (RK == RecurrenceDescriptor::MRK_FloatMin ||
724 RK == RecurrenceDescriptor::MRK_FloatMax)
725 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
726 else
727 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
728
729 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
730 return Select;
731}
732
Simon Pilgrim23c21822018-04-09 15:44:20 +0000733// Helper to generate an ordered reduction.
734Value *
735llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
736 unsigned Op,
737 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
738 ArrayRef<Value *> RedOps) {
739 unsigned VF = Src->getType()->getVectorNumElements();
740
741 // Extract and apply reduction ops in ascending order:
742 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
743 Value *Result = Acc;
744 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
745 Value *Ext =
746 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
747
748 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
749 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
750 "bin.rdx");
751 } else {
752 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
753 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000754 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
Simon Pilgrim23c21822018-04-09 15:44:20 +0000755 }
756
757 if (!RedOps.empty())
758 propagateIRFlags(Result, RedOps);
759 }
760
761 return Result;
762}
763
Amara Emersoncf9daa32017-05-09 10:43:25 +0000764// Helper to generate a log2 shuffle reduction.
Amara Emerson836b0f42017-05-10 09:42:49 +0000765Value *
766llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
767 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
768 ArrayRef<Value *> RedOps) {
Amara Emersoncf9daa32017-05-09 10:43:25 +0000769 unsigned VF = Src->getType()->getVectorNumElements();
770 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
771 // and vector ops, reducing the set of values being computed by half each
772 // round.
773 assert(isPowerOf2_32(VF) &&
774 "Reduction emission only supported for pow2 vectors!");
775 Value *TmpVec = Src;
776 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
777 for (unsigned i = VF; i != 1; i >>= 1) {
778 // Move the upper half of the vector to the lower half.
779 for (unsigned j = 0; j != i / 2; ++j)
780 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
781
782 // Fill the rest of the mask with undef.
783 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
784 UndefValue::get(Builder.getInt32Ty()));
785
786 Value *Shuf = Builder.CreateShuffleVector(
787 TmpVec, UndefValue::get(TmpVec->getType()),
788 ConstantVector::get(ShuffleMask), "rdx.shuf");
789
790 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
791 // Floating point operations had to be 'fast' to enable the reduction.
792 TmpVec = addFastMathFlag(Builder.CreateBinOp((Instruction::BinaryOps)Op,
793 TmpVec, Shuf, "bin.rdx"));
794 } else {
795 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
796 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000797 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000798 }
799 if (!RedOps.empty())
800 propagateIRFlags(TmpVec, RedOps);
801 }
802 // The result is in the first element of the vector.
803 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
804}
805
806/// Create a simple vector reduction specified by an opcode and some
807/// flags (if generating min/max reductions).
808Value *llvm::createSimpleTargetReduction(
809 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
810 Value *Src, TargetTransformInfo::ReductionFlags Flags,
811 ArrayRef<Value *> RedOps) {
812 assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
813
814 Value *ScalarUdf = UndefValue::get(Src->getType()->getVectorElementType());
Vikram TV7e98d692018-09-12 01:59:43 +0000815 std::function<Value *()> BuildFunc;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000816 using RD = RecurrenceDescriptor;
817 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
818 // TODO: Support creating ordered reductions.
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000819 FastMathFlags FMFFast;
820 FMFFast.setFast();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000821
822 switch (Opcode) {
823 case Instruction::Add:
824 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
825 break;
826 case Instruction::Mul:
827 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
828 break;
829 case Instruction::And:
830 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
831 break;
832 case Instruction::Or:
833 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
834 break;
835 case Instruction::Xor:
836 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
837 break;
838 case Instruction::FAdd:
839 BuildFunc = [&]() {
840 auto Rdx = Builder.CreateFAddReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000841 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000842 return Rdx;
843 };
844 break;
845 case Instruction::FMul:
846 BuildFunc = [&]() {
847 auto Rdx = Builder.CreateFMulReduce(ScalarUdf, Src);
Sanjay Patel1ea7b6f2017-12-06 19:11:23 +0000848 cast<CallInst>(Rdx)->setFastMathFlags(FMFFast);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000849 return Rdx;
850 };
851 break;
852 case Instruction::ICmp:
853 if (Flags.IsMaxOp) {
854 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
855 BuildFunc = [&]() {
856 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
857 };
858 } else {
859 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
860 BuildFunc = [&]() {
861 return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
862 };
863 }
864 break;
865 case Instruction::FCmp:
866 if (Flags.IsMaxOp) {
867 MinMaxKind = RD::MRK_FloatMax;
868 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
869 } else {
870 MinMaxKind = RD::MRK_FloatMin;
871 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
872 }
873 break;
874 default:
875 llvm_unreachable("Unhandled opcode");
876 break;
877 }
878 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
879 return BuildFunc();
880 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
881}
882
883/// Create a vector reduction using a given recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000884Value *llvm::createTargetReduction(IRBuilder<> &B,
Amara Emersoncf9daa32017-05-09 10:43:25 +0000885 const TargetTransformInfo *TTI,
886 RecurrenceDescriptor &Desc, Value *Src,
887 bool NoNaN) {
888 // TODO: Support in-order reductions based on the recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000889 using RD = RecurrenceDescriptor;
890 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000891 TargetTransformInfo::ReductionFlags Flags;
892 Flags.NoNaN = NoNaN;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000893 switch (RecKind) {
Sanjay Patel3e069f52017-12-06 19:37:00 +0000894 case RD::RK_FloatAdd:
895 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
896 case RD::RK_FloatMult:
897 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
898 case RD::RK_IntegerAdd:
899 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
900 case RD::RK_IntegerMult:
901 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
902 case RD::RK_IntegerAnd:
903 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
904 case RD::RK_IntegerOr:
905 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
906 case RD::RK_IntegerXor:
907 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
908 case RD::RK_IntegerMinMax: {
909 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
910 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
911 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
912 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000913 }
Sanjay Patel3e069f52017-12-06 19:37:00 +0000914 case RD::RK_FloatMinMax: {
915 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
916 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000917 }
918 default:
919 llvm_unreachable("Unhandled RecKind");
920 }
921}
922
Dinar Temirbulatova61f4b82017-07-19 10:02:07 +0000923void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
924 auto *VecOp = dyn_cast<Instruction>(I);
925 if (!VecOp)
926 return;
927 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
928 : dyn_cast<Instruction>(OpValue);
929 if (!Intersection)
930 return;
931 const unsigned Opcode = Intersection->getOpcode();
932 VecOp->copyIRFlags(Intersection);
933 for (auto *V : VL) {
934 auto *Instr = dyn_cast<Instruction>(V);
935 if (!Instr)
936 continue;
937 if (OpValue == nullptr || Opcode == Instr->getOpcode())
938 VecOp->andIRFlags(V);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000939 }
940}