blob: fef10352482ca3699bc6e5c613f98f10361578bb [file] [log] [blame]
Karthik Bhat76aa6622015-04-20 04:38:33 +00001//===-- LoopUtils.cpp - Loop Utility functions -------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Karthik Bhat76aa6622015-04-20 04:38:33 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines common loop utility functions.
10//
11//===----------------------------------------------------------------------===//
12
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000013#include "llvm/Transforms/Utils/LoopUtils.h"
Chandler Carruth4a000882017-06-25 22:45:31 +000014#include "llvm/ADT/ScopeExit.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000015#include "llvm/Analysis/AliasAnalysis.h"
16#include "llvm/Analysis/BasicAliasAnalysis.h"
Richard Trieu5f436fc2019-02-06 02:52:52 +000017#include "llvm/Analysis/DomTreeUpdater.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"
Alina Sbirlea97468e92019-02-21 21:13:34 +000022#include "llvm/Analysis/MemorySSAUpdater.h"
Philip Reames23aed5e2018-03-20 22:45:23 +000023#include "llvm/Analysis/MustExecute.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000024#include "llvm/Analysis/ScalarEvolution.h"
Adam Nemet2f2bd8c2016-07-26 17:52:02 +000025#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
Elena Demikhovskyc434d092016-05-10 07:33:35 +000026#include "llvm/Analysis/ScalarEvolutionExpander.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000027#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000028#include "llvm/Analysis/TargetTransformInfo.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000029#include "llvm/Analysis/ValueTracking.h"
Davide Italiano744c3c32018-12-12 23:32:35 +000030#include "llvm/IR/DIBuilder.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000031#include "llvm/IR/Dominators.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000032#include "llvm/IR/Instructions.h"
Davide Italiano744c3c32018-12-12 23:32:35 +000033#include "llvm/IR/IntrinsicInst.h"
Weiming Zhao45d4cb92015-11-24 18:57:06 +000034#include "llvm/IR/Module.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000035#include "llvm/IR/PatternMatch.h"
36#include "llvm/IR/ValueHandle.h"
Chandler Carruth31088a92016-02-19 10:45:18 +000037#include "llvm/Pass.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000038#include "llvm/Support/Debug.h"
Chad Rosiera097bc62018-02-04 15:42:24 +000039#include "llvm/Support/KnownBits.h"
Chandler Carruth4a000882017-06-25 22:45:31 +000040#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Karthik Bhat76aa6622015-04-20 04:38:33 +000041
42using namespace llvm;
43using namespace llvm::PatternMatch;
44
45#define DEBUG_TYPE "loop-utils"
46
Michael Kruse72448522018-12-12 17:32:52 +000047static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced";
48
Chandler Carruth4a000882017-06-25 22:45:31 +000049bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI,
Alina Sbirlea97468e92019-02-21 21:13:34 +000050 MemorySSAUpdater *MSSAU,
Chandler Carruth4a000882017-06-25 22:45:31 +000051 bool PreserveLCSSA) {
52 bool Changed = false;
53
54 // We re-use a vector for the in-loop predecesosrs.
55 SmallVector<BasicBlock *, 4> InLoopPredecessors;
56
57 auto RewriteExit = [&](BasicBlock *BB) {
58 assert(InLoopPredecessors.empty() &&
59 "Must start with an empty predecessors list!");
60 auto Cleanup = make_scope_exit([&] { InLoopPredecessors.clear(); });
61
62 // See if there are any non-loop predecessors of this exit block and
63 // keep track of the in-loop predecessors.
64 bool IsDedicatedExit = true;
65 for (auto *PredBB : predecessors(BB))
66 if (L->contains(PredBB)) {
67 if (isa<IndirectBrInst>(PredBB->getTerminator()))
68 // We cannot rewrite exiting edges from an indirectbr.
69 return false;
Craig Topper784929d2019-02-08 20:48:56 +000070 if (isa<CallBrInst>(PredBB->getTerminator()))
71 // We cannot rewrite exiting edges from a callbr.
72 return false;
Chandler Carruth4a000882017-06-25 22:45:31 +000073
74 InLoopPredecessors.push_back(PredBB);
75 } else {
76 IsDedicatedExit = false;
77 }
78
79 assert(!InLoopPredecessors.empty() && "Must have *some* loop predecessor!");
80
81 // Nothing to do if this is already a dedicated exit.
82 if (IsDedicatedExit)
83 return false;
84
85 auto *NewExitBB = SplitBlockPredecessors(
Alina Sbirlea97468e92019-02-21 21:13:34 +000086 BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA);
Chandler Carruth4a000882017-06-25 22:45:31 +000087
88 if (!NewExitBB)
Nicola Zaghend34e60c2018-05-14 12:53:11 +000089 LLVM_DEBUG(
90 dbgs() << "WARNING: Can't create a dedicated exit block for loop: "
91 << *L << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000092 else
Nicola Zaghend34e60c2018-05-14 12:53:11 +000093 LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block "
94 << NewExitBB->getName() << "\n");
Chandler Carruth4a000882017-06-25 22:45:31 +000095 return true;
96 };
97
98 // Walk the exit blocks directly rather than building up a data structure for
99 // them, but only visit each one once.
100 SmallPtrSet<BasicBlock *, 4> Visited;
101 for (auto *BB : L->blocks())
102 for (auto *SuccBB : successors(BB)) {
103 // We're looking for exit blocks so skip in-loop successors.
104 if (L->contains(SuccBB))
105 continue;
106
107 // Visit each exit block exactly once.
108 if (!Visited.insert(SuccBB).second)
109 continue;
110
111 Changed |= RewriteExit(SuccBB);
112 }
113
114 return Changed;
115}
116
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000117/// Returns the instructions that use values defined in the loop.
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000118SmallVector<Instruction *, 8> llvm::findDefsUsedOutsideOfLoop(Loop *L) {
119 SmallVector<Instruction *, 8> UsedOutside;
120
121 for (auto *Block : L->getBlocks())
122 // FIXME: I believe that this could use copy_if if the Inst reference could
123 // be adapted into a pointer.
124 for (auto &Inst : *Block) {
125 auto Users = Inst.users();
David Majnemer0a16c222016-08-11 21:15:00 +0000126 if (any_of(Users, [&](User *U) {
Ashutosh Nemac5b7b552015-08-19 05:40:42 +0000127 auto *Use = cast<Instruction>(U);
128 return !L->contains(Use->getParent());
129 }))
130 UsedOutside.push_back(&Inst);
131 }
132
133 return UsedOutside;
134}
Chandler Carruth31088a92016-02-19 10:45:18 +0000135
136void llvm::getLoopAnalysisUsage(AnalysisUsage &AU) {
137 // By definition, all loop passes need the LoopInfo analysis and the
138 // Dominator tree it depends on. Because they all participate in the loop
139 // pass manager, they must also preserve these.
140 AU.addRequired<DominatorTreeWrapperPass>();
141 AU.addPreserved<DominatorTreeWrapperPass>();
142 AU.addRequired<LoopInfoWrapperPass>();
143 AU.addPreserved<LoopInfoWrapperPass>();
144
145 // We must also preserve LoopSimplify and LCSSA. We locally access their IDs
146 // here because users shouldn't directly get them from this header.
147 extern char &LoopSimplifyID;
148 extern char &LCSSAID;
149 AU.addRequiredID(LoopSimplifyID);
150 AU.addPreservedID(LoopSimplifyID);
151 AU.addRequiredID(LCSSAID);
152 AU.addPreservedID(LCSSAID);
Igor Laevskyc3ccf5d2016-10-28 12:57:20 +0000153 // This is used in the LPPassManager to perform LCSSA verification on passes
154 // which preserve lcssa form
155 AU.addRequired<LCSSAVerificationPass>();
156 AU.addPreserved<LCSSAVerificationPass>();
Chandler Carruth31088a92016-02-19 10:45:18 +0000157
158 // Loop passes are designed to run inside of a loop pass manager which means
159 // that any function analyses they require must be required by the first loop
160 // pass in the manager (so that it is computed before the loop pass manager
161 // runs) and preserved by all loop pasess in the manager. To make this
162 // reasonably robust, the set needed for most loop passes is maintained here.
163 // If your loop pass requires an analysis not listed here, you will need to
164 // carefully audit the loop pass manager nesting structure that results.
165 AU.addRequired<AAResultsWrapperPass>();
166 AU.addPreserved<AAResultsWrapperPass>();
167 AU.addPreserved<BasicAAWrapperPass>();
168 AU.addPreserved<GlobalsAAWrapperPass>();
169 AU.addPreserved<SCEVAAWrapperPass>();
170 AU.addRequired<ScalarEvolutionWrapperPass>();
171 AU.addPreserved<ScalarEvolutionWrapperPass>();
172}
173
174/// Manually defined generic "LoopPass" dependency initialization. This is used
175/// to initialize the exact set of passes from above in \c
176/// getLoopAnalysisUsage. It can be used within a loop pass's initialization
177/// with:
178///
179/// INITIALIZE_PASS_DEPENDENCY(LoopPass)
180///
181/// As-if "LoopPass" were a pass.
182void llvm::initializeLoopPassPass(PassRegistry &Registry) {
183 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
184 INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
185 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
Easwaran Ramane12c4872016-06-09 19:44:46 +0000186 INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass)
Chandler Carruth31088a92016-02-19 10:45:18 +0000187 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
188 INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
189 INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
190 INITIALIZE_PASS_DEPENDENCY(SCEVAAWrapperPass)
191 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
192}
Adam Nemet963341c2016-04-21 17:33:17 +0000193
Serguei Katkov3c3a7652019-07-26 06:10:08 +0000194/// Create MDNode for input string.
195static MDNode *createStringMetadata(Loop *TheLoop, StringRef Name, unsigned V) {
196 LLVMContext &Context = TheLoop->getHeader()->getContext();
197 Metadata *MDs[] = {
198 MDString::get(Context, Name),
199 ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(Context), V))};
200 return MDNode::get(Context, MDs);
201}
202
203/// Set input string into loop metadata by keeping other values intact.
204void llvm::addStringMetadataToLoop(Loop *TheLoop, const char *MDString,
205 unsigned V) {
206 SmallVector<Metadata *, 4> MDs(1);
207 // If the loop already has metadata, retain it.
208 MDNode *LoopID = TheLoop->getLoopID();
209 if (LoopID) {
210 for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
211 MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
212 MDs.push_back(Node);
213 }
214 }
215 // Add new metadata.
216 MDs.push_back(createStringMetadata(TheLoop, MDString, V));
217 // Replace current metadata node with new one.
218 LLVMContext &Context = TheLoop->getHeader()->getContext();
219 MDNode *NewLoopID = MDNode::get(Context, MDs);
220 // Set operand 0 to refer to the loop id itself.
221 NewLoopID->replaceOperandWith(0, NewLoopID);
222 TheLoop->setLoopID(NewLoopID);
223}
224
Michael Kruse72448522018-12-12 17:32:52 +0000225/// Find string metadata for loop
226///
227/// If it has a value (e.g. {"llvm.distribute", 1} return the value as an
228/// operand or null otherwise. If the string metadata is not found return
229/// Optional's not-a-value.
Michael Kruse978ba612018-12-20 04:58:07 +0000230Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop,
Michael Kruse72448522018-12-12 17:32:52 +0000231 StringRef Name) {
Michael Kruse978ba612018-12-20 04:58:07 +0000232 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
Michael Kruse72448522018-12-12 17:32:52 +0000233 if (!MD)
234 return None;
235 switch (MD->getNumOperands()) {
236 case 1:
237 return nullptr;
238 case 2:
239 return &MD->getOperand(1);
240 default:
241 llvm_unreachable("loop metadata has 0 or 1 operand");
242 }
243}
244
245static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop,
246 StringRef Name) {
Michael Kruse978ba612018-12-20 04:58:07 +0000247 MDNode *MD = findOptionMDForLoop(TheLoop, Name);
248 if (!MD)
Michael Kruse72448522018-12-12 17:32:52 +0000249 return None;
Michael Kruse978ba612018-12-20 04:58:07 +0000250 switch (MD->getNumOperands()) {
Michael Kruse72448522018-12-12 17:32:52 +0000251 case 1:
252 // When the value is absent it is interpreted as 'attribute set'.
253 return true;
254 case 2:
Alina Sbirleaf9027e52019-01-29 22:33:20 +0000255 if (ConstantInt *IntMD =
256 mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get()))
257 return IntMD->getZExtValue();
258 return true;
Michael Kruse72448522018-12-12 17:32:52 +0000259 }
260 llvm_unreachable("unexpected number of options");
261}
262
263static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) {
264 return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false);
265}
266
267llvm::Optional<int> llvm::getOptionalIntLoopAttribute(Loop *TheLoop,
268 StringRef Name) {
269 const MDOperand *AttrMD =
270 findStringMetadataForLoop(TheLoop, Name).getValueOr(nullptr);
271 if (!AttrMD)
272 return None;
273
274 ConstantInt *IntMD = mdconst::extract_or_null<ConstantInt>(AttrMD->get());
275 if (!IntMD)
276 return None;
277
278 return IntMD->getSExtValue();
279}
280
281Optional<MDNode *> llvm::makeFollowupLoopID(
282 MDNode *OrigLoopID, ArrayRef<StringRef> FollowupOptions,
283 const char *InheritOptionsExceptPrefix, bool AlwaysNew) {
284 if (!OrigLoopID) {
285 if (AlwaysNew)
286 return nullptr;
287 return None;
288 }
289
290 assert(OrigLoopID->getOperand(0) == OrigLoopID);
291
292 bool InheritAllAttrs = !InheritOptionsExceptPrefix;
293 bool InheritSomeAttrs =
294 InheritOptionsExceptPrefix && InheritOptionsExceptPrefix[0] != '\0';
295 SmallVector<Metadata *, 8> MDs;
296 MDs.push_back(nullptr);
297
298 bool Changed = false;
299 if (InheritAllAttrs || InheritSomeAttrs) {
300 for (const MDOperand &Existing : drop_begin(OrigLoopID->operands(), 1)) {
301 MDNode *Op = cast<MDNode>(Existing.get());
302
303 auto InheritThisAttribute = [InheritSomeAttrs,
304 InheritOptionsExceptPrefix](MDNode *Op) {
305 if (!InheritSomeAttrs)
306 return false;
307
308 // Skip malformatted attribute metadata nodes.
309 if (Op->getNumOperands() == 0)
310 return true;
311 Metadata *NameMD = Op->getOperand(0).get();
312 if (!isa<MDString>(NameMD))
313 return true;
314 StringRef AttrName = cast<MDString>(NameMD)->getString();
315
316 // Do not inherit excluded attributes.
317 return !AttrName.startswith(InheritOptionsExceptPrefix);
318 };
319
320 if (InheritThisAttribute(Op))
321 MDs.push_back(Op);
322 else
323 Changed = true;
324 }
325 } else {
326 // Modified if we dropped at least one attribute.
327 Changed = OrigLoopID->getNumOperands() > 1;
328 }
329
330 bool HasAnyFollowup = false;
331 for (StringRef OptionName : FollowupOptions) {
Michael Kruse978ba612018-12-20 04:58:07 +0000332 MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName);
Michael Kruse72448522018-12-12 17:32:52 +0000333 if (!FollowupNode)
334 continue;
335
336 HasAnyFollowup = true;
337 for (const MDOperand &Option : drop_begin(FollowupNode->operands(), 1)) {
338 MDs.push_back(Option.get());
339 Changed = true;
340 }
341 }
342
343 // Attributes of the followup loop not specified explicity, so signal to the
344 // transformation pass to add suitable attributes.
345 if (!AlwaysNew && !HasAnyFollowup)
346 return None;
347
348 // If no attributes were added or remove, the previous loop Id can be reused.
349 if (!AlwaysNew && !Changed)
350 return OrigLoopID;
351
352 // No attributes is equivalent to having no !llvm.loop metadata at all.
353 if (MDs.size() == 1)
354 return nullptr;
355
356 // Build the new loop ID.
357 MDTuple *FollowupLoopID = MDNode::get(OrigLoopID->getContext(), MDs);
358 FollowupLoopID->replaceOperandWith(0, FollowupLoopID);
359 return FollowupLoopID;
360}
361
362bool llvm::hasDisableAllTransformsHint(const Loop *L) {
363 return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced);
364}
365
366TransformationMode llvm::hasUnrollTransformation(Loop *L) {
367 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.disable"))
368 return TM_SuppressedByUser;
369
370 Optional<int> Count =
371 getOptionalIntLoopAttribute(L, "llvm.loop.unroll.count");
372 if (Count.hasValue())
373 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
374
375 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.enable"))
376 return TM_ForcedByUser;
377
378 if (getBooleanLoopAttribute(L, "llvm.loop.unroll.full"))
379 return TM_ForcedByUser;
380
381 if (hasDisableAllTransformsHint(L))
382 return TM_Disable;
383
384 return TM_Unspecified;
385}
386
387TransformationMode llvm::hasUnrollAndJamTransformation(Loop *L) {
388 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.disable"))
389 return TM_SuppressedByUser;
390
391 Optional<int> Count =
392 getOptionalIntLoopAttribute(L, "llvm.loop.unroll_and_jam.count");
393 if (Count.hasValue())
394 return Count.getValue() == 1 ? TM_SuppressedByUser : TM_ForcedByUser;
395
396 if (getBooleanLoopAttribute(L, "llvm.loop.unroll_and_jam.enable"))
397 return TM_ForcedByUser;
398
399 if (hasDisableAllTransformsHint(L))
400 return TM_Disable;
401
402 return TM_Unspecified;
403}
404
405TransformationMode llvm::hasVectorizeTransformation(Loop *L) {
406 Optional<bool> Enable =
407 getOptionalBoolLoopAttribute(L, "llvm.loop.vectorize.enable");
408
409 if (Enable == false)
410 return TM_SuppressedByUser;
411
412 Optional<int> VectorizeWidth =
413 getOptionalIntLoopAttribute(L, "llvm.loop.vectorize.width");
414 Optional<int> InterleaveCount =
415 getOptionalIntLoopAttribute(L, "llvm.loop.interleave.count");
416
Michael Kruse70560a02019-02-04 19:55:59 +0000417 // 'Forcing' vector width and interleave count to one effectively disables
418 // this tranformation.
419 if (Enable == true && VectorizeWidth == 1 && InterleaveCount == 1)
420 return TM_SuppressedByUser;
Michael Kruse72448522018-12-12 17:32:52 +0000421
422 if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized"))
423 return TM_Disable;
424
Michael Kruse70560a02019-02-04 19:55:59 +0000425 if (Enable == true)
426 return TM_ForcedByUser;
427
Michael Kruse72448522018-12-12 17:32:52 +0000428 if (VectorizeWidth == 1 && InterleaveCount == 1)
429 return TM_Disable;
430
431 if (VectorizeWidth > 1 || InterleaveCount > 1)
432 return TM_Enable;
433
434 if (hasDisableAllTransformsHint(L))
435 return TM_Disable;
436
437 return TM_Unspecified;
438}
439
440TransformationMode llvm::hasDistributeTransformation(Loop *L) {
441 if (getBooleanLoopAttribute(L, "llvm.loop.distribute.enable"))
442 return TM_ForcedByUser;
443
444 if (hasDisableAllTransformsHint(L))
445 return TM_Disable;
446
447 return TM_Unspecified;
448}
449
450TransformationMode llvm::hasLICMVersioningTransformation(Loop *L) {
451 if (getBooleanLoopAttribute(L, "llvm.loop.licm_versioning.disable"))
452 return TM_SuppressedByUser;
453
454 if (hasDisableAllTransformsHint(L))
455 return TM_Disable;
456
457 return TM_Unspecified;
458}
459
Alina Sbirlea7ed58562017-09-15 00:04:16 +0000460/// Does a BFS from a given node to all of its children inside a given loop.
461/// The returned vector of nodes includes the starting point.
462SmallVector<DomTreeNode *, 16>
463llvm::collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop) {
464 SmallVector<DomTreeNode *, 16> Worklist;
465 auto AddRegionToWorklist = [&](DomTreeNode *DTN) {
466 // Only include subregions in the top level loop.
467 BasicBlock *BB = DTN->getBlock();
468 if (CurLoop->contains(BB))
469 Worklist.push_back(DTN);
470 };
471
472 AddRegionToWorklist(N);
473
474 for (size_t I = 0; I < Worklist.size(); I++)
475 for (DomTreeNode *Child : Worklist[I]->getChildren())
476 AddRegionToWorklist(Child);
477
478 return Worklist;
479}
480
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000481void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr,
482 ScalarEvolution *SE = nullptr,
483 LoopInfo *LI = nullptr) {
Hans Wennborg899809d2017-10-04 21:14:07 +0000484 assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000485 auto *Preheader = L->getLoopPreheader();
486 assert(Preheader && "Preheader should exist!");
487
488 // Now that we know the removal is safe, remove the loop by changing the
489 // branch from the preheader to go to the single exit block.
490 //
491 // Because we're deleting a large chunk of code at once, the sequence in which
492 // we remove things is very important to avoid invalidation issues.
493
494 // Tell ScalarEvolution that the loop is deleted. Do this before
495 // deleting the loop so that ScalarEvolution can look at the loop
496 // to determine what it needs to clean up.
497 if (SE)
498 SE->forgetLoop(L);
499
500 auto *ExitBlock = L->getUniqueExitBlock();
501 assert(ExitBlock && "Should have a unique exit block!");
502 assert(L->hasDedicatedExits() && "Loop should have dedicated exits!");
503
504 auto *OldBr = dyn_cast<BranchInst>(Preheader->getTerminator());
505 assert(OldBr && "Preheader must end with a branch");
506 assert(OldBr->isUnconditional() && "Preheader must have a single successor");
507 // Connect the preheader to the exit block. Keep the old edge to the header
508 // around to perform the dominator tree update in two separate steps
509 // -- #1 insertion of the edge preheader -> exit and #2 deletion of the edge
510 // preheader -> header.
511 //
512 //
513 // 0. Preheader 1. Preheader 2. Preheader
514 // | | | |
515 // V | V |
516 // Header <--\ | Header <--\ | Header <--\
517 // | | | | | | | | | | |
518 // | V | | | V | | | V |
519 // | Body --/ | | Body --/ | | Body --/
520 // V V V V V
521 // Exit Exit Exit
522 //
523 // By doing this is two separate steps we can perform the dominator tree
524 // update without using the batch update API.
525 //
526 // Even when the loop is never executed, we cannot remove the edge from the
527 // source block to the exit block. Consider the case where the unexecuted loop
528 // branches back to an outer loop. If we deleted the loop and removed the edge
529 // coming to this inner loop, this will break the outer loop structure (by
530 // deleting the backedge of the outer loop). If the outer loop is indeed a
531 // non-loop, it will be deleted in a future iteration of loop deletion pass.
532 IRBuilder<> Builder(OldBr);
533 Builder.CreateCondBr(Builder.getFalse(), L->getHeader(), ExitBlock);
534 // Remove the old branch. The conditional branch becomes a new terminator.
535 OldBr->eraseFromParent();
536
537 // Rewrite phis in the exit block to get their inputs from the Preheader
538 // instead of the exiting block.
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000539 for (PHINode &P : ExitBlock->phis()) {
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000540 // Set the zero'th element of Phi to be from the preheader and remove all
541 // other incoming values. Given the loop has dedicated exits, all other
542 // incoming values must be from the exiting blocks.
543 int PredIndex = 0;
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000544 P.setIncomingBlock(PredIndex, Preheader);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000545 // Removes all incoming values from all other exiting blocks (including
546 // duplicate values from an exiting block).
547 // Nuke all entries except the zero'th entry which is the preheader entry.
548 // NOTE! We need to remove Incoming Values in the reverse order as done
549 // below, to keep the indices valid for deletion (removeIncomingValues
550 // updates getNumIncomingValues and shifts all values down into the operand
551 // being deleted).
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000552 for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i)
553 P.removeIncomingValue(e - i, false);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000554
Benjamin Kramerc7fc81e2017-12-30 15:27:33 +0000555 assert((P.getNumIncomingValues() == 1 &&
556 P.getIncomingBlock(PredIndex) == Preheader) &&
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000557 "Should have exactly one value and that's from the preheader!");
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000558 }
559
560 // Disconnect the loop body by branching directly to its exit.
561 Builder.SetInsertPoint(Preheader->getTerminator());
562 Builder.CreateBr(ExitBlock);
563 // Remove the old branch.
564 Preheader->getTerminator()->eraseFromParent();
565
Chijun Sima21a8b602018-08-03 05:08:17 +0000566 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000567 if (DT) {
568 // Update the dominator tree by informing it about the new edge from the
Chijun Simaf131d612019-02-22 05:41:43 +0000569 // preheader to the exit and the removed edge.
570 DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock},
571 {DominatorTree::Delete, Preheader, L->getHeader()}});
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000572 }
573
Davide Italiano744c3c32018-12-12 23:32:35 +0000574 // Use a map to unique and a vector to guarantee deterministic ordering.
Davide Italiano8ee59ca2018-12-13 01:11:52 +0000575 llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet;
Davide Italiano744c3c32018-12-12 23:32:35 +0000576 llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst;
577
Serguei Katkova757d652018-01-12 07:24:43 +0000578 // Given LCSSA form is satisfied, we should not have users of instructions
579 // within the dead loop outside of the loop. However, LCSSA doesn't take
580 // unreachable uses into account. We handle them here.
581 // We could do it after drop all references (in this case all users in the
582 // loop will be already eliminated and we have less work to do but according
583 // to API doc of User::dropAllReferences only valid operation after dropping
584 // references, is deletion. So let's substitute all usages of
585 // instruction from the loop with undef value of corresponding type first.
586 for (auto *Block : L->blocks())
587 for (Instruction &I : *Block) {
588 auto *Undef = UndefValue::get(I.getType());
589 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E;) {
590 Use &U = *UI;
591 ++UI;
592 if (auto *Usr = dyn_cast<Instruction>(U.getUser()))
593 if (L->contains(Usr->getParent()))
594 continue;
595 // If we have a DT then we can check that uses outside a loop only in
596 // unreachable block.
597 if (DT)
598 assert(!DT->isReachableFromEntry(U) &&
599 "Unexpected user in reachable block");
600 U.set(Undef);
601 }
Davide Italiano744c3c32018-12-12 23:32:35 +0000602 auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I);
603 if (!DVI)
604 continue;
Davide Italiano8ee59ca2018-12-13 01:11:52 +0000605 auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()});
606 if (Key != DeadDebugSet.end())
Davide Italiano744c3c32018-12-12 23:32:35 +0000607 continue;
Davide Italiano8ee59ca2018-12-13 01:11:52 +0000608 DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()});
Davide Italiano744c3c32018-12-12 23:32:35 +0000609 DeadDebugInst.push_back(DVI);
Serguei Katkova757d652018-01-12 07:24:43 +0000610 }
611
Davide Italiano744c3c32018-12-12 23:32:35 +0000612 // After the loop has been deleted all the values defined and modified
613 // inside the loop are going to be unavailable.
614 // Since debug values in the loop have been deleted, inserting an undef
615 // dbg.value truncates the range of any dbg.value before the loop where the
616 // loop used to be. This is particularly important for constant values.
617 DIBuilder DIB(*ExitBlock->getModule());
Roman Lebedeve5be6602019-05-05 18:59:12 +0000618 Instruction *InsertDbgValueBefore = ExitBlock->getFirstNonPHI();
619 assert(InsertDbgValueBefore &&
620 "There should be a non-PHI instruction in exit block, else these "
621 "instructions will have no parent.");
Davide Italiano744c3c32018-12-12 23:32:35 +0000622 for (auto *DVI : DeadDebugInst)
Roman Lebedeve5be6602019-05-05 18:59:12 +0000623 DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()),
624 DVI->getVariable(), DVI->getExpression(),
625 DVI->getDebugLoc(), InsertDbgValueBefore);
Davide Italiano744c3c32018-12-12 23:32:35 +0000626
Marcello Maggionidf3e71e2017-10-04 20:42:46 +0000627 // Remove the block from the reference counting scheme, so that we can
628 // delete it freely later.
629 for (auto *Block : L->blocks())
630 Block->dropAllReferences();
631
632 if (LI) {
633 // Erase the instructions and the blocks without having to worry
634 // about ordering because we already dropped the references.
635 // NOTE: This iteration is safe because erasing the block does not remove
636 // its entry from the loop's block list. We do that in the next section.
637 for (Loop::block_iterator LpI = L->block_begin(), LpE = L->block_end();
638 LpI != LpE; ++LpI)
639 (*LpI)->eraseFromParent();
640
641 // Finally, the blocks from loopinfo. This has to happen late because
642 // otherwise our loop iterators won't work.
643
644 SmallPtrSet<BasicBlock *, 8> blocks;
645 blocks.insert(L->block_begin(), L->block_end());
646 for (BasicBlock *BB : blocks)
647 LI->removeBlock(BB);
648
649 // The last step is to update LoopInfo now that we've eliminated this loop.
650 LI->erase(L);
651 }
652}
653
Dehao Chen41d72a82016-11-17 01:17:02 +0000654Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) {
Serguei Katkov45c43e72019-07-15 06:42:39 +0000655 // Support loops with an exiting latch and other existing exists only
656 // deoptimize.
Dehao Chen41d72a82016-11-17 01:17:02 +0000657
Hiroshi Inoued24ddcd2018-01-19 10:55:29 +0000658 // Get the branch weights for the loop's backedge.
Serguei Katkov45c43e72019-07-15 06:42:39 +0000659 BasicBlock *Latch = L->getLoopLatch();
660 if (!Latch)
661 return None;
662 BranchInst *LatchBR = dyn_cast<BranchInst>(Latch->getTerminator());
663 if (!LatchBR || LatchBR->getNumSuccessors() != 2 || !L->isLoopExiting(Latch))
Dehao Chen41d72a82016-11-17 01:17:02 +0000664 return None;
665
666 assert((LatchBR->getSuccessor(0) == L->getHeader() ||
667 LatchBR->getSuccessor(1) == L->getHeader()) &&
668 "At least one edge out of the latch must go to the header");
669
Serguei Katkov45c43e72019-07-15 06:42:39 +0000670 SmallVector<BasicBlock *, 4> ExitBlocks;
671 L->getUniqueNonLatchExitBlocks(ExitBlocks);
672 if (any_of(ExitBlocks, [](const BasicBlock *EB) {
673 return !EB->getTerminatingDeoptimizeCall();
674 }))
675 return None;
676
Dehao Chen41d72a82016-11-17 01:17:02 +0000677 // To estimate the number of times the loop body was executed, we want to
678 // know the number of times the backedge was taken, vs. the number of times
679 // we exited the loop.
Dehao Chen41d72a82016-11-17 01:17:02 +0000680 uint64_t TrueVal, FalseVal;
Michael Kupersteinb151a642016-11-30 21:13:57 +0000681 if (!LatchBR->extractProfMetadata(TrueVal, FalseVal))
Dehao Chen41d72a82016-11-17 01:17:02 +0000682 return None;
683
Michael Kupersteinb151a642016-11-30 21:13:57 +0000684 if (!TrueVal || !FalseVal)
685 return 0;
Dehao Chen41d72a82016-11-17 01:17:02 +0000686
Michael Kupersteinb151a642016-11-30 21:13:57 +0000687 // Divide the count of the backedge by the count of the edge exiting the loop,
688 // rounding to nearest.
Dehao Chen41d72a82016-11-17 01:17:02 +0000689 if (LatchBR->getSuccessor(0) == L->getHeader())
Michael Kupersteinb151a642016-11-30 21:13:57 +0000690 return (TrueVal + (FalseVal / 2)) / FalseVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000691 else
Michael Kupersteinb151a642016-11-30 21:13:57 +0000692 return (FalseVal + (TrueVal / 2)) / TrueVal;
Dehao Chen41d72a82016-11-17 01:17:02 +0000693}
Amara Emersoncf9daa32017-05-09 10:43:25 +0000694
David Green6cb64782018-08-15 10:59:41 +0000695bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop,
696 ScalarEvolution &SE) {
David Green395b80c2018-08-11 06:57:28 +0000697 Loop *OuterL = InnerLoop->getParentLoop();
698 if (!OuterL)
699 return true;
700
701 // Get the backedge taken count for the inner loop
702 BasicBlock *InnerLoopLatch = InnerLoop->getLoopLatch();
703 const SCEV *InnerLoopBECountSC = SE.getExitCount(InnerLoop, InnerLoopLatch);
704 if (isa<SCEVCouldNotCompute>(InnerLoopBECountSC) ||
705 !InnerLoopBECountSC->getType()->isIntegerTy())
706 return false;
707
708 // Get whether count is invariant to the outer loop
709 ScalarEvolution::LoopDisposition LD =
710 SE.getLoopDisposition(InnerLoopBECountSC, OuterL);
711 if (LD != ScalarEvolution::LoopInvariant)
712 return false;
713
714 return true;
715}
716
Vikram TV6594dc32018-09-10 05:05:08 +0000717Value *llvm::createMinMaxOp(IRBuilder<> &Builder,
718 RecurrenceDescriptor::MinMaxRecurrenceKind RK,
719 Value *Left, Value *Right) {
720 CmpInst::Predicate P = CmpInst::ICMP_NE;
721 switch (RK) {
722 default:
723 llvm_unreachable("Unknown min/max recurrence kind");
724 case RecurrenceDescriptor::MRK_UIntMin:
725 P = CmpInst::ICMP_ULT;
726 break;
727 case RecurrenceDescriptor::MRK_UIntMax:
728 P = CmpInst::ICMP_UGT;
729 break;
730 case RecurrenceDescriptor::MRK_SIntMin:
731 P = CmpInst::ICMP_SLT;
732 break;
733 case RecurrenceDescriptor::MRK_SIntMax:
734 P = CmpInst::ICMP_SGT;
735 break;
736 case RecurrenceDescriptor::MRK_FloatMin:
737 P = CmpInst::FCMP_OLT;
738 break;
739 case RecurrenceDescriptor::MRK_FloatMax:
740 P = CmpInst::FCMP_OGT;
741 break;
742 }
743
744 // We only match FP sequences that are 'fast', so we can unconditionally
745 // set it on any generated instructions.
746 IRBuilder<>::FastMathFlagGuard FMFG(Builder);
747 FastMathFlags FMF;
748 FMF.setFast();
749 Builder.setFastMathFlags(FMF);
750
751 Value *Cmp;
752 if (RK == RecurrenceDescriptor::MRK_FloatMin ||
753 RK == RecurrenceDescriptor::MRK_FloatMax)
754 Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
755 else
756 Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
757
758 Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
759 return Select;
760}
761
Simon Pilgrim23c21822018-04-09 15:44:20 +0000762// Helper to generate an ordered reduction.
763Value *
764llvm::getOrderedReduction(IRBuilder<> &Builder, Value *Acc, Value *Src,
765 unsigned Op,
766 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
767 ArrayRef<Value *> RedOps) {
768 unsigned VF = Src->getType()->getVectorNumElements();
769
770 // Extract and apply reduction ops in ascending order:
771 // e.g. ((((Acc + Scl[0]) + Scl[1]) + Scl[2]) + ) ... + Scl[VF-1]
772 Value *Result = Acc;
773 for (unsigned ExtractIdx = 0; ExtractIdx != VF; ++ExtractIdx) {
774 Value *Ext =
775 Builder.CreateExtractElement(Src, Builder.getInt32(ExtractIdx));
776
777 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
778 Result = Builder.CreateBinOp((Instruction::BinaryOps)Op, Result, Ext,
779 "bin.rdx");
780 } else {
781 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
782 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000783 Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext);
Simon Pilgrim23c21822018-04-09 15:44:20 +0000784 }
785
786 if (!RedOps.empty())
787 propagateIRFlags(Result, RedOps);
788 }
789
790 return Result;
791}
792
Amara Emersoncf9daa32017-05-09 10:43:25 +0000793// Helper to generate a log2 shuffle reduction.
Amara Emerson836b0f42017-05-10 09:42:49 +0000794Value *
795llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op,
796 RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind,
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000797 ArrayRef<Value *> RedOps) {
Amara Emersoncf9daa32017-05-09 10:43:25 +0000798 unsigned VF = Src->getType()->getVectorNumElements();
799 // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
800 // and vector ops, reducing the set of values being computed by half each
801 // round.
802 assert(isPowerOf2_32(VF) &&
803 "Reduction emission only supported for pow2 vectors!");
804 Value *TmpVec = Src;
805 SmallVector<Constant *, 32> ShuffleMask(VF, nullptr);
806 for (unsigned i = VF; i != 1; i >>= 1) {
807 // Move the upper half of the vector to the lower half.
808 for (unsigned j = 0; j != i / 2; ++j)
809 ShuffleMask[j] = Builder.getInt32(i / 2 + j);
810
811 // Fill the rest of the mask with undef.
812 std::fill(&ShuffleMask[i / 2], ShuffleMask.end(),
813 UndefValue::get(Builder.getInt32Ty()));
814
815 Value *Shuf = Builder.CreateShuffleVector(
816 TmpVec, UndefValue::get(TmpVec->getType()),
817 ConstantVector::get(ShuffleMask), "rdx.shuf");
818
819 if (Op != Instruction::ICmp && Op != Instruction::FCmp) {
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000820 // The builder propagates its fast-math-flags setting.
821 TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
822 "bin.rdx");
Amara Emersoncf9daa32017-05-09 10:43:25 +0000823 } else {
824 assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid &&
825 "Invalid min/max");
Vikram TV6594dc32018-09-10 05:05:08 +0000826 TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000827 }
828 if (!RedOps.empty())
829 propagateIRFlags(TmpVec, RedOps);
830 }
831 // The result is in the first element of the vector.
832 return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
833}
834
835/// Create a simple vector reduction specified by an opcode and some
836/// flags (if generating min/max reductions).
837Value *llvm::createSimpleTargetReduction(
838 IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode,
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000839 Value *Src, TargetTransformInfo::ReductionFlags Flags,
Amara Emersoncf9daa32017-05-09 10:43:25 +0000840 ArrayRef<Value *> RedOps) {
841 assert(isa<VectorType>(Src->getType()) && "Type must be a vector");
842
Vikram TV7e98d692018-09-12 01:59:43 +0000843 std::function<Value *()> BuildFunc;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000844 using RD = RecurrenceDescriptor;
845 RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid;
Amara Emersoncf9daa32017-05-09 10:43:25 +0000846
847 switch (Opcode) {
848 case Instruction::Add:
849 BuildFunc = [&]() { return Builder.CreateAddReduce(Src); };
850 break;
851 case Instruction::Mul:
852 BuildFunc = [&]() { return Builder.CreateMulReduce(Src); };
853 break;
854 case Instruction::And:
855 BuildFunc = [&]() { return Builder.CreateAndReduce(Src); };
856 break;
857 case Instruction::Or:
858 BuildFunc = [&]() { return Builder.CreateOrReduce(Src); };
859 break;
860 case Instruction::Xor:
861 BuildFunc = [&]() { return Builder.CreateXorReduce(Src); };
862 break;
863 case Instruction::FAdd:
864 BuildFunc = [&]() {
Sander de Smalencbeb5632019-06-11 08:22:10 +0000865 auto Rdx = Builder.CreateFAddReduce(
866 Constant::getNullValue(Src->getType()->getVectorElementType()), Src);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000867 return Rdx;
868 };
869 break;
870 case Instruction::FMul:
871 BuildFunc = [&]() {
Sander de Smalencbeb5632019-06-11 08:22:10 +0000872 Type *Ty = Src->getType()->getVectorElementType();
873 auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000874 return Rdx;
875 };
876 break;
877 case Instruction::ICmp:
878 if (Flags.IsMaxOp) {
879 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMax : RD::MRK_UIntMax;
880 BuildFunc = [&]() {
881 return Builder.CreateIntMaxReduce(Src, Flags.IsSigned);
882 };
883 } else {
884 MinMaxKind = Flags.IsSigned ? RD::MRK_SIntMin : RD::MRK_UIntMin;
885 BuildFunc = [&]() {
886 return Builder.CreateIntMinReduce(Src, Flags.IsSigned);
887 };
888 }
889 break;
890 case Instruction::FCmp:
891 if (Flags.IsMaxOp) {
892 MinMaxKind = RD::MRK_FloatMax;
893 BuildFunc = [&]() { return Builder.CreateFPMaxReduce(Src, Flags.NoNaN); };
894 } else {
895 MinMaxKind = RD::MRK_FloatMin;
896 BuildFunc = [&]() { return Builder.CreateFPMinReduce(Src, Flags.NoNaN); };
897 }
898 break;
899 default:
900 llvm_unreachable("Unhandled opcode");
901 break;
902 }
903 if (TTI->useReductionIntrinsic(Opcode, Src->getType(), Flags))
904 return BuildFunc();
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000905 return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000906}
907
908/// Create a vector reduction using a given recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000909Value *llvm::createTargetReduction(IRBuilder<> &B,
Amara Emersoncf9daa32017-05-09 10:43:25 +0000910 const TargetTransformInfo *TTI,
911 RecurrenceDescriptor &Desc, Value *Src,
912 bool NoNaN) {
913 // TODO: Support in-order reductions based on the recurrence descriptor.
Sanjay Patel3e069f52017-12-06 19:37:00 +0000914 using RD = RecurrenceDescriptor;
915 RD::RecurrenceKind RecKind = Desc.getRecurrenceKind();
Amara Emersoncf9daa32017-05-09 10:43:25 +0000916 TargetTransformInfo::ReductionFlags Flags;
917 Flags.NoNaN = NoNaN;
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000918
919 // All ops in the reduction inherit fast-math-flags from the recurrence
920 // descriptor.
921 IRBuilder<>::FastMathFlagGuard FMFGuard(B);
922 B.setFastMathFlags(Desc.getFastMathFlags());
923
Amara Emersoncf9daa32017-05-09 10:43:25 +0000924 switch (RecKind) {
Sanjay Patel3e069f52017-12-06 19:37:00 +0000925 case RD::RK_FloatAdd:
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000926 return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000927 case RD::RK_FloatMult:
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000928 return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000929 case RD::RK_IntegerAdd:
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000930 return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000931 case RD::RK_IntegerMult:
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000932 return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000933 case RD::RK_IntegerAnd:
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000934 return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000935 case RD::RK_IntegerOr:
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000936 return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000937 case RD::RK_IntegerXor:
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000938 return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags);
Sanjay Patel3e069f52017-12-06 19:37:00 +0000939 case RD::RK_IntegerMinMax: {
940 RD::MinMaxRecurrenceKind MMKind = Desc.getMinMaxRecurrenceKind();
941 Flags.IsMaxOp = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_UIntMax);
942 Flags.IsSigned = (MMKind == RD::MRK_SIntMax || MMKind == RD::MRK_SIntMin);
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000943 return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000944 }
Sanjay Patel3e069f52017-12-06 19:37:00 +0000945 case RD::RK_FloatMinMax: {
946 Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax;
Sanjay Patelad62a3a2019-06-05 14:58:04 +0000947 return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000948 }
949 default:
950 llvm_unreachable("Unhandled RecKind");
951 }
952}
953
Dinar Temirbulatova61f4b82017-07-19 10:02:07 +0000954void llvm::propagateIRFlags(Value *I, ArrayRef<Value *> VL, Value *OpValue) {
955 auto *VecOp = dyn_cast<Instruction>(I);
956 if (!VecOp)
957 return;
958 auto *Intersection = (OpValue == nullptr) ? dyn_cast<Instruction>(VL[0])
959 : dyn_cast<Instruction>(OpValue);
960 if (!Intersection)
961 return;
962 const unsigned Opcode = Intersection->getOpcode();
963 VecOp->copyIRFlags(Intersection);
964 for (auto *V : VL) {
965 auto *Instr = dyn_cast<Instruction>(V);
966 if (!Instr)
967 continue;
968 if (OpValue == nullptr || Opcode == Instr->getOpcode())
969 VecOp->andIRFlags(V);
Amara Emersoncf9daa32017-05-09 10:43:25 +0000970 }
971}
Max Kazantseva78dc4d2019-01-15 09:51:34 +0000972
973bool llvm::isKnownNegativeInLoop(const SCEV *S, const Loop *L,
974 ScalarEvolution &SE) {
975 const SCEV *Zero = SE.getZero(S->getType());
976 return SE.isAvailableAtLoopEntry(S, L) &&
977 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SLT, S, Zero);
978}
979
980bool llvm::isKnownNonNegativeInLoop(const SCEV *S, const Loop *L,
981 ScalarEvolution &SE) {
982 const SCEV *Zero = SE.getZero(S->getType());
983 return SE.isAvailableAtLoopEntry(S, L) &&
984 SE.isLoopEntryGuardedByCond(L, ICmpInst::ICMP_SGE, S, Zero);
985}
986
987bool llvm::cannotBeMinInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
988 bool Signed) {
989 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
990 APInt Min = Signed ? APInt::getSignedMinValue(BitWidth) :
991 APInt::getMinValue(BitWidth);
992 auto Predicate = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
993 return SE.isAvailableAtLoopEntry(S, L) &&
994 SE.isLoopEntryGuardedByCond(L, Predicate, S,
995 SE.getConstant(Min));
996}
997
998bool llvm::cannotBeMaxInLoop(const SCEV *S, const Loop *L, ScalarEvolution &SE,
999 bool Signed) {
1000 unsigned BitWidth = cast<IntegerType>(S->getType())->getBitWidth();
1001 APInt Max = Signed ? APInt::getSignedMaxValue(BitWidth) :
1002 APInt::getMaxValue(BitWidth);
1003 auto Predicate = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1004 return SE.isAvailableAtLoopEntry(S, L) &&
1005 SE.isLoopEntryGuardedByCond(L, Predicate, S,
1006 SE.getConstant(Max));
1007}