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