1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This pass performs loop invariant code motion, attempting to remove as much 11 // code from the body of a loop as possible. It does this by either hoisting 12 // code into the preheader block, or by sinking code to the exit blocks if it is 13 // safe. This pass also promotes must-aliased memory locations in the loop to 14 // live in registers, thus hoisting and sinking "invariant" loads and stores. 15 // 16 // This pass uses alias analysis for two purposes: 17 // 18 // 1. Moving loop invariant loads and calls out of loops. If we can determine 19 // that a load or call inside of a loop never aliases anything stored to, 20 // we can hoist it or sink it like any other instruction. 21 // 2. Scalar Promotion of Memory - If there is a store instruction inside of 22 // the loop, we try to move the store to happen AFTER the loop instead of 23 // inside of the loop. This can only happen if a few conditions are true: 24 // A. The pointer stored through is loop invariant 25 // B. There are no stores or loads in the loop which _may_ alias the 26 // pointer. There are no calls in the loop which mod/ref the pointer. 27 // If these conditions are true, we can promote the loads and stores in the 28 // loop of the pointer to use a temporary alloca'd variable. We then use 29 // the SSAUpdater to construct the appropriate SSA form for the value. 30 // 31 //===----------------------------------------------------------------------===// 32 33 #include "llvm/ADT/Statistic.h" 34 #include "llvm/Analysis/AliasAnalysis.h" 35 #include "llvm/Analysis/AliasSetTracker.h" 36 #include "llvm/Analysis/BasicAliasAnalysis.h" 37 #include "llvm/Analysis/CaptureTracking.h" 38 #include "llvm/Analysis/ConstantFolding.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/Loads.h" 41 #include "llvm/Analysis/LoopInfo.h" 42 #include "llvm/Analysis/LoopPass.h" 43 #include "llvm/Analysis/MemoryBuiltins.h" 44 #include "llvm/Analysis/ScalarEvolution.h" 45 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 46 #include "llvm/Analysis/TargetLibraryInfo.h" 47 #include "llvm/Analysis/ValueTracking.h" 48 #include "llvm/IR/CFG.h" 49 #include "llvm/IR/Constants.h" 50 #include "llvm/IR/DataLayout.h" 51 #include "llvm/IR/DerivedTypes.h" 52 #include "llvm/IR/Dominators.h" 53 #include "llvm/IR/Instructions.h" 54 #include "llvm/IR/IntrinsicInst.h" 55 #include "llvm/IR/LLVMContext.h" 56 #include "llvm/IR/Metadata.h" 57 #include "llvm/IR/PredIteratorCache.h" 58 #include "llvm/Support/CommandLine.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include "llvm/Transforms/Scalar.h" 62 #include "llvm/Transforms/Utils/Local.h" 63 #include "llvm/Transforms/Utils/LoopUtils.h" 64 #include "llvm/Transforms/Utils/SSAUpdater.h" 65 #include <algorithm> 66 #include <utility> 67 using namespace llvm; 68 69 #define DEBUG_TYPE "licm" 70 71 STATISTIC(NumSunk, "Number of instructions sunk out of loop"); 72 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop"); 73 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk"); 74 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk"); 75 STATISTIC(NumPromoted, "Number of memory locations promoted to registers"); 76 77 static cl::opt<bool> 78 DisablePromotion("disable-licm-promotion", cl::Hidden, 79 cl::desc("Disable memory promotion in LICM pass")); 80 81 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI); 82 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop, 83 const LoopSafetyInfo *SafetyInfo); 84 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 85 const LoopSafetyInfo *SafetyInfo); 86 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 87 const Loop *CurLoop, AliasSetTracker *CurAST, 88 const LoopSafetyInfo *SafetyInfo); 89 static bool isSafeToExecuteUnconditionally(const Instruction &Inst, 90 const DominatorTree *DT, 91 const TargetLibraryInfo *TLI, 92 const Loop *CurLoop, 93 const LoopSafetyInfo *SafetyInfo, 94 const Instruction *CtxI = nullptr); 95 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 96 const AAMDNodes &AAInfo, 97 AliasSetTracker *CurAST); 98 static Instruction * 99 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 100 const LoopInfo *LI, 101 const LoopSafetyInfo *SafetyInfo); 102 static bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, 103 DominatorTree *DT, TargetLibraryInfo *TLI, 104 Loop *CurLoop, AliasSetTracker *CurAST, 105 LoopSafetyInfo *SafetyInfo); 106 107 namespace { 108 struct LICM : public LoopPass { 109 static char ID; // Pass identification, replacement for typeid 110 LICM() : LoopPass(ID) { 111 initializeLICMPass(*PassRegistry::getPassRegistry()); 112 } 113 114 bool runOnLoop(Loop *L, LPPassManager &LPM) override; 115 116 /// This transformation requires natural loop information & requires that 117 /// loop preheaders be inserted into the CFG... 118 /// 119 void getAnalysisUsage(AnalysisUsage &AU) const override { 120 AU.setPreservesCFG(); 121 AU.addRequired<TargetLibraryInfoWrapperPass>(); 122 getLoopAnalysisUsage(AU); 123 } 124 125 using llvm::Pass::doFinalization; 126 127 bool doFinalization() override { 128 assert(LoopToAliasSetMap.empty() && "Didn't free loop alias sets"); 129 return false; 130 } 131 132 private: 133 AliasAnalysis *AA; // Current AliasAnalysis information 134 LoopInfo *LI; // Current LoopInfo 135 DominatorTree *DT; // Dominator Tree for the current Loop. 136 137 TargetLibraryInfo *TLI; // TargetLibraryInfo for constant folding. 138 139 // State that is updated as we process loops. 140 bool Changed; // Set to true when we change anything. 141 BasicBlock *Preheader; // The preheader block of the current loop... 142 Loop *CurLoop; // The current loop we are working on... 143 AliasSetTracker *CurAST; // AliasSet information for the current loop... 144 DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap; 145 146 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info. 147 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, 148 Loop *L) override; 149 150 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias 151 /// set. 152 void deleteAnalysisValue(Value *V, Loop *L) override; 153 154 /// Simple Analysis hook. Delete loop L from alias set map. 155 void deleteAnalysisLoop(Loop *L) override; 156 157 AliasSetTracker *collectAliasInfoForLoop(Loop *L); 158 }; 159 } 160 161 char LICM::ID = 0; 162 INITIALIZE_PASS_BEGIN(LICM, "licm", "Loop Invariant Code Motion", false, false) 163 INITIALIZE_PASS_DEPENDENCY(LoopPass) 164 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 165 INITIALIZE_PASS_END(LICM, "licm", "Loop Invariant Code Motion", false, false) 166 167 Pass *llvm::createLICMPass() { return new LICM(); } 168 169 /// Hoist expressions out of the specified loop. Note, alias info for inner 170 /// loop is not preserved so it is not a good idea to run LICM multiple 171 /// times on one loop. 172 /// 173 bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) { 174 if (skipLoop(L)) 175 return false; 176 177 Changed = false; 178 179 // Get our Loop and Alias Analysis information... 180 LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 181 AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 182 DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 183 184 TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(); 185 186 assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form."); 187 188 CurAST = collectAliasInfoForLoop(L); 189 190 CurLoop = L; 191 192 // Get the preheader block to move instructions into... 193 Preheader = L->getLoopPreheader(); 194 195 // Compute loop safety information. 196 LoopSafetyInfo SafetyInfo; 197 computeLoopSafetyInfo(&SafetyInfo, CurLoop); 198 199 // We want to visit all of the instructions in this loop... that are not parts 200 // of our subloops (they have already had their invariants hoisted out of 201 // their loop, into this loop, so there is no need to process the BODIES of 202 // the subloops). 203 // 204 // Traverse the body of the loop in depth first order on the dominator tree so 205 // that we are guaranteed to see definitions before we see uses. This allows 206 // us to sink instructions in one pass, without iteration. After sinking 207 // instructions, we perform another pass to hoist them out of the loop. 208 // 209 if (L->hasDedicatedExits()) 210 Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, CurLoop, 211 CurAST, &SafetyInfo); 212 if (Preheader) 213 Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, 214 CurLoop, CurAST, &SafetyInfo); 215 216 // Now that all loop invariants have been removed from the loop, promote any 217 // memory references to scalars that we can. 218 if (!DisablePromotion && (Preheader || L->hasDedicatedExits())) { 219 SmallVector<BasicBlock *, 8> ExitBlocks; 220 SmallVector<Instruction *, 8> InsertPts; 221 PredIteratorCache PIC; 222 223 // Loop over all of the alias sets in the tracker object. 224 for (AliasSet &AS : *CurAST) 225 Changed |= 226 promoteLoopAccessesToScalars(AS, ExitBlocks, InsertPts, PIC, LI, DT, 227 TLI, CurLoop, CurAST, &SafetyInfo); 228 229 // Once we have promoted values across the loop body we have to recursively 230 // reform LCSSA as any nested loop may now have values defined within the 231 // loop used in the outer loop. 232 // FIXME: This is really heavy handed. It would be a bit better to use an 233 // SSAUpdater strategy during promotion that was LCSSA aware and reformed 234 // it as it went. 235 if (Changed) { 236 auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>(); 237 formLCSSARecursively(*L, *DT, LI, SEWP ? &SEWP->getSE() : nullptr); 238 } 239 } 240 241 // Check that neither this loop nor its parent have had LCSSA broken. LICM is 242 // specifically moving instructions across the loop boundary and so it is 243 // especially in need of sanity checking here. 244 assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!"); 245 assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) && 246 "Parent loop not left in LCSSA form after LICM!"); 247 248 // Clear out loops state information for the next iteration 249 CurLoop = nullptr; 250 Preheader = nullptr; 251 252 // If this loop is nested inside of another one, save the alias information 253 // for when we process the outer loop. 254 if (L->getParentLoop()) 255 LoopToAliasSetMap[L] = CurAST; 256 else 257 delete CurAST; 258 259 if (Changed) 260 if (auto *SEWP = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>()) 261 SEWP->getSE().forgetLoopDispositions(L); 262 return Changed; 263 } 264 265 /// Walk the specified region of the CFG (defined by all blocks dominated by 266 /// the specified block, and that are in the current loop) in reverse depth 267 /// first order w.r.t the DominatorTree. This allows us to visit uses before 268 /// definitions, allowing us to sink a loop body in one pass without iteration. 269 /// 270 bool llvm::sinkRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 271 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 272 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) { 273 274 // Verify inputs. 275 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 276 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && 277 "Unexpected input to sinkRegion"); 278 279 BasicBlock *BB = N->getBlock(); 280 // If this subregion is not in the top level loop at all, exit. 281 if (!CurLoop->contains(BB)) 282 return false; 283 284 // We are processing blocks in reverse dfo, so process children first. 285 bool Changed = false; 286 const std::vector<DomTreeNode *> &Children = N->getChildren(); 287 for (DomTreeNode *Child : Children) 288 Changed |= sinkRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo); 289 290 // Only need to process the contents of this block if it is not part of a 291 // subloop (which would already have been processed). 292 if (inSubLoop(BB, CurLoop, LI)) 293 return Changed; 294 295 for (BasicBlock::iterator II = BB->end(); II != BB->begin();) { 296 Instruction &I = *--II; 297 298 // If the instruction is dead, we would try to sink it because it isn't used 299 // in the loop, instead, just delete it. 300 if (isInstructionTriviallyDead(&I, TLI)) { 301 DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n'); 302 ++II; 303 CurAST->deleteValue(&I); 304 I.eraseFromParent(); 305 Changed = true; 306 continue; 307 } 308 309 // Check to see if we can sink this instruction to the exit blocks 310 // of the loop. We can do this if the all users of the instruction are 311 // outside of the loop. In this case, it doesn't even matter if the 312 // operands of the instruction are loop invariant. 313 // 314 if (isNotUsedInLoop(I, CurLoop, SafetyInfo) && 315 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo)) { 316 ++II; 317 Changed |= sink(I, LI, DT, CurLoop, CurAST, SafetyInfo); 318 } 319 } 320 return Changed; 321 } 322 323 /// Walk the specified region of the CFG (defined by all blocks dominated by 324 /// the specified block, and that are in the current loop) in depth first 325 /// order w.r.t the DominatorTree. This allows us to visit definitions before 326 /// uses, allowing us to hoist a loop body in one pass without iteration. 327 /// 328 bool llvm::hoistRegion(DomTreeNode *N, AliasAnalysis *AA, LoopInfo *LI, 329 DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop, 330 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) { 331 // Verify inputs. 332 assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr && 333 CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr && 334 "Unexpected input to hoistRegion"); 335 336 BasicBlock *BB = N->getBlock(); 337 338 // If this subregion is not in the top level loop at all, exit. 339 if (!CurLoop->contains(BB)) 340 return false; 341 342 // Only need to process the contents of this block if it is not part of a 343 // subloop (which would already have been processed). 344 bool Changed = false; 345 if (!inSubLoop(BB, CurLoop, LI)) 346 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) { 347 Instruction &I = *II++; 348 // Try constant folding this instruction. If all the operands are 349 // constants, it is technically hoistable, but it would be better to just 350 // fold it. 351 if (Constant *C = ConstantFoldInstruction( 352 &I, I.getModule()->getDataLayout(), TLI)) { 353 DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C << '\n'); 354 CurAST->copyValue(&I, C); 355 CurAST->deleteValue(&I); 356 I.replaceAllUsesWith(C); 357 I.eraseFromParent(); 358 continue; 359 } 360 361 // Try hoisting the instruction out to the preheader. We can only do this 362 // if all of the operands of the instruction are loop invariant and if it 363 // is safe to hoist the instruction. 364 // 365 if (CurLoop->hasLoopInvariantOperands(&I) && 366 canSinkOrHoistInst(I, AA, DT, TLI, CurLoop, CurAST, SafetyInfo) && 367 isSafeToExecuteUnconditionally( 368 I, DT, TLI, CurLoop, SafetyInfo, 369 CurLoop->getLoopPreheader()->getTerminator())) 370 Changed |= hoist(I, DT, CurLoop, SafetyInfo); 371 } 372 373 const std::vector<DomTreeNode *> &Children = N->getChildren(); 374 for (DomTreeNode *Child : Children) 375 Changed |= hoistRegion(Child, AA, LI, DT, TLI, CurLoop, CurAST, SafetyInfo); 376 return Changed; 377 } 378 379 /// Computes loop safety information, checks loop body & header 380 /// for the possibility of may throw exception. 381 /// 382 void llvm::computeLoopSafetyInfo(LoopSafetyInfo *SafetyInfo, Loop *CurLoop) { 383 assert(CurLoop != nullptr && "CurLoop cant be null"); 384 BasicBlock *Header = CurLoop->getHeader(); 385 // Setting default safety values. 386 SafetyInfo->MayThrow = false; 387 SafetyInfo->HeaderMayThrow = false; 388 // Iterate over header and compute safety info. 389 for (BasicBlock::iterator I = Header->begin(), E = Header->end(); 390 (I != E) && !SafetyInfo->HeaderMayThrow; ++I) 391 SafetyInfo->HeaderMayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I); 392 393 SafetyInfo->MayThrow = SafetyInfo->HeaderMayThrow; 394 // Iterate over loop instructions and compute safety info. 395 for (Loop::block_iterator BB = CurLoop->block_begin(), 396 BBE = CurLoop->block_end(); 397 (BB != BBE) && !SafetyInfo->MayThrow; ++BB) 398 for (BasicBlock::iterator I = (*BB)->begin(), E = (*BB)->end(); 399 (I != E) && !SafetyInfo->MayThrow; ++I) 400 SafetyInfo->MayThrow |= !isGuaranteedToTransferExecutionToSuccessor(&*I); 401 402 // Compute funclet colors if we might sink/hoist in a function with a funclet 403 // personality routine. 404 Function *Fn = CurLoop->getHeader()->getParent(); 405 if (Fn->hasPersonalityFn()) 406 if (Constant *PersonalityFn = Fn->getPersonalityFn()) 407 if (isFuncletEHPersonality(classifyEHPersonality(PersonalityFn))) 408 SafetyInfo->BlockColors = colorEHFunclets(*Fn); 409 } 410 411 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this 412 /// instruction. 413 /// 414 bool canSinkOrHoistInst(Instruction &I, AliasAnalysis *AA, DominatorTree *DT, 415 TargetLibraryInfo *TLI, Loop *CurLoop, 416 AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) { 417 // Loads have extra constraints we have to verify before we can hoist them. 418 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) { 419 if (!LI->isUnordered()) 420 return false; // Don't hoist volatile/atomic loads! 421 422 // Loads from constant memory are always safe to move, even if they end up 423 // in the same alias set as something that ends up being modified. 424 if (AA->pointsToConstantMemory(LI->getOperand(0))) 425 return true; 426 if (LI->getMetadata(LLVMContext::MD_invariant_load)) 427 return true; 428 429 // Don't hoist loads which have may-aliased stores in loop. 430 uint64_t Size = 0; 431 if (LI->getType()->isSized()) 432 Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType()); 433 434 AAMDNodes AAInfo; 435 LI->getAAMetadata(AAInfo); 436 437 return !pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST); 438 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) { 439 // Don't sink or hoist dbg info; it's legal, but not useful. 440 if (isa<DbgInfoIntrinsic>(I)) 441 return false; 442 443 // Don't sink calls which can throw. 444 if (CI->mayThrow()) 445 return false; 446 447 // Handle simple cases by querying alias analysis. 448 FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI); 449 if (Behavior == FMRB_DoesNotAccessMemory) 450 return true; 451 if (AliasAnalysis::onlyReadsMemory(Behavior)) { 452 // A readonly argmemonly function only reads from memory pointed to by 453 // it's arguments with arbitrary offsets. If we can prove there are no 454 // writes to this memory in the loop, we can hoist or sink. 455 if (AliasAnalysis::onlyAccessesArgPointees(Behavior)) { 456 for (Value *Op : CI->arg_operands()) 457 if (Op->getType()->isPointerTy() && 458 pointerInvalidatedByLoop(Op, MemoryLocation::UnknownSize, 459 AAMDNodes(), CurAST)) 460 return false; 461 return true; 462 } 463 // If this call only reads from memory and there are no writes to memory 464 // in the loop, we can hoist or sink the call as appropriate. 465 bool FoundMod = false; 466 for (AliasSet &AS : *CurAST) { 467 if (!AS.isForwardingAliasSet() && AS.isMod()) { 468 FoundMod = true; 469 break; 470 } 471 } 472 if (!FoundMod) 473 return true; 474 } 475 476 // FIXME: This should use mod/ref information to see if we can hoist or 477 // sink the call. 478 479 return false; 480 } 481 482 // Only these instructions are hoistable/sinkable. 483 if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) && 484 !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) && 485 !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) && 486 !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) && 487 !isa<InsertValueInst>(I)) 488 return false; 489 490 // TODO: Plumb the context instruction through to make hoisting and sinking 491 // more powerful. Hoisting of loads already works due to the special casing 492 // above. 493 return isSafeToExecuteUnconditionally(I, DT, TLI, CurLoop, SafetyInfo, 494 nullptr); 495 } 496 497 /// Returns true if a PHINode is a trivially replaceable with an 498 /// Instruction. 499 /// This is true when all incoming values are that instruction. 500 /// This pattern occurs most often with LCSSA PHI nodes. 501 /// 502 static bool isTriviallyReplacablePHI(const PHINode &PN, const Instruction &I) { 503 for (const Value *IncValue : PN.incoming_values()) 504 if (IncValue != &I) 505 return false; 506 507 return true; 508 } 509 510 /// Return true if the only users of this instruction are outside of 511 /// the loop. If this is true, we can sink the instruction to the exit 512 /// blocks of the loop. 513 /// 514 static bool isNotUsedInLoop(const Instruction &I, const Loop *CurLoop, 515 const LoopSafetyInfo *SafetyInfo) { 516 const auto &BlockColors = SafetyInfo->BlockColors; 517 for (const User *U : I.users()) { 518 const Instruction *UI = cast<Instruction>(U); 519 if (const PHINode *PN = dyn_cast<PHINode>(UI)) { 520 const BasicBlock *BB = PN->getParent(); 521 // We cannot sink uses in catchswitches. 522 if (isa<CatchSwitchInst>(BB->getTerminator())) 523 return false; 524 525 // We need to sink a callsite to a unique funclet. Avoid sinking if the 526 // phi use is too muddled. 527 if (isa<CallInst>(I)) 528 if (!BlockColors.empty() && 529 BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1) 530 return false; 531 532 // A PHI node where all of the incoming values are this instruction are 533 // special -- they can just be RAUW'ed with the instruction and thus 534 // don't require a use in the predecessor. This is a particular important 535 // special case because it is the pattern found in LCSSA form. 536 if (isTriviallyReplacablePHI(*PN, I)) { 537 if (CurLoop->contains(PN)) 538 return false; 539 else 540 continue; 541 } 542 543 // Otherwise, PHI node uses occur in predecessor blocks if the incoming 544 // values. Check for such a use being inside the loop. 545 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) 546 if (PN->getIncomingValue(i) == &I) 547 if (CurLoop->contains(PN->getIncomingBlock(i))) 548 return false; 549 550 continue; 551 } 552 553 if (CurLoop->contains(UI)) 554 return false; 555 } 556 return true; 557 } 558 559 static Instruction * 560 CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, 561 const LoopInfo *LI, 562 const LoopSafetyInfo *SafetyInfo) { 563 Instruction *New; 564 if (auto *CI = dyn_cast<CallInst>(&I)) { 565 const auto &BlockColors = SafetyInfo->BlockColors; 566 567 // Sinking call-sites need to be handled differently from other 568 // instructions. The cloned call-site needs a funclet bundle operand 569 // appropriate for it's location in the CFG. 570 SmallVector<OperandBundleDef, 1> OpBundles; 571 for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles(); 572 BundleIdx != BundleEnd; ++BundleIdx) { 573 OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx); 574 if (Bundle.getTagID() == LLVMContext::OB_funclet) 575 continue; 576 577 OpBundles.emplace_back(Bundle); 578 } 579 580 if (!BlockColors.empty()) { 581 const ColorVector &CV = BlockColors.find(&ExitBlock)->second; 582 assert(CV.size() == 1 && "non-unique color for exit block!"); 583 BasicBlock *BBColor = CV.front(); 584 Instruction *EHPad = BBColor->getFirstNonPHI(); 585 if (EHPad->isEHPad()) 586 OpBundles.emplace_back("funclet", EHPad); 587 } 588 589 New = CallInst::Create(CI, OpBundles); 590 } else { 591 New = I.clone(); 592 } 593 594 ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New); 595 if (!I.getName().empty()) 596 New->setName(I.getName() + ".le"); 597 598 // Build LCSSA PHI nodes for any in-loop operands. Note that this is 599 // particularly cheap because we can rip off the PHI node that we're 600 // replacing for the number and blocks of the predecessors. 601 // OPT: If this shows up in a profile, we can instead finish sinking all 602 // invariant instructions, and then walk their operands to re-establish 603 // LCSSA. That will eliminate creating PHI nodes just to nuke them when 604 // sinking bottom-up. 605 for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE; 606 ++OI) 607 if (Instruction *OInst = dyn_cast<Instruction>(*OI)) 608 if (Loop *OLoop = LI->getLoopFor(OInst->getParent())) 609 if (!OLoop->contains(&PN)) { 610 PHINode *OpPN = 611 PHINode::Create(OInst->getType(), PN.getNumIncomingValues(), 612 OInst->getName() + ".lcssa", &ExitBlock.front()); 613 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) 614 OpPN->addIncoming(OInst, PN.getIncomingBlock(i)); 615 *OI = OpPN; 616 } 617 return New; 618 } 619 620 /// When an instruction is found to only be used outside of the loop, this 621 /// function moves it to the exit blocks and patches up SSA form as needed. 622 /// This method is guaranteed to remove the original instruction from its 623 /// position, and may either delete it or move it to outside of the loop. 624 /// 625 static bool sink(Instruction &I, const LoopInfo *LI, const DominatorTree *DT, 626 const Loop *CurLoop, AliasSetTracker *CurAST, 627 const LoopSafetyInfo *SafetyInfo) { 628 DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n"); 629 bool Changed = false; 630 if (isa<LoadInst>(I)) 631 ++NumMovedLoads; 632 else if (isa<CallInst>(I)) 633 ++NumMovedCalls; 634 ++NumSunk; 635 Changed = true; 636 637 #ifndef NDEBUG 638 SmallVector<BasicBlock *, 32> ExitBlocks; 639 CurLoop->getUniqueExitBlocks(ExitBlocks); 640 SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(), 641 ExitBlocks.end()); 642 #endif 643 644 // Clones of this instruction. Don't create more than one per exit block! 645 SmallDenseMap<BasicBlock *, Instruction *, 32> SunkCopies; 646 647 // If this instruction is only used outside of the loop, then all users are 648 // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of 649 // the instruction. 650 while (!I.use_empty()) { 651 Value::user_iterator UI = I.user_begin(); 652 auto *User = cast<Instruction>(*UI); 653 if (!DT->isReachableFromEntry(User->getParent())) { 654 User->replaceUsesOfWith(&I, UndefValue::get(I.getType())); 655 continue; 656 } 657 // The user must be a PHI node. 658 PHINode *PN = cast<PHINode>(User); 659 660 // Surprisingly, instructions can be used outside of loops without any 661 // exits. This can only happen in PHI nodes if the incoming block is 662 // unreachable. 663 Use &U = UI.getUse(); 664 BasicBlock *BB = PN->getIncomingBlock(U); 665 if (!DT->isReachableFromEntry(BB)) { 666 U = UndefValue::get(I.getType()); 667 continue; 668 } 669 670 BasicBlock *ExitBlock = PN->getParent(); 671 assert(ExitBlockSet.count(ExitBlock) && 672 "The LCSSA PHI is not in an exit block!"); 673 674 Instruction *New; 675 auto It = SunkCopies.find(ExitBlock); 676 if (It != SunkCopies.end()) 677 New = It->second; 678 else 679 New = SunkCopies[ExitBlock] = 680 CloneInstructionInExitBlock(I, *ExitBlock, *PN, LI, SafetyInfo); 681 682 PN->replaceAllUsesWith(New); 683 PN->eraseFromParent(); 684 } 685 686 CurAST->deleteValue(&I); 687 I.eraseFromParent(); 688 return Changed; 689 } 690 691 /// When an instruction is found to only use loop invariant operands that 692 /// is safe to hoist, this instruction is called to do the dirty work. 693 /// 694 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, 695 const LoopSafetyInfo *SafetyInfo) { 696 auto *Preheader = CurLoop->getLoopPreheader(); 697 DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I 698 << "\n"); 699 700 // Metadata can be dependent on conditions we are hoisting above. 701 // Conservatively strip all metadata on the instruction unless we were 702 // guaranteed to execute I if we entered the loop, in which case the metadata 703 // is valid in the loop preheader. 704 if (I.hasMetadataOtherThanDebugLoc() && 705 // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning 706 // time in isGuaranteedToExecute if we don't actually have anything to 707 // drop. It is a compile time optimization, not required for correctness. 708 !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo)) 709 I.dropUnknownNonDebugMetadata(); 710 711 // Move the new node to the Preheader, before its terminator. 712 I.moveBefore(Preheader->getTerminator()); 713 714 if (isa<LoadInst>(I)) 715 ++NumMovedLoads; 716 else if (isa<CallInst>(I)) 717 ++NumMovedCalls; 718 ++NumHoisted; 719 return true; 720 } 721 722 /// Only sink or hoist an instruction if it is not a trapping instruction, 723 /// or if the instruction is known not to trap when moved to the preheader. 724 /// or if it is a trapping instruction and is guaranteed to execute. 725 static bool isSafeToExecuteUnconditionally(const Instruction &Inst, 726 const DominatorTree *DT, 727 const TargetLibraryInfo *TLI, 728 const Loop *CurLoop, 729 const LoopSafetyInfo *SafetyInfo, 730 const Instruction *CtxI) { 731 if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT, TLI)) 732 return true; 733 734 return isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo); 735 } 736 737 namespace { 738 class LoopPromoter : public LoadAndStorePromoter { 739 Value *SomePtr; // Designated pointer to store to. 740 SmallPtrSetImpl<Value *> &PointerMustAliases; 741 SmallVectorImpl<BasicBlock *> &LoopExitBlocks; 742 SmallVectorImpl<Instruction *> &LoopInsertPts; 743 PredIteratorCache &PredCache; 744 AliasSetTracker &AST; 745 LoopInfo &LI; 746 DebugLoc DL; 747 int Alignment; 748 AAMDNodes AATags; 749 750 Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const { 751 if (Instruction *I = dyn_cast<Instruction>(V)) 752 if (Loop *L = LI.getLoopFor(I->getParent())) 753 if (!L->contains(BB)) { 754 // We need to create an LCSSA PHI node for the incoming value and 755 // store that. 756 PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB), 757 I->getName() + ".lcssa", &BB->front()); 758 for (BasicBlock *Pred : PredCache.get(BB)) 759 PN->addIncoming(I, Pred); 760 return PN; 761 } 762 return V; 763 } 764 765 public: 766 LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S, 767 SmallPtrSetImpl<Value *> &PMA, 768 SmallVectorImpl<BasicBlock *> &LEB, 769 SmallVectorImpl<Instruction *> &LIP, PredIteratorCache &PIC, 770 AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment, 771 const AAMDNodes &AATags) 772 : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA), 773 LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast), 774 LI(li), DL(std::move(dl)), Alignment(alignment), AATags(AATags) {} 775 776 bool isInstInList(Instruction *I, 777 const SmallVectorImpl<Instruction *> &) const override { 778 Value *Ptr; 779 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 780 Ptr = LI->getOperand(0); 781 else 782 Ptr = cast<StoreInst>(I)->getPointerOperand(); 783 return PointerMustAliases.count(Ptr); 784 } 785 786 void doExtraRewritesBeforeFinalDeletion() const override { 787 // Insert stores after in the loop exit blocks. Each exit block gets a 788 // store of the live-out values that feed them. Since we've already told 789 // the SSA updater about the defs in the loop and the preheader 790 // definition, it is all set and we can start using it. 791 for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) { 792 BasicBlock *ExitBlock = LoopExitBlocks[i]; 793 Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock); 794 LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock); 795 Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock); 796 Instruction *InsertPos = LoopInsertPts[i]; 797 StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos); 798 NewSI->setAlignment(Alignment); 799 NewSI->setDebugLoc(DL); 800 if (AATags) 801 NewSI->setAAMetadata(AATags); 802 } 803 } 804 805 void replaceLoadWithValue(LoadInst *LI, Value *V) const override { 806 // Update alias analysis. 807 AST.copyValue(LI, V); 808 } 809 void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); } 810 }; 811 } // end anon namespace 812 813 /// Try to promote memory values to scalars by sinking stores out of the 814 /// loop and moving loads to before the loop. We do this by looping over 815 /// the stores in the loop, looking for stores to Must pointers which are 816 /// loop invariant. 817 /// 818 bool llvm::promoteLoopAccessesToScalars( 819 AliasSet &AS, SmallVectorImpl<BasicBlock *> &ExitBlocks, 820 SmallVectorImpl<Instruction *> &InsertPts, PredIteratorCache &PIC, 821 LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI, 822 Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo) { 823 // Verify inputs. 824 assert(LI != nullptr && DT != nullptr && CurLoop != nullptr && 825 CurAST != nullptr && SafetyInfo != nullptr && 826 "Unexpected Input to promoteLoopAccessesToScalars"); 827 828 // We can promote this alias set if it has a store, if it is a "Must" alias 829 // set, if the pointer is loop invariant, and if we are not eliminating any 830 // volatile loads or stores. 831 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() || 832 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->getValue())) 833 return false; 834 835 assert(!AS.empty() && 836 "Must alias set should have at least one pointer element in it!"); 837 838 Value *SomePtr = AS.begin()->getValue(); 839 BasicBlock *Preheader = CurLoop->getLoopPreheader(); 840 841 // It isn't safe to promote a load/store from the loop if the load/store is 842 // conditional. For example, turning: 843 // 844 // for () { if (c) *P += 1; } 845 // 846 // into: 847 // 848 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp; 849 // 850 // is not safe, because *P may only be valid to access if 'c' is true. 851 // 852 // The safety property divides into two parts: 853 // 1) The memory may not be dereferenceable on entry to the loop. In this 854 // case, we can't insert the required load in the preheader. 855 // 2) The memory model does not allow us to insert a store along any dynamic 856 // path which did not originally have one. 857 // 858 // It is safe to promote P if all uses are direct load/stores and if at 859 // least one is guaranteed to be executed. 860 bool GuaranteedToExecute = false; 861 862 // It is also safe to promote P if we can prove that speculating a load into 863 // the preheader is safe (i.e. proving dereferenceability on all 864 // paths through the loop), and that the memory can be proven thread local 865 // (so that the memory model requirement doesn't apply.) We first establish 866 // the former, and then run a capture analysis below to establish the later. 867 // We can use any access within the alias set to prove dereferenceability 868 // since they're all must alias. 869 bool CanSpeculateLoad = false; 870 871 SmallVector<Instruction *, 64> LoopUses; 872 SmallPtrSet<Value *, 4> PointerMustAliases; 873 874 // We start with an alignment of one and try to find instructions that allow 875 // us to prove better alignment. 876 unsigned Alignment = 1; 877 AAMDNodes AATags; 878 bool HasDedicatedExits = CurLoop->hasDedicatedExits(); 879 880 // Don't sink stores from loops without dedicated block exits. Exits 881 // containing indirect branches are not transformed by loop simplify, 882 // make sure we catch that. An additional load may be generated in the 883 // preheader for SSA updater, so also avoid sinking when no preheader 884 // is available. 885 if (!HasDedicatedExits || !Preheader) 886 return false; 887 888 const DataLayout &MDL = Preheader->getModule()->getDataLayout(); 889 890 if (SafetyInfo->MayThrow) { 891 // If a loop can throw, we have to insert a store along each unwind edge. 892 // That said, we can't actually make the unwind edge explicit. Therefore, 893 // we have to prove that the store is dead along the unwind edge. 894 // 895 // Currently, this code just special-cases alloca instructions. 896 if (!isa<AllocaInst>(GetUnderlyingObject(SomePtr, MDL))) 897 return false; 898 } 899 900 // Check that all of the pointers in the alias set have the same type. We 901 // cannot (yet) promote a memory location that is loaded and stored in 902 // different sizes. While we are at it, collect alignment and AA info. 903 bool Changed = false; 904 for (AliasSet::iterator ASI = AS.begin(), E = AS.end(); ASI != E; ++ASI) { 905 Value *ASIV = ASI->getValue(); 906 PointerMustAliases.insert(ASIV); 907 908 // Check that all of the pointers in the alias set have the same type. We 909 // cannot (yet) promote a memory location that is loaded and stored in 910 // different sizes. 911 if (SomePtr->getType() != ASIV->getType()) 912 return Changed; 913 914 for (User *U : ASIV->users()) { 915 // Ignore instructions that are outside the loop. 916 Instruction *UI = dyn_cast<Instruction>(U); 917 if (!UI || !CurLoop->contains(UI)) 918 continue; 919 920 // If there is an non-load/store instruction in the loop, we can't promote 921 // it. 922 if (const LoadInst *Load = dyn_cast<LoadInst>(UI)) { 923 assert(!Load->isVolatile() && "AST broken"); 924 if (!Load->isSimple()) 925 return Changed; 926 927 if (!GuaranteedToExecute && !CanSpeculateLoad) 928 CanSpeculateLoad = isSafeToExecuteUnconditionally( 929 *Load, DT, TLI, CurLoop, SafetyInfo, Preheader->getTerminator()); 930 } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) { 931 // Stores *of* the pointer are not interesting, only stores *to* the 932 // pointer. 933 if (UI->getOperand(1) != ASIV) 934 continue; 935 assert(!Store->isVolatile() && "AST broken"); 936 if (!Store->isSimple()) 937 return Changed; 938 939 // Note that we only check GuaranteedToExecute inside the store case 940 // so that we do not introduce stores where they did not exist before 941 // (which would break the LLVM concurrency model). 942 943 // If the alignment of this instruction allows us to specify a more 944 // restrictive (and performant) alignment and if we are sure this 945 // instruction will be executed, update the alignment. 946 // Larger is better, with the exception of 0 being the best alignment. 947 unsigned InstAlignment = Store->getAlignment(); 948 if ((InstAlignment > Alignment || InstAlignment == 0) && Alignment != 0) 949 if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) { 950 GuaranteedToExecute = true; 951 Alignment = InstAlignment; 952 } 953 954 if (!GuaranteedToExecute) 955 GuaranteedToExecute = 956 isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo); 957 958 if (!GuaranteedToExecute && !CanSpeculateLoad) { 959 CanSpeculateLoad = isDereferenceableAndAlignedPointer( 960 Store->getPointerOperand(), Store->getAlignment(), MDL, 961 Preheader->getTerminator(), DT, TLI); 962 } 963 } else 964 return Changed; // Not a load or store. 965 966 // Merge the AA tags. 967 if (LoopUses.empty()) { 968 // On the first load/store, just take its AA tags. 969 UI->getAAMetadata(AATags); 970 } else if (AATags) { 971 UI->getAAMetadata(AATags, /* Merge = */ true); 972 } 973 974 LoopUses.push_back(UI); 975 } 976 } 977 978 // Check legality per comment above. Otherwise, we can't promote. 979 bool PromotionIsLegal = GuaranteedToExecute; 980 if (!PromotionIsLegal && CanSpeculateLoad) { 981 // If this is a thread local location, then we can insert stores along 982 // paths which originally didn't have them without violating the memory 983 // model. 984 Value *Object = GetUnderlyingObject(SomePtr, MDL); 985 PromotionIsLegal = 986 isAllocLikeFn(Object, TLI) && !PointerMayBeCaptured(Object, true, true); 987 } 988 if (!PromotionIsLegal) 989 return Changed; 990 991 // Figure out the loop exits and their insertion points, if this is the 992 // first promotion. 993 if (ExitBlocks.empty()) { 994 CurLoop->getUniqueExitBlocks(ExitBlocks); 995 InsertPts.clear(); 996 InsertPts.reserve(ExitBlocks.size()); 997 for (BasicBlock *ExitBlock : ExitBlocks) 998 InsertPts.push_back(&*ExitBlock->getFirstInsertionPt()); 999 } 1000 1001 // Can't insert into a catchswitch. 1002 for (BasicBlock *ExitBlock : ExitBlocks) 1003 if (isa<CatchSwitchInst>(ExitBlock->getTerminator())) 1004 return Changed; 1005 1006 // Otherwise, this is safe to promote, lets do it! 1007 DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr 1008 << '\n'); 1009 Changed = true; 1010 ++NumPromoted; 1011 1012 // Grab a debug location for the inserted loads/stores; given that the 1013 // inserted loads/stores have little relation to the original loads/stores, 1014 // this code just arbitrarily picks a location from one, since any debug 1015 // location is better than none. 1016 DebugLoc DL = LoopUses[0]->getDebugLoc(); 1017 1018 // We use the SSAUpdater interface to insert phi nodes as required. 1019 SmallVector<PHINode *, 16> NewPHIs; 1020 SSAUpdater SSA(&NewPHIs); 1021 LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks, 1022 InsertPts, PIC, *CurAST, *LI, DL, Alignment, AATags); 1023 1024 // Set up the preheader to have a definition of the value. It is the live-out 1025 // value from the preheader that uses in the loop will use. 1026 LoadInst *PreheaderLoad = new LoadInst( 1027 SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator()); 1028 PreheaderLoad->setAlignment(Alignment); 1029 PreheaderLoad->setDebugLoc(DL); 1030 if (AATags) 1031 PreheaderLoad->setAAMetadata(AATags); 1032 SSA.AddAvailableValue(Preheader, PreheaderLoad); 1033 1034 // Rewrite all the loads in the loop and remember all the definitions from 1035 // stores in the loop. 1036 Promoter.run(LoopUses); 1037 1038 // If the SSAUpdater didn't use the load in the preheader, just zap it now. 1039 if (PreheaderLoad->use_empty()) 1040 PreheaderLoad->eraseFromParent(); 1041 1042 return Changed; 1043 } 1044 1045 /// Returns an owning pointer to an alias set which incorporates aliasing info 1046 /// from L and all subloops of L. 1047 AliasSetTracker *LICM::collectAliasInfoForLoop(Loop *L) { 1048 AliasSetTracker *CurAST = nullptr; 1049 SmallVector<Loop *, 4> RecomputeLoops; 1050 for (Loop *InnerL : L->getSubLoops()) { 1051 auto MapI = LoopToAliasSetMap.find(InnerL); 1052 // If the AST for this inner loop is missing it may have been merged into 1053 // some other loop's AST and then that loop unrolled, and so we need to 1054 // recompute it. 1055 if (MapI == LoopToAliasSetMap.end()) { 1056 RecomputeLoops.push_back(InnerL); 1057 continue; 1058 } 1059 AliasSetTracker *InnerAST = MapI->second; 1060 1061 if (CurAST != nullptr) { 1062 // What if InnerLoop was modified by other passes ? 1063 CurAST->add(*InnerAST); 1064 1065 // Once we've incorporated the inner loop's AST into ours, we don't need 1066 // the subloop's anymore. 1067 delete InnerAST; 1068 } else { 1069 CurAST = InnerAST; 1070 } 1071 LoopToAliasSetMap.erase(MapI); 1072 } 1073 if (CurAST == nullptr) 1074 CurAST = new AliasSetTracker(*AA); 1075 1076 auto mergeLoop = [&](Loop *L) { 1077 // Loop over the body of this loop, looking for calls, invokes, and stores. 1078 // Because subloops have already been incorporated into AST, we skip blocks 1079 // in subloops. 1080 for (BasicBlock *BB : L->blocks()) 1081 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops. 1082 CurAST->add(*BB); // Incorporate the specified basic block 1083 }; 1084 1085 // Add everything from the sub loops that are no longer directly available. 1086 for (Loop *InnerL : RecomputeLoops) 1087 mergeLoop(InnerL); 1088 1089 // And merge in this loop. 1090 mergeLoop(L); 1091 1092 return CurAST; 1093 } 1094 1095 /// Simple analysis hook. Clone alias set info. 1096 /// 1097 void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) { 1098 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1099 if (!AST) 1100 return; 1101 1102 AST->copyValue(From, To); 1103 } 1104 1105 /// Simple Analysis hook. Delete value V from alias set 1106 /// 1107 void LICM::deleteAnalysisValue(Value *V, Loop *L) { 1108 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1109 if (!AST) 1110 return; 1111 1112 AST->deleteValue(V); 1113 } 1114 1115 /// Simple Analysis hook. Delete value L from alias set map. 1116 /// 1117 void LICM::deleteAnalysisLoop(Loop *L) { 1118 AliasSetTracker *AST = LoopToAliasSetMap.lookup(L); 1119 if (!AST) 1120 return; 1121 1122 delete AST; 1123 LoopToAliasSetMap.erase(L); 1124 } 1125 1126 /// Return true if the body of this loop may store into the memory 1127 /// location pointed to by V. 1128 /// 1129 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, 1130 const AAMDNodes &AAInfo, 1131 AliasSetTracker *CurAST) { 1132 // Check to see if any of the basic blocks in CurLoop invalidate *V. 1133 return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod(); 1134 } 1135 1136 /// Little predicate that returns true if the specified basic block is in 1137 /// a subloop of the current one, not the current one itself. 1138 /// 1139 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) { 1140 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop"); 1141 return LI->getLoopFor(BB) != CurLoop; 1142 } 1143