Karthik Bhat | 76aa662 | 2015-04-20 04:38:33 +0000 | [diff] [blame] | 1 | //===-- LoopUtils.cpp - Loop Utility functions -------------------------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | // See https://llvm.org/LICENSE.txt for license information. |
| 5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Karthik Bhat | 76aa662 | 2015-04-20 04:38:33 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | // |
| 9 | // This file defines common loop utility functions. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
Adam Nemet | 2f2bd8c | 2016-07-26 17:52:02 +0000 | [diff] [blame] | 13 | #include "llvm/Transforms/Utils/LoopUtils.h" |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 14 | #include "llvm/ADT/ScopeExit.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 15 | #include "llvm/Analysis/AliasAnalysis.h" |
| 16 | #include "llvm/Analysis/BasicAliasAnalysis.h" |
Richard Trieu | 5f436fc | 2019-02-06 02:52:52 +0000 | [diff] [blame] | 17 | #include "llvm/Analysis/DomTreeUpdater.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 18 | #include "llvm/Analysis/GlobalsModRef.h" |
Philip Reames | a21d5f1 | 2018-03-15 21:04:28 +0000 | [diff] [blame] | 19 | #include "llvm/Analysis/InstructionSimplify.h" |
Adam Nemet | 2f2bd8c | 2016-07-26 17:52:02 +0000 | [diff] [blame] | 20 | #include "llvm/Analysis/LoopInfo.h" |
Igor Laevsky | c3ccf5d | 2016-10-28 12:57:20 +0000 | [diff] [blame] | 21 | #include "llvm/Analysis/LoopPass.h" |
Alina Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 22 | #include "llvm/Analysis/MemorySSAUpdater.h" |
Philip Reames | 23aed5e | 2018-03-20 22:45:23 +0000 | [diff] [blame] | 23 | #include "llvm/Analysis/MustExecute.h" |
Weiming Zhao | 45d4cb9 | 2015-11-24 18:57:06 +0000 | [diff] [blame] | 24 | #include "llvm/Analysis/ScalarEvolution.h" |
Adam Nemet | 2f2bd8c | 2016-07-26 17:52:02 +0000 | [diff] [blame] | 25 | #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" |
Elena Demikhovsky | c434d09 | 2016-05-10 07:33:35 +0000 | [diff] [blame] | 26 | #include "llvm/Analysis/ScalarEvolutionExpander.h" |
Weiming Zhao | 45d4cb9 | 2015-11-24 18:57:06 +0000 | [diff] [blame] | 27 | #include "llvm/Analysis/ScalarEvolutionExpressions.h" |
Chandler Carruth | 6bda14b | 2017-06-06 11:49:48 +0000 | [diff] [blame] | 28 | #include "llvm/Analysis/TargetTransformInfo.h" |
Chad Rosier | a097bc6 | 2018-02-04 15:42:24 +0000 | [diff] [blame] | 29 | #include "llvm/Analysis/ValueTracking.h" |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 30 | #include "llvm/IR/DIBuilder.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 31 | #include "llvm/IR/Dominators.h" |
Karthik Bhat | 76aa662 | 2015-04-20 04:38:33 +0000 | [diff] [blame] | 32 | #include "llvm/IR/Instructions.h" |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 33 | #include "llvm/IR/IntrinsicInst.h" |
Weiming Zhao | 45d4cb9 | 2015-11-24 18:57:06 +0000 | [diff] [blame] | 34 | #include "llvm/IR/Module.h" |
Karthik Bhat | 76aa662 | 2015-04-20 04:38:33 +0000 | [diff] [blame] | 35 | #include "llvm/IR/PatternMatch.h" |
| 36 | #include "llvm/IR/ValueHandle.h" |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 37 | #include "llvm/Pass.h" |
Karthik Bhat | 76aa662 | 2015-04-20 04:38:33 +0000 | [diff] [blame] | 38 | #include "llvm/Support/Debug.h" |
Chad Rosier | a097bc6 | 2018-02-04 15:42:24 +0000 | [diff] [blame] | 39 | #include "llvm/Support/KnownBits.h" |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 40 | #include "llvm/Transforms/Utils/BasicBlockUtils.h" |
Karthik Bhat | 76aa662 | 2015-04-20 04:38:33 +0000 | [diff] [blame] | 41 | |
| 42 | using namespace llvm; |
| 43 | using namespace llvm::PatternMatch; |
| 44 | |
| 45 | #define DEBUG_TYPE "loop-utils" |
| 46 | |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 47 | static const char *LLVMLoopDisableNonforced = "llvm.loop.disable_nonforced"; |
| 48 | |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 49 | bool llvm::formDedicatedExitBlocks(Loop *L, DominatorTree *DT, LoopInfo *LI, |
Alina Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 50 | MemorySSAUpdater *MSSAU, |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 51 | 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 Topper | 784929d | 2019-02-08 20:48:56 +0000 | [diff] [blame] | 70 | if (isa<CallBrInst>(PredBB->getTerminator())) |
| 71 | // We cannot rewrite exiting edges from a callbr. |
| 72 | return false; |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 73 | |
| 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 Sbirlea | 97468e9 | 2019-02-21 21:13:34 +0000 | [diff] [blame] | 86 | BB, InLoopPredecessors, ".loopexit", DT, LI, MSSAU, PreserveLCSSA); |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 87 | |
| 88 | if (!NewExitBB) |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 89 | LLVM_DEBUG( |
| 90 | dbgs() << "WARNING: Can't create a dedicated exit block for loop: " |
| 91 | << *L << "\n"); |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 92 | else |
Nicola Zaghen | d34e60c | 2018-05-14 12:53:11 +0000 | [diff] [blame] | 93 | LLVM_DEBUG(dbgs() << "LoopSimplify: Creating dedicated exit block " |
| 94 | << NewExitBB->getName() << "\n"); |
Chandler Carruth | 4a00088 | 2017-06-25 22:45:31 +0000 | [diff] [blame] | 95 | 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 Prantl | 5f8f34e4 | 2018-05-01 15:54:18 +0000 | [diff] [blame] | 117 | /// Returns the instructions that use values defined in the loop. |
Ashutosh Nema | c5b7b55 | 2015-08-19 05:40:42 +0000 | [diff] [blame] | 118 | SmallVector<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 Majnemer | 0a16c22 | 2016-08-11 21:15:00 +0000 | [diff] [blame] | 126 | if (any_of(Users, [&](User *U) { |
Ashutosh Nema | c5b7b55 | 2015-08-19 05:40:42 +0000 | [diff] [blame] | 127 | auto *Use = cast<Instruction>(U); |
| 128 | return !L->contains(Use->getParent()); |
| 129 | })) |
| 130 | UsedOutside.push_back(&Inst); |
| 131 | } |
| 132 | |
| 133 | return UsedOutside; |
| 134 | } |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 135 | |
| 136 | void 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 Laevsky | c3ccf5d | 2016-10-28 12:57:20 +0000 | [diff] [blame] | 153 | // 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 Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 157 | |
| 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. |
| 182 | void llvm::initializeLoopPassPass(PassRegistry &Registry) { |
| 183 | INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) |
| 184 | INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass) |
| 185 | INITIALIZE_PASS_DEPENDENCY(LoopSimplify) |
Easwaran Raman | e12c487 | 2016-06-09 19:44:46 +0000 | [diff] [blame] | 186 | INITIALIZE_PASS_DEPENDENCY(LCSSAWrapperPass) |
Chandler Carruth | 31088a9 | 2016-02-19 10:45:18 +0000 | [diff] [blame] | 187 | 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 Nemet | 963341c | 2016-04-21 17:33:17 +0000 | [diff] [blame] | 193 | |
Serguei Katkov | 3c3a765 | 2019-07-26 06:10:08 +0000 | [diff] [blame^] | 194 | /// Create MDNode for input string. |
| 195 | static 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. |
| 204 | void 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 Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 225 | /// 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 Kruse | 978ba61 | 2018-12-20 04:58:07 +0000 | [diff] [blame] | 230 | Optional<const MDOperand *> llvm::findStringMetadataForLoop(const Loop *TheLoop, |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 231 | StringRef Name) { |
Michael Kruse | 978ba61 | 2018-12-20 04:58:07 +0000 | [diff] [blame] | 232 | MDNode *MD = findOptionMDForLoop(TheLoop, Name); |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 233 | 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 | |
| 245 | static Optional<bool> getOptionalBoolLoopAttribute(const Loop *TheLoop, |
| 246 | StringRef Name) { |
Michael Kruse | 978ba61 | 2018-12-20 04:58:07 +0000 | [diff] [blame] | 247 | MDNode *MD = findOptionMDForLoop(TheLoop, Name); |
| 248 | if (!MD) |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 249 | return None; |
Michael Kruse | 978ba61 | 2018-12-20 04:58:07 +0000 | [diff] [blame] | 250 | switch (MD->getNumOperands()) { |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 251 | case 1: |
| 252 | // When the value is absent it is interpreted as 'attribute set'. |
| 253 | return true; |
| 254 | case 2: |
Alina Sbirlea | f9027e5 | 2019-01-29 22:33:20 +0000 | [diff] [blame] | 255 | if (ConstantInt *IntMD = |
| 256 | mdconst::extract_or_null<ConstantInt>(MD->getOperand(1).get())) |
| 257 | return IntMD->getZExtValue(); |
| 258 | return true; |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 259 | } |
| 260 | llvm_unreachable("unexpected number of options"); |
| 261 | } |
| 262 | |
| 263 | static bool getBooleanLoopAttribute(const Loop *TheLoop, StringRef Name) { |
| 264 | return getOptionalBoolLoopAttribute(TheLoop, Name).getValueOr(false); |
| 265 | } |
| 266 | |
| 267 | llvm::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 | |
| 281 | Optional<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 Kruse | 978ba61 | 2018-12-20 04:58:07 +0000 | [diff] [blame] | 332 | MDNode *FollowupNode = findOptionMDForLoopID(OrigLoopID, OptionName); |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 333 | 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 | |
| 362 | bool llvm::hasDisableAllTransformsHint(const Loop *L) { |
| 363 | return getBooleanLoopAttribute(L, LLVMLoopDisableNonforced); |
| 364 | } |
| 365 | |
| 366 | TransformationMode 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 | |
| 387 | TransformationMode 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 | |
| 405 | TransformationMode 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 Kruse | 70560a0 | 2019-02-04 19:55:59 +0000 | [diff] [blame] | 417 | // '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 Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 421 | |
| 422 | if (getBooleanLoopAttribute(L, "llvm.loop.isvectorized")) |
| 423 | return TM_Disable; |
| 424 | |
Michael Kruse | 70560a0 | 2019-02-04 19:55:59 +0000 | [diff] [blame] | 425 | if (Enable == true) |
| 426 | return TM_ForcedByUser; |
| 427 | |
Michael Kruse | 7244852 | 2018-12-12 17:32:52 +0000 | [diff] [blame] | 428 | 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 | |
| 440 | TransformationMode 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 | |
| 450 | TransformationMode 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 Sbirlea | 7ed5856 | 2017-09-15 00:04:16 +0000 | [diff] [blame] | 460 | /// 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. |
| 462 | SmallVector<DomTreeNode *, 16> |
| 463 | llvm::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 Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 481 | void llvm::deleteDeadLoop(Loop *L, DominatorTree *DT = nullptr, |
| 482 | ScalarEvolution *SE = nullptr, |
| 483 | LoopInfo *LI = nullptr) { |
Hans Wennborg | 899809d | 2017-10-04 21:14:07 +0000 | [diff] [blame] | 484 | assert((!DT || L->isLCSSAForm(*DT)) && "Expected LCSSA!"); |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 485 | 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 Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 539 | for (PHINode &P : ExitBlock->phis()) { |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 540 | // 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 Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 544 | P.setIncomingBlock(PredIndex, Preheader); |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 545 | // 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 Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 552 | for (unsigned i = 0, e = P.getNumIncomingValues() - 1; i != e; ++i) |
| 553 | P.removeIncomingValue(e - i, false); |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 554 | |
Benjamin Kramer | c7fc81e | 2017-12-30 15:27:33 +0000 | [diff] [blame] | 555 | assert((P.getNumIncomingValues() == 1 && |
| 556 | P.getIncomingBlock(PredIndex) == Preheader) && |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 557 | "Should have exactly one value and that's from the preheader!"); |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 558 | } |
| 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 Sima | 21a8b60 | 2018-08-03 05:08:17 +0000 | [diff] [blame] | 566 | DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager); |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 567 | if (DT) { |
| 568 | // Update the dominator tree by informing it about the new edge from the |
Chijun Sima | f131d61 | 2019-02-22 05:41:43 +0000 | [diff] [blame] | 569 | // preheader to the exit and the removed edge. |
| 570 | DTU.applyUpdates({{DominatorTree::Insert, Preheader, ExitBlock}, |
| 571 | {DominatorTree::Delete, Preheader, L->getHeader()}}); |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 572 | } |
| 573 | |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 574 | // Use a map to unique and a vector to guarantee deterministic ordering. |
Davide Italiano | 8ee59ca | 2018-12-13 01:11:52 +0000 | [diff] [blame] | 575 | llvm::SmallDenseSet<std::pair<DIVariable *, DIExpression *>, 4> DeadDebugSet; |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 576 | llvm::SmallVector<DbgVariableIntrinsic *, 4> DeadDebugInst; |
| 577 | |
Serguei Katkov | a757d65 | 2018-01-12 07:24:43 +0000 | [diff] [blame] | 578 | // 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 Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 602 | auto *DVI = dyn_cast<DbgVariableIntrinsic>(&I); |
| 603 | if (!DVI) |
| 604 | continue; |
Davide Italiano | 8ee59ca | 2018-12-13 01:11:52 +0000 | [diff] [blame] | 605 | auto Key = DeadDebugSet.find({DVI->getVariable(), DVI->getExpression()}); |
| 606 | if (Key != DeadDebugSet.end()) |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 607 | continue; |
Davide Italiano | 8ee59ca | 2018-12-13 01:11:52 +0000 | [diff] [blame] | 608 | DeadDebugSet.insert({DVI->getVariable(), DVI->getExpression()}); |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 609 | DeadDebugInst.push_back(DVI); |
Serguei Katkov | a757d65 | 2018-01-12 07:24:43 +0000 | [diff] [blame] | 610 | } |
| 611 | |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 612 | // 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 Lebedev | e5be660 | 2019-05-05 18:59:12 +0000 | [diff] [blame] | 618 | 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 Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 622 | for (auto *DVI : DeadDebugInst) |
Roman Lebedev | e5be660 | 2019-05-05 18:59:12 +0000 | [diff] [blame] | 623 | DIB.insertDbgValueIntrinsic(UndefValue::get(Builder.getInt32Ty()), |
| 624 | DVI->getVariable(), DVI->getExpression(), |
| 625 | DVI->getDebugLoc(), InsertDbgValueBefore); |
Davide Italiano | 744c3c3 | 2018-12-12 23:32:35 +0000 | [diff] [blame] | 626 | |
Marcello Maggioni | df3e71e | 2017-10-04 20:42:46 +0000 | [diff] [blame] | 627 | // 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 Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 654 | Optional<unsigned> llvm::getLoopEstimatedTripCount(Loop *L) { |
Serguei Katkov | 45c43e7 | 2019-07-15 06:42:39 +0000 | [diff] [blame] | 655 | // Support loops with an exiting latch and other existing exists only |
| 656 | // deoptimize. |
Dehao Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 657 | |
Hiroshi Inoue | d24ddcd | 2018-01-19 10:55:29 +0000 | [diff] [blame] | 658 | // Get the branch weights for the loop's backedge. |
Serguei Katkov | 45c43e7 | 2019-07-15 06:42:39 +0000 | [diff] [blame] | 659 | 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 Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 664 | 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 Katkov | 45c43e7 | 2019-07-15 06:42:39 +0000 | [diff] [blame] | 670 | 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 Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 677 | // 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 Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 680 | uint64_t TrueVal, FalseVal; |
Michael Kuperstein | b151a64 | 2016-11-30 21:13:57 +0000 | [diff] [blame] | 681 | if (!LatchBR->extractProfMetadata(TrueVal, FalseVal)) |
Dehao Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 682 | return None; |
| 683 | |
Michael Kuperstein | b151a64 | 2016-11-30 21:13:57 +0000 | [diff] [blame] | 684 | if (!TrueVal || !FalseVal) |
| 685 | return 0; |
Dehao Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 686 | |
Michael Kuperstein | b151a64 | 2016-11-30 21:13:57 +0000 | [diff] [blame] | 687 | // Divide the count of the backedge by the count of the edge exiting the loop, |
| 688 | // rounding to nearest. |
Dehao Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 689 | if (LatchBR->getSuccessor(0) == L->getHeader()) |
Michael Kuperstein | b151a64 | 2016-11-30 21:13:57 +0000 | [diff] [blame] | 690 | return (TrueVal + (FalseVal / 2)) / FalseVal; |
Dehao Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 691 | else |
Michael Kuperstein | b151a64 | 2016-11-30 21:13:57 +0000 | [diff] [blame] | 692 | return (FalseVal + (TrueVal / 2)) / TrueVal; |
Dehao Chen | 41d72a8 | 2016-11-17 01:17:02 +0000 | [diff] [blame] | 693 | } |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 694 | |
David Green | 6cb6478 | 2018-08-15 10:59:41 +0000 | [diff] [blame] | 695 | bool llvm::hasIterationCountInvariantInParent(Loop *InnerLoop, |
| 696 | ScalarEvolution &SE) { |
David Green | 395b80c | 2018-08-11 06:57:28 +0000 | [diff] [blame] | 697 | 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 TV | 6594dc3 | 2018-09-10 05:05:08 +0000 | [diff] [blame] | 717 | Value *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 Pilgrim | 23c2182 | 2018-04-09 15:44:20 +0000 | [diff] [blame] | 762 | // Helper to generate an ordered reduction. |
| 763 | Value * |
| 764 | llvm::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 TV | 6594dc3 | 2018-09-10 05:05:08 +0000 | [diff] [blame] | 783 | Result = createMinMaxOp(Builder, MinMaxKind, Result, Ext); |
Simon Pilgrim | 23c2182 | 2018-04-09 15:44:20 +0000 | [diff] [blame] | 784 | } |
| 785 | |
| 786 | if (!RedOps.empty()) |
| 787 | propagateIRFlags(Result, RedOps); |
| 788 | } |
| 789 | |
| 790 | return Result; |
| 791 | } |
| 792 | |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 793 | // Helper to generate a log2 shuffle reduction. |
Amara Emerson | 836b0f4 | 2017-05-10 09:42:49 +0000 | [diff] [blame] | 794 | Value * |
| 795 | llvm::getShuffleReduction(IRBuilder<> &Builder, Value *Src, unsigned Op, |
| 796 | RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind, |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 797 | ArrayRef<Value *> RedOps) { |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 798 | 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 Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 820 | // The builder propagates its fast-math-flags setting. |
| 821 | TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf, |
| 822 | "bin.rdx"); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 823 | } else { |
| 824 | assert(MinMaxKind != RecurrenceDescriptor::MRK_Invalid && |
| 825 | "Invalid min/max"); |
Vikram TV | 6594dc3 | 2018-09-10 05:05:08 +0000 | [diff] [blame] | 826 | TmpVec = createMinMaxOp(Builder, MinMaxKind, TmpVec, Shuf); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 827 | } |
| 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). |
| 837 | Value *llvm::createSimpleTargetReduction( |
| 838 | IRBuilder<> &Builder, const TargetTransformInfo *TTI, unsigned Opcode, |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 839 | Value *Src, TargetTransformInfo::ReductionFlags Flags, |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 840 | ArrayRef<Value *> RedOps) { |
| 841 | assert(isa<VectorType>(Src->getType()) && "Type must be a vector"); |
| 842 | |
Vikram TV | 7e98d69 | 2018-09-12 01:59:43 +0000 | [diff] [blame] | 843 | std::function<Value *()> BuildFunc; |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 844 | using RD = RecurrenceDescriptor; |
| 845 | RD::MinMaxRecurrenceKind MinMaxKind = RD::MRK_Invalid; |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 846 | |
| 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 Smalen | cbeb563 | 2019-06-11 08:22:10 +0000 | [diff] [blame] | 865 | auto Rdx = Builder.CreateFAddReduce( |
| 866 | Constant::getNullValue(Src->getType()->getVectorElementType()), Src); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 867 | return Rdx; |
| 868 | }; |
| 869 | break; |
| 870 | case Instruction::FMul: |
| 871 | BuildFunc = [&]() { |
Sander de Smalen | cbeb563 | 2019-06-11 08:22:10 +0000 | [diff] [blame] | 872 | Type *Ty = Src->getType()->getVectorElementType(); |
| 873 | auto Rdx = Builder.CreateFMulReduce(ConstantFP::get(Ty, 1.0), Src); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 874 | 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 Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 905 | return getShuffleReduction(Builder, Src, Opcode, MinMaxKind, RedOps); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 906 | } |
| 907 | |
| 908 | /// Create a vector reduction using a given recurrence descriptor. |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 909 | Value *llvm::createTargetReduction(IRBuilder<> &B, |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 910 | const TargetTransformInfo *TTI, |
| 911 | RecurrenceDescriptor &Desc, Value *Src, |
| 912 | bool NoNaN) { |
| 913 | // TODO: Support in-order reductions based on the recurrence descriptor. |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 914 | using RD = RecurrenceDescriptor; |
| 915 | RD::RecurrenceKind RecKind = Desc.getRecurrenceKind(); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 916 | TargetTransformInfo::ReductionFlags Flags; |
| 917 | Flags.NoNaN = NoNaN; |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 918 | |
| 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 Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 924 | switch (RecKind) { |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 925 | case RD::RK_FloatAdd: |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 926 | return createSimpleTargetReduction(B, TTI, Instruction::FAdd, Src, Flags); |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 927 | case RD::RK_FloatMult: |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 928 | return createSimpleTargetReduction(B, TTI, Instruction::FMul, Src, Flags); |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 929 | case RD::RK_IntegerAdd: |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 930 | return createSimpleTargetReduction(B, TTI, Instruction::Add, Src, Flags); |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 931 | case RD::RK_IntegerMult: |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 932 | return createSimpleTargetReduction(B, TTI, Instruction::Mul, Src, Flags); |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 933 | case RD::RK_IntegerAnd: |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 934 | return createSimpleTargetReduction(B, TTI, Instruction::And, Src, Flags); |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 935 | case RD::RK_IntegerOr: |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 936 | return createSimpleTargetReduction(B, TTI, Instruction::Or, Src, Flags); |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 937 | case RD::RK_IntegerXor: |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 938 | return createSimpleTargetReduction(B, TTI, Instruction::Xor, Src, Flags); |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 939 | 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 Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 943 | return createSimpleTargetReduction(B, TTI, Instruction::ICmp, Src, Flags); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 944 | } |
Sanjay Patel | 3e069f5 | 2017-12-06 19:37:00 +0000 | [diff] [blame] | 945 | case RD::RK_FloatMinMax: { |
| 946 | Flags.IsMaxOp = Desc.getMinMaxRecurrenceKind() == RD::MRK_FloatMax; |
Sanjay Patel | ad62a3a | 2019-06-05 14:58:04 +0000 | [diff] [blame] | 947 | return createSimpleTargetReduction(B, TTI, Instruction::FCmp, Src, Flags); |
Amara Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 948 | } |
| 949 | default: |
| 950 | llvm_unreachable("Unhandled RecKind"); |
| 951 | } |
| 952 | } |
| 953 | |
Dinar Temirbulatov | a61f4b8 | 2017-07-19 10:02:07 +0000 | [diff] [blame] | 954 | void 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 Emerson | cf9daa3 | 2017-05-09 10:43:25 +0000 | [diff] [blame] | 970 | } |
| 971 | } |
Max Kazantsev | a78dc4d | 2019-01-15 09:51:34 +0000 | [diff] [blame] | 972 | |
| 973 | bool 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 | |
| 980 | bool 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 | |
| 987 | bool 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 | |
| 998 | bool 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 | } |