LLVM  7.0.0svn
LICM.cpp
Go to the documentation of this file.
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 
34 #include "llvm/ADT/Statistic.h"
41 #include "llvm/Analysis/Loads.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/LoopPass.h"
52 #include "llvm/IR/CFG.h"
53 #include "llvm/IR/Constants.h"
54 #include "llvm/IR/DataLayout.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Instructions.h"
58 #include "llvm/IR/IntrinsicInst.h"
59 #include "llvm/IR/LLVMContext.h"
60 #include "llvm/IR/Metadata.h"
63 #include "llvm/Support/Debug.h"
65 #include "llvm/Transforms/Scalar.h"
70 #include <algorithm>
71 #include <utility>
72 using namespace llvm;
73 
74 #define DEBUG_TYPE "licm"
75 
76 STATISTIC(NumSunk, "Number of instructions sunk out of loop");
77 STATISTIC(NumHoisted, "Number of instructions hoisted out of loop");
78 STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
79 STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
80 STATISTIC(NumPromoted, "Number of memory locations promoted to registers");
81 
82 /// Memory promotion is enabled by default.
83 static cl::opt<bool>
84  DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false),
85  cl::desc("Disable memory promotion in LICM pass"));
86 
88  "licm-max-num-uses-traversed", cl::Hidden, cl::init(8),
89  cl::desc("Max num uses visited for identifying load "
90  "invariance in loop using invariant start (default = 8)"));
91 
92 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI);
93 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
94  const LoopSafetyInfo *SafetyInfo,
95  TargetTransformInfo *TTI, bool &FreeInLoop);
96 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
97  const LoopSafetyInfo *SafetyInfo,
99 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
100  const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
101  OptimizationRemarkEmitter *ORE, bool FreeInLoop);
103  const DominatorTree *DT,
104  const Loop *CurLoop,
105  const LoopSafetyInfo *SafetyInfo,
107  const Instruction *CtxI = nullptr);
108 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
109  const AAMDNodes &AAInfo,
110  AliasSetTracker *CurAST);
111 static Instruction *
113  const LoopInfo *LI,
114  const LoopSafetyInfo *SafetyInfo);
115 
116 namespace {
117 struct LoopInvariantCodeMotion {
118  bool runOnLoop(Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
120  ScalarEvolution *SE, MemorySSA *MSSA,
121  OptimizationRemarkEmitter *ORE, bool DeleteAST);
122 
123  DenseMap<Loop *, AliasSetTracker *> &getLoopToAliasSetMap() {
124  return LoopToAliasSetMap;
125  }
126 
127 private:
128  DenseMap<Loop *, AliasSetTracker *> LoopToAliasSetMap;
129 
130  AliasSetTracker *collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
131  AliasAnalysis *AA);
132 };
133 
134 struct LegacyLICMPass : public LoopPass {
135  static char ID; // Pass identification, replacement for typeid
136  LegacyLICMPass() : LoopPass(ID) {
138  }
139 
140  bool runOnLoop(Loop *L, LPPassManager &LPM) override {
141  if (skipLoop(L)) {
142  // If we have run LICM on a previous loop but now we are skipping
143  // (because we've hit the opt-bisect limit), we need to clear the
144  // loop alias information.
145  for (auto &LTAS : LICM.getLoopToAliasSetMap())
146  delete LTAS.second;
147  LICM.getLoopToAliasSetMap().clear();
148  return false;
149  }
150 
151  auto *SE = getAnalysisIfAvailable<ScalarEvolutionWrapperPass>();
153  ? (&getAnalysis<MemorySSAWrapperPass>().getMSSA())
154  : nullptr;
155  // For the old PM, we can't use OptimizationRemarkEmitter as an analysis
156  // pass. Function analyses need to be preserved across loop transformations
157  // but ORE cannot be preserved (see comment before the pass definition).
159  return LICM.runOnLoop(L,
160  &getAnalysis<AAResultsWrapperPass>().getAAResults(),
161  &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(),
162  &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
163  &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
164  &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
165  *L->getHeader()->getParent()),
166  SE ? &SE->getSE() : nullptr, MSSA, &ORE, false);
167  }
168 
169  /// This transformation requires natural loop information & requires that
170  /// loop preheaders be inserted into the CFG...
171  ///
172  void getAnalysisUsage(AnalysisUsage &AU) const override {
180  }
181 
183 
184  bool doFinalization() override {
185  assert(LICM.getLoopToAliasSetMap().empty() &&
186  "Didn't free loop alias sets");
187  return false;
188  }
189 
190 private:
191  LoopInvariantCodeMotion LICM;
192 
193  /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
194  void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
195  Loop *L) override;
196 
197  /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
198  /// set.
199  void deleteAnalysisValue(Value *V, Loop *L) override;
200 
201  /// Simple Analysis hook. Delete loop L from alias set map.
202  void deleteAnalysisLoop(Loop *L) override;
203 };
204 } // namespace
205 
208  const auto &FAM =
209  AM.getResult<FunctionAnalysisManagerLoopProxy>(L, AR).getManager();
210  Function *F = L.getHeader()->getParent();
211 
212  auto *ORE = FAM.getCachedResult<OptimizationRemarkEmitterAnalysis>(*F);
213  // FIXME: This should probably be optional rather than required.
214  if (!ORE)
215  report_fatal_error("LICM: OptimizationRemarkEmitterAnalysis not "
216  "cached at a higher level");
217 
218  LoopInvariantCodeMotion LICM;
219  if (!LICM.runOnLoop(&L, &AR.AA, &AR.LI, &AR.DT, &AR.TLI, &AR.TTI, &AR.SE,
220  AR.MSSA, ORE, true))
221  return PreservedAnalyses::all();
222 
223  auto PA = getLoopPassPreservedAnalyses();
224 
225  PA.preserve<DominatorTreeAnalysis>();
226  PA.preserve<LoopAnalysis>();
227 
228  return PA;
229 }
230 
231 char LegacyLICMPass::ID = 0;
232 INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion",
233  false, false)
238 INITIALIZE_PASS_END(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false,
239  false)
240 
241 Pass *llvm::createLICMPass() { return new LegacyLICMPass(); }
242 
243 /// Hoist expressions out of the specified loop. Note, alias info for inner
244 /// loop is not preserved so it is not a good idea to run LICM multiple
245 /// times on one loop.
246 /// We should delete AST for inner loops in the new pass manager to avoid
247 /// memory leak.
248 ///
249 bool LoopInvariantCodeMotion::runOnLoop(
250  Loop *L, AliasAnalysis *AA, LoopInfo *LI, DominatorTree *DT,
252  MemorySSA *MSSA, OptimizationRemarkEmitter *ORE, bool DeleteAST) {
253  bool Changed = false;
254 
255  assert(L->isLCSSAForm(*DT) && "Loop is not in LCSSA form.");
256 
257  AliasSetTracker *CurAST = collectAliasInfoForLoop(L, LI, AA);
258 
259  // Get the preheader block to move instructions into...
260  BasicBlock *Preheader = L->getLoopPreheader();
261 
262  // Compute loop safety information.
263  LoopSafetyInfo SafetyInfo;
264  computeLoopSafetyInfo(&SafetyInfo, L);
265 
266  // We want to visit all of the instructions in this loop... that are not parts
267  // of our subloops (they have already had their invariants hoisted out of
268  // their loop, into this loop, so there is no need to process the BODIES of
269  // the subloops).
270  //
271  // Traverse the body of the loop in depth first order on the dominator tree so
272  // that we are guaranteed to see definitions before we see uses. This allows
273  // us to sink instructions in one pass, without iteration. After sinking
274  // instructions, we perform another pass to hoist them out of the loop.
275  //
276  if (L->hasDedicatedExits())
277  Changed |= sinkRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, TTI, L,
278  CurAST, &SafetyInfo, ORE);
279  if (Preheader)
280  Changed |= hoistRegion(DT->getNode(L->getHeader()), AA, LI, DT, TLI, L,
281  CurAST, &SafetyInfo, ORE);
282 
283  // Now that all loop invariants have been removed from the loop, promote any
284  // memory references to scalars that we can.
285  // Don't sink stores from loops without dedicated block exits. Exits
286  // containing indirect branches are not transformed by loop simplify,
287  // make sure we catch that. An additional load may be generated in the
288  // preheader for SSA updater, so also avoid sinking when no preheader
289  // is available.
290  if (!DisablePromotion && Preheader && L->hasDedicatedExits()) {
291  // Figure out the loop exits and their insertion points
292  SmallVector<BasicBlock *, 8> ExitBlocks;
293  L->getUniqueExitBlocks(ExitBlocks);
294 
295  // We can't insert into a catchswitch.
296  bool HasCatchSwitch = llvm::any_of(ExitBlocks, [](BasicBlock *Exit) {
297  return isa<CatchSwitchInst>(Exit->getTerminator());
298  });
299 
300  if (!HasCatchSwitch) {
302  InsertPts.reserve(ExitBlocks.size());
303  for (BasicBlock *ExitBlock : ExitBlocks)
304  InsertPts.push_back(&*ExitBlock->getFirstInsertionPt());
305 
306  PredIteratorCache PIC;
307 
308  bool Promoted = false;
309 
310  // Loop over all of the alias sets in the tracker object.
311  for (AliasSet &AS : *CurAST) {
312  // We can promote this alias set if it has a store, if it is a "Must"
313  // alias set, if the pointer is loop invariant, and if we are not
314  // eliminating any volatile loads or stores.
315  if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
316  AS.isVolatile() || !L->isLoopInvariant(AS.begin()->getValue()))
317  continue;
318 
319  assert(
320  !AS.empty() &&
321  "Must alias set should have at least one pointer element in it!");
322 
323  SmallSetVector<Value *, 8> PointerMustAliases;
324  for (const auto &ASI : AS)
325  PointerMustAliases.insert(ASI.getValue());
326 
327  Promoted |= promoteLoopAccessesToScalars(PointerMustAliases, ExitBlocks,
328  InsertPts, PIC, LI, DT, TLI, L,
329  CurAST, &SafetyInfo, ORE);
330  }
331 
332  // Once we have promoted values across the loop body we have to
333  // recursively reform LCSSA as any nested loop may now have values defined
334  // within the loop used in the outer loop.
335  // FIXME: This is really heavy handed. It would be a bit better to use an
336  // SSAUpdater strategy during promotion that was LCSSA aware and reformed
337  // it as it went.
338  if (Promoted)
339  formLCSSARecursively(*L, *DT, LI, SE);
340 
341  Changed |= Promoted;
342  }
343  }
344 
345  // Check that neither this loop nor its parent have had LCSSA broken. LICM is
346  // specifically moving instructions across the loop boundary and so it is
347  // especially in need of sanity checking here.
348  assert(L->isLCSSAForm(*DT) && "Loop not left in LCSSA form after LICM!");
349  assert((!L->getParentLoop() || L->getParentLoop()->isLCSSAForm(*DT)) &&
350  "Parent loop not left in LCSSA form after LICM!");
351 
352  // If this loop is nested inside of another one, save the alias information
353  // for when we process the outer loop.
354  if (L->getParentLoop() && !DeleteAST)
355  LoopToAliasSetMap[L] = CurAST;
356  else
357  delete CurAST;
358 
359  if (Changed && SE)
360  SE->forgetLoopDispositions(L);
361  return Changed;
362 }
363 
364 /// Walk the specified region of the CFG (defined by all blocks dominated by
365 /// the specified block, and that are in the current loop) in reverse depth
366 /// first order w.r.t the DominatorTree. This allows us to visit uses before
367 /// definitions, allowing us to sink a loop body in one pass without iteration.
368 ///
371  TargetTransformInfo *TTI, Loop *CurLoop,
372  AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
374 
375  // Verify inputs.
376  assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
377  CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
378  "Unexpected input to sinkRegion");
379 
380  // We want to visit children before parents. We will enque all the parents
381  // before their children in the worklist and process the worklist in reverse
382  // order.
384 
385  bool Changed = false;
386  for (DomTreeNode *DTN : reverse(Worklist)) {
387  BasicBlock *BB = DTN->getBlock();
388  // Only need to process the contents of this block if it is not part of a
389  // subloop (which would already have been processed).
390  if (inSubLoop(BB, CurLoop, LI))
391  continue;
392 
393  for (BasicBlock::iterator II = BB->end(); II != BB->begin();) {
394  Instruction &I = *--II;
395 
396  // If the instruction is dead, we would try to sink it because it isn't
397  // used in the loop, instead, just delete it.
398  if (isInstructionTriviallyDead(&I, TLI)) {
399  LLVM_DEBUG(dbgs() << "LICM deleting dead inst: " << I << '\n');
400  salvageDebugInfo(I);
401  ++II;
402  CurAST->deleteValue(&I);
403  I.eraseFromParent();
404  Changed = true;
405  continue;
406  }
407 
408  // Check to see if we can sink this instruction to the exit blocks
409  // of the loop. We can do this if the all users of the instruction are
410  // outside of the loop. In this case, it doesn't even matter if the
411  // operands of the instruction are loop invariant.
412  //
413  bool FreeInLoop = false;
414  if (isNotUsedOrFreeInLoop(I, CurLoop, SafetyInfo, TTI, FreeInLoop) &&
415  canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE)) {
416  if (sink(I, LI, DT, CurLoop, SafetyInfo, ORE, FreeInLoop)) {
417  if (!FreeInLoop) {
418  ++II;
419  CurAST->deleteValue(&I);
420  I.eraseFromParent();
421  }
422  Changed = true;
423  }
424  }
425  }
426  }
427  return Changed;
428 }
429 
430 /// Walk the specified region of the CFG (defined by all blocks dominated by
431 /// the specified block, and that are in the current loop) in depth first
432 /// order w.r.t the DominatorTree. This allows us to visit definitions before
433 /// uses, allowing us to hoist a loop body in one pass without iteration.
434 ///
436  DominatorTree *DT, TargetLibraryInfo *TLI, Loop *CurLoop,
437  AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
439  // Verify inputs.
440  assert(N != nullptr && AA != nullptr && LI != nullptr && DT != nullptr &&
441  CurLoop != nullptr && CurAST != nullptr && SafetyInfo != nullptr &&
442  "Unexpected input to hoistRegion");
443 
444  // We want to visit parents before children. We will enque all the parents
445  // before their children in the worklist and process the worklist in order.
447 
448  bool Changed = false;
449  for (DomTreeNode *DTN : Worklist) {
450  BasicBlock *BB = DTN->getBlock();
451  // Only need to process the contents of this block if it is not part of a
452  // subloop (which would already have been processed).
453  if (inSubLoop(BB, CurLoop, LI))
454  continue;
455 
456  // Keep track of whether the prefix of instructions visited so far are such
457  // that the next instruction visited is guaranteed to execute if the loop
458  // is entered.
459  bool IsMustExecute = CurLoop->getHeader() == BB;
460 
461  for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E;) {
462  Instruction &I = *II++;
463  // Try constant folding this instruction. If all the operands are
464  // constants, it is technically hoistable, but it would be better to
465  // just fold it.
467  &I, I.getModule()->getDataLayout(), TLI)) {
468  LLVM_DEBUG(dbgs() << "LICM folding inst: " << I << " --> " << *C
469  << '\n');
470  CurAST->copyValue(&I, C);
472  if (isInstructionTriviallyDead(&I, TLI)) {
473  CurAST->deleteValue(&I);
474  I.eraseFromParent();
475  }
476  Changed = true;
477  continue;
478  }
479 
480  // Try hoisting the instruction out to the preheader. We can only do
481  // this if all of the operands of the instruction are loop invariant and
482  // if it is safe to hoist the instruction.
483  //
484  if (CurLoop->hasLoopInvariantOperands(&I) &&
485  canSinkOrHoistInst(I, AA, DT, CurLoop, CurAST, SafetyInfo, ORE) &&
486  (IsMustExecute ||
488  I, DT, CurLoop, SafetyInfo, ORE,
489  CurLoop->getLoopPreheader()->getTerminator()))) {
490  Changed |= hoist(I, DT, CurLoop, SafetyInfo, ORE);
491  continue;
492  }
493 
494  // Attempt to remove floating point division out of the loop by
495  // converting it to a reciprocal multiplication.
496  if (I.getOpcode() == Instruction::FDiv &&
497  CurLoop->isLoopInvariant(I.getOperand(1)) &&
498  I.hasAllowReciprocal()) {
499  auto Divisor = I.getOperand(1);
500  auto One = llvm::ConstantFP::get(Divisor->getType(), 1.0);
501  auto ReciprocalDivisor = BinaryOperator::CreateFDiv(One, Divisor);
502  ReciprocalDivisor->setFastMathFlags(I.getFastMathFlags());
503  ReciprocalDivisor->insertBefore(&I);
504 
505  auto Product =
506  BinaryOperator::CreateFMul(I.getOperand(0), ReciprocalDivisor);
507  Product->setFastMathFlags(I.getFastMathFlags());
508  Product->insertAfter(&I);
509  I.replaceAllUsesWith(Product);
510  I.eraseFromParent();
511 
512  hoist(*ReciprocalDivisor, DT, CurLoop, SafetyInfo, ORE);
513  Changed = true;
514  continue;
515  }
516 
517  if (IsMustExecute)
518  IsMustExecute = isGuaranteedToTransferExecutionToSuccessor(&I);
519  }
520  }
521 
522  return Changed;
523 }
524 
525 // Return true if LI is invariant within scope of the loop. LI is invariant if
526 // CurLoop is dominated by an invariant.start representing the same memory
527 // location and size as the memory location LI loads from, and also the
528 // invariant.start has no uses.
530  Loop *CurLoop) {
531  Value *Addr = LI->getOperand(0);
532  const DataLayout &DL = LI->getModule()->getDataLayout();
533  const uint32_t LocSizeInBits = DL.getTypeSizeInBits(
534  cast<PointerType>(Addr->getType())->getElementType());
535 
536  // if the type is i8 addrspace(x)*, we know this is the type of
537  // llvm.invariant.start operand
538  auto *PtrInt8Ty = PointerType::get(Type::getInt8Ty(LI->getContext()),
539  LI->getPointerAddressSpace());
540  unsigned BitcastsVisited = 0;
541  // Look through bitcasts until we reach the i8* type (this is invariant.start
542  // operand type).
543  while (Addr->getType() != PtrInt8Ty) {
544  auto *BC = dyn_cast<BitCastInst>(Addr);
545  // Avoid traversing high number of bitcast uses.
546  if (++BitcastsVisited > MaxNumUsesTraversed || !BC)
547  return false;
548  Addr = BC->getOperand(0);
549  }
550 
551  unsigned UsesVisited = 0;
552  // Traverse all uses of the load operand value, to see if invariant.start is
553  // one of the uses, and whether it dominates the load instruction.
554  for (auto *U : Addr->users()) {
555  // Avoid traversing for Load operand with high number of users.
556  if (++UsesVisited > MaxNumUsesTraversed)
557  return false;
559  // If there are escaping uses of invariant.start instruction, the load maybe
560  // non-invariant.
561  if (!II || II->getIntrinsicID() != Intrinsic::invariant_start ||
562  !II->use_empty())
563  continue;
564  unsigned InvariantSizeInBits =
565  cast<ConstantInt>(II->getArgOperand(0))->getSExtValue() * 8;
566  // Confirm the invariant.start location size contains the load operand size
567  // in bits. Also, the invariant.start should dominate the load, and we
568  // should not hoist the load out of a loop that contains this dominating
569  // invariant.start.
570  if (LocSizeInBits <= InvariantSizeInBits &&
571  DT->properlyDominates(II->getParent(), CurLoop->getHeader()))
572  return true;
573  }
574 
575  return false;
576 }
577 
579  Loop *CurLoop, AliasSetTracker *CurAST,
580  LoopSafetyInfo *SafetyInfo,
582  // SafetyInfo is nullptr if we are checking for sinking from preheader to
583  // loop body.
584  const bool SinkingToLoopBody = !SafetyInfo;
585  // Loads have extra constraints we have to verify before we can hoist them.
586  if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
587  if (!LI->isUnordered())
588  return false; // Don't sink/hoist volatile or ordered atomic loads!
589 
590  // Loads from constant memory are always safe to move, even if they end up
591  // in the same alias set as something that ends up being modified.
592  if (AA->pointsToConstantMemory(LI->getOperand(0)))
593  return true;
594  if (LI->getMetadata(LLVMContext::MD_invariant_load))
595  return true;
596 
597  if (LI->isAtomic() && SinkingToLoopBody)
598  return false; // Don't sink unordered atomic loads to loop body.
599 
600  // This checks for an invariant.start dominating the load.
601  if (isLoadInvariantInLoop(LI, DT, CurLoop))
602  return true;
603 
604  // Don't hoist loads which have may-aliased stores in loop.
605  uint64_t Size = 0;
606  if (LI->getType()->isSized())
607  Size = I.getModule()->getDataLayout().getTypeStoreSize(LI->getType());
608 
609  AAMDNodes AAInfo;
610  LI->getAAMetadata(AAInfo);
611 
612  bool Invalidated =
613  pointerInvalidatedByLoop(LI->getOperand(0), Size, AAInfo, CurAST);
614  // Check loop-invariant address because this may also be a sinkable load
615  // whose address is not necessarily loop-invariant.
616  if (ORE && Invalidated && CurLoop->isLoopInvariant(LI->getPointerOperand()))
617  ORE->emit([&]() {
619  DEBUG_TYPE, "LoadWithLoopInvariantAddressInvalidated", LI)
620  << "failed to move load with loop-invariant address "
621  "because the loop may invalidate its value";
622  });
623 
624  return !Invalidated;
625  } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
626  // Don't sink or hoist dbg info; it's legal, but not useful.
627  if (isa<DbgInfoIntrinsic>(I))
628  return false;
629 
630  // Don't sink calls which can throw.
631  if (CI->mayThrow())
632  return false;
633 
634  // Handle simple cases by querying alias analysis.
635  FunctionModRefBehavior Behavior = AA->getModRefBehavior(CI);
636  if (Behavior == FMRB_DoesNotAccessMemory)
637  return true;
638  if (AliasAnalysis::onlyReadsMemory(Behavior)) {
639  // A readonly argmemonly function only reads from memory pointed to by
640  // it's arguments with arbitrary offsets. If we can prove there are no
641  // writes to this memory in the loop, we can hoist or sink.
643  for (Value *Op : CI->arg_operands())
644  if (Op->getType()->isPointerTy() &&
646  AAMDNodes(), CurAST))
647  return false;
648  return true;
649  }
650  // If this call only reads from memory and there are no writes to memory
651  // in the loop, we can hoist or sink the call as appropriate.
652  bool FoundMod = false;
653  for (AliasSet &AS : *CurAST) {
654  if (!AS.isForwardingAliasSet() && AS.isMod()) {
655  FoundMod = true;
656  break;
657  }
658  }
659  if (!FoundMod)
660  return true;
661  }
662 
663  // FIXME: This should use mod/ref information to see if we can hoist or
664  // sink the call.
665 
666  return false;
667  }
668 
669  // Only these instructions are hoistable/sinkable.
670  if (!isa<BinaryOperator>(I) && !isa<CastInst>(I) && !isa<SelectInst>(I) &&
671  !isa<GetElementPtrInst>(I) && !isa<CmpInst>(I) &&
672  !isa<InsertElementInst>(I) && !isa<ExtractElementInst>(I) &&
673  !isa<ShuffleVectorInst>(I) && !isa<ExtractValueInst>(I) &&
674  !isa<InsertValueInst>(I))
675  return false;
676 
677  // If we are checking for sinking from preheader to loop body it will be
678  // always safe as there is no speculative execution.
679  if (SinkingToLoopBody)
680  return true;
681 
682  // TODO: Plumb the context instruction through to make hoisting and sinking
683  // more powerful. Hoisting of loads already works due to the special casing
684  // above.
685  return isSafeToExecuteUnconditionally(I, DT, CurLoop, SafetyInfo, nullptr);
686 }
687 
688 /// Returns true if a PHINode is a trivially replaceable with an
689 /// Instruction.
690 /// This is true when all incoming values are that instruction.
691 /// This pattern occurs most often with LCSSA PHI nodes.
692 ///
693 static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I) {
694  for (const Value *IncValue : PN.incoming_values())
695  if (IncValue != &I)
696  return false;
697 
698  return true;
699 }
700 
701 /// Return true if the instruction is free in the loop.
702 static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop,
703  const TargetTransformInfo *TTI) {
704 
705  if (const GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
707  return false;
708  // For a GEP, we cannot simply use getUserCost because currently it
709  // optimistically assume that a GEP will fold into addressing mode
710  // regardless of its users.
711  const BasicBlock *BB = GEP->getParent();
712  for (const User *U : GEP->users()) {
713  const Instruction *UI = cast<Instruction>(U);
714  if (CurLoop->contains(UI) &&
715  (BB != UI->getParent() ||
716  (!isa<StoreInst>(UI) && !isa<LoadInst>(UI))))
717  return false;
718  }
719  return true;
720  } else
721  return TTI->getUserCost(&I) == TargetTransformInfo::TCC_Free;
722 }
723 
724 /// Return true if the only users of this instruction are outside of
725 /// the loop. If this is true, we can sink the instruction to the exit
726 /// blocks of the loop.
727 ///
728 /// We also return true if the instruction could be folded away in lowering.
729 /// (e.g., a GEP can be folded into a load as an addressing mode in the loop).
730 static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop,
731  const LoopSafetyInfo *SafetyInfo,
732  TargetTransformInfo *TTI, bool &FreeInLoop) {
733  const auto &BlockColors = SafetyInfo->BlockColors;
734  bool IsFree = isFreeInLoop(I, CurLoop, TTI);
735  for (const User *U : I.users()) {
736  const Instruction *UI = cast<Instruction>(U);
737  if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
738  const BasicBlock *BB = PN->getParent();
739  // We cannot sink uses in catchswitches.
740  if (isa<CatchSwitchInst>(BB->getTerminator()))
741  return false;
742 
743  // We need to sink a callsite to a unique funclet. Avoid sinking if the
744  // phi use is too muddled.
745  if (isa<CallInst>(I))
746  if (!BlockColors.empty() &&
747  BlockColors.find(const_cast<BasicBlock *>(BB))->second.size() != 1)
748  return false;
749  }
750 
751  if (CurLoop->contains(UI)) {
752  if (IsFree) {
753  FreeInLoop = true;
754  continue;
755  }
756  return false;
757  }
758  }
759  return true;
760 }
761 
762 static Instruction *
764  const LoopInfo *LI,
765  const LoopSafetyInfo *SafetyInfo) {
766  Instruction *New;
767  if (auto *CI = dyn_cast<CallInst>(&I)) {
768  const auto &BlockColors = SafetyInfo->BlockColors;
769 
770  // Sinking call-sites need to be handled differently from other
771  // instructions. The cloned call-site needs a funclet bundle operand
772  // appropriate for it's location in the CFG.
774  for (unsigned BundleIdx = 0, BundleEnd = CI->getNumOperandBundles();
775  BundleIdx != BundleEnd; ++BundleIdx) {
776  OperandBundleUse Bundle = CI->getOperandBundleAt(BundleIdx);
777  if (Bundle.getTagID() == LLVMContext::OB_funclet)
778  continue;
779 
780  OpBundles.emplace_back(Bundle);
781  }
782 
783  if (!BlockColors.empty()) {
784  const ColorVector &CV = BlockColors.find(&ExitBlock)->second;
785  assert(CV.size() == 1 && "non-unique color for exit block!");
786  BasicBlock *BBColor = CV.front();
787  Instruction *EHPad = BBColor->getFirstNonPHI();
788  if (EHPad->isEHPad())
789  OpBundles.emplace_back("funclet", EHPad);
790  }
791 
792  New = CallInst::Create(CI, OpBundles);
793  } else {
794  New = I.clone();
795  }
796 
797  ExitBlock.getInstList().insert(ExitBlock.getFirstInsertionPt(), New);
798  if (!I.getName().empty())
799  New->setName(I.getName() + ".le");
800 
801  // Build LCSSA PHI nodes for any in-loop operands. Note that this is
802  // particularly cheap because we can rip off the PHI node that we're
803  // replacing for the number and blocks of the predecessors.
804  // OPT: If this shows up in a profile, we can instead finish sinking all
805  // invariant instructions, and then walk their operands to re-establish
806  // LCSSA. That will eliminate creating PHI nodes just to nuke them when
807  // sinking bottom-up.
808  for (User::op_iterator OI = New->op_begin(), OE = New->op_end(); OI != OE;
809  ++OI)
810  if (Instruction *OInst = dyn_cast<Instruction>(*OI))
811  if (Loop *OLoop = LI->getLoopFor(OInst->getParent()))
812  if (!OLoop->contains(&PN)) {
813  PHINode *OpPN =
814  PHINode::Create(OInst->getType(), PN.getNumIncomingValues(),
815  OInst->getName() + ".lcssa", &ExitBlock.front());
816  for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
817  OpPN->addIncoming(OInst, PN.getIncomingBlock(i));
818  *OI = OpPN;
819  }
820  return New;
821 }
822 
824  PHINode *TPN, Instruction *I, LoopInfo *LI,
826  const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop) {
827  assert(isTriviallyReplaceablePHI(*TPN, *I) &&
828  "Expect only trivially replaceable PHI");
829  BasicBlock *ExitBlock = TPN->getParent();
830  Instruction *New;
831  auto It = SunkCopies.find(ExitBlock);
832  if (It != SunkCopies.end())
833  New = It->second;
834  else
835  New = SunkCopies[ExitBlock] =
836  CloneInstructionInExitBlock(*I, *ExitBlock, *TPN, LI, SafetyInfo);
837  return New;
838 }
839 
840 static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo) {
841  BasicBlock *BB = PN->getParent();
842  if (!BB->canSplitPredecessors())
843  return false;
844  // It's not impossible to split EHPad blocks, but if BlockColors already exist
845  // it require updating BlockColors for all offspring blocks accordingly. By
846  // skipping such corner case, we can make updating BlockColors after splitting
847  // predecessor fairly simple.
848  if (!SafetyInfo->BlockColors.empty() && BB->getFirstNonPHI()->isEHPad())
849  return false;
850  for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
851  BasicBlock *BBPred = *PI;
852  if (isa<IndirectBrInst>(BBPred->getTerminator()))
853  return false;
854  }
855  return true;
856 }
857 
859  LoopInfo *LI, const Loop *CurLoop,
860  LoopSafetyInfo *SafetyInfo) {
861 #ifndef NDEBUG
863  CurLoop->getUniqueExitBlocks(ExitBlocks);
864  SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
865  ExitBlocks.end());
866 #endif
867  BasicBlock *ExitBB = PN->getParent();
868  assert(ExitBlockSet.count(ExitBB) && "Expect the PHI is in an exit block.");
869 
870  // Split predecessors of the loop exit to make instructions in the loop are
871  // exposed to exit blocks through trivially replaceable PHIs while keeping the
872  // loop in the canonical form where each predecessor of each exit block should
873  // be contained within the loop. For example, this will convert the loop below
874  // from
875  //
876  // LB1:
877  // %v1 =
878  // br %LE, %LB2
879  // LB2:
880  // %v2 =
881  // br %LE, %LB1
882  // LE:
883  // %p = phi [%v1, %LB1], [%v2, %LB2] <-- non-trivially replaceable
884  //
885  // to
886  //
887  // LB1:
888  // %v1 =
889  // br %LE.split, %LB2
890  // LB2:
891  // %v2 =
892  // br %LE.split2, %LB1
893  // LE.split:
894  // %p1 = phi [%v1, %LB1] <-- trivially replaceable
895  // br %LE
896  // LE.split2:
897  // %p2 = phi [%v2, %LB2] <-- trivially replaceable
898  // br %LE
899  // LE:
900  // %p = phi [%p1, %LE.split], [%p2, %LE.split2]
901  //
902  auto &BlockColors = SafetyInfo->BlockColors;
903  SmallSetVector<BasicBlock *, 8> PredBBs(pred_begin(ExitBB), pred_end(ExitBB));
904  while (!PredBBs.empty()) {
905  BasicBlock *PredBB = *PredBBs.begin();
906  assert(CurLoop->contains(PredBB) &&
907  "Expect all predecessors are in the loop");
908  if (PN->getBasicBlockIndex(PredBB) >= 0) {
910  ExitBB, PredBB, ".split.loop.exit", DT, LI, true);
911  // Since we do not allow splitting EH-block with BlockColors in
912  // canSplitPredecessors(), we can simply assign predecessor's color to
913  // the new block.
914  if (!BlockColors.empty()) {
915  // Grab a reference to the ColorVector to be inserted before getting the
916  // reference to the vector we are copying because inserting the new
917  // element in BlockColors might cause the map to be reallocated.
918  ColorVector &ColorsForNewBlock = BlockColors[NewPred];
919  ColorVector &ColorsForOldBlock = BlockColors[PredBB];
920  ColorsForNewBlock = ColorsForOldBlock;
921  }
922  }
923  PredBBs.remove(PredBB);
924  }
925 }
926 
927 /// When an instruction is found to only be used outside of the loop, this
928 /// function moves it to the exit blocks and patches up SSA form as needed.
929 /// This method is guaranteed to remove the original instruction from its
930 /// position, and may either delete it or move it to outside of the loop.
931 ///
932 static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT,
933  const Loop *CurLoop, LoopSafetyInfo *SafetyInfo,
934  OptimizationRemarkEmitter *ORE, bool FreeInLoop) {
935  LLVM_DEBUG(dbgs() << "LICM sinking instruction: " << I << "\n");
936  ORE->emit([&]() {
937  return OptimizationRemark(DEBUG_TYPE, "InstSunk", &I)
938  << "sinking " << ore::NV("Inst", &I);
939  });
940  bool Changed = false;
941  if (isa<LoadInst>(I))
942  ++NumMovedLoads;
943  else if (isa<CallInst>(I))
944  ++NumMovedCalls;
945  ++NumSunk;
946 
947  // Iterate over users to be ready for actual sinking. Replace users via
948  // unrechable blocks with undef and make all user PHIs trivially replcable.
949  SmallPtrSet<Instruction *, 8> VisitedUsers;
950  for (Value::user_iterator UI = I.user_begin(), UE = I.user_end(); UI != UE;) {
951  auto *User = cast<Instruction>(*UI);
952  Use &U = UI.getUse();
953  ++UI;
954 
955  if (VisitedUsers.count(User) || CurLoop->contains(User))
956  continue;
957 
958  if (!DT->isReachableFromEntry(User->getParent())) {
959  U = UndefValue::get(I.getType());
960  Changed = true;
961  continue;
962  }
963 
964  // The user must be a PHI node.
965  PHINode *PN = cast<PHINode>(User);
966 
967  // Surprisingly, instructions can be used outside of loops without any
968  // exits. This can only happen in PHI nodes if the incoming block is
969  // unreachable.
970  BasicBlock *BB = PN->getIncomingBlock(U);
971  if (!DT->isReachableFromEntry(BB)) {
972  U = UndefValue::get(I.getType());
973  Changed = true;
974  continue;
975  }
976 
977  VisitedUsers.insert(PN);
978  if (isTriviallyReplaceablePHI(*PN, I))
979  continue;
980 
981  if (!canSplitPredecessors(PN, SafetyInfo))
982  return Changed;
983 
984  // Split predecessors of the PHI so that we can make users trivially
985  // replaceable.
986  splitPredecessorsOfLoopExit(PN, DT, LI, CurLoop, SafetyInfo);
987 
988  // Should rebuild the iterators, as they may be invalidated by
989  // splitPredecessorsOfLoopExit().
990  UI = I.user_begin();
991  UE = I.user_end();
992  }
993 
994  if (VisitedUsers.empty())
995  return Changed;
996 
997 #ifndef NDEBUG
999  CurLoop->getUniqueExitBlocks(ExitBlocks);
1000  SmallPtrSet<BasicBlock *, 32> ExitBlockSet(ExitBlocks.begin(),
1001  ExitBlocks.end());
1002 #endif
1003 
1004  // Clones of this instruction. Don't create more than one per exit block!
1006 
1007  // If this instruction is only used outside of the loop, then all users are
1008  // PHI nodes in exit blocks due to LCSSA form. Just RAUW them with clones of
1009  // the instruction.
1011  for (auto *UI : Users) {
1012  auto *User = cast<Instruction>(UI);
1013 
1014  if (CurLoop->contains(User))
1015  continue;
1016 
1017  PHINode *PN = cast<PHINode>(User);
1018  assert(ExitBlockSet.count(PN->getParent()) &&
1019  "The LCSSA PHI is not in an exit block!");
1020  // The PHI must be trivially replaceable.
1021  Instruction *New = sinkThroughTriviallyReplaceablePHI(PN, &I, LI, SunkCopies,
1022  SafetyInfo, CurLoop);
1023  PN->replaceAllUsesWith(New);
1024  PN->eraseFromParent();
1025  Changed = true;
1026  }
1027  return Changed;
1028 }
1029 
1030 /// When an instruction is found to only use loop invariant operands that
1031 /// is safe to hoist, this instruction is called to do the dirty work.
1032 ///
1033 static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop,
1034  const LoopSafetyInfo *SafetyInfo,
1036  auto *Preheader = CurLoop->getLoopPreheader();
1037  LLVM_DEBUG(dbgs() << "LICM hoisting to " << Preheader->getName() << ": " << I
1038  << "\n");
1039  ORE->emit([&]() {
1040  return OptimizationRemark(DEBUG_TYPE, "Hoisted", &I) << "hoisting "
1041  << ore::NV("Inst", &I);
1042  });
1043 
1044  // Metadata can be dependent on conditions we are hoisting above.
1045  // Conservatively strip all metadata on the instruction unless we were
1046  // guaranteed to execute I if we entered the loop, in which case the metadata
1047  // is valid in the loop preheader.
1048  if (I.hasMetadataOtherThanDebugLoc() &&
1049  // The check on hasMetadataOtherThanDebugLoc is to prevent us from burning
1050  // time in isGuaranteedToExecute if we don't actually have anything to
1051  // drop. It is a compile time optimization, not required for correctness.
1052  !isGuaranteedToExecute(I, DT, CurLoop, SafetyInfo))
1054 
1055  // Move the new node to the Preheader, before its terminator.
1056  I.moveBefore(Preheader->getTerminator());
1057 
1058  // Do not retain debug locations when we are moving instructions to different
1059  // basic blocks, because we want to avoid jumpy line tables. Calls, however,
1060  // need to retain their debug locs because they may be inlined.
1061  // FIXME: How do we retain source locations without causing poor debugging
1062  // behavior?
1063  if (!isa<CallInst>(I))
1064  I.setDebugLoc(DebugLoc());
1065 
1066  if (isa<LoadInst>(I))
1067  ++NumMovedLoads;
1068  else if (isa<CallInst>(I))
1069  ++NumMovedCalls;
1070  ++NumHoisted;
1071  return true;
1072 }
1073 
1074 /// Only sink or hoist an instruction if it is not a trapping instruction,
1075 /// or if the instruction is known not to trap when moved to the preheader.
1076 /// or if it is a trapping instruction and is guaranteed to execute.
1078  const DominatorTree *DT,
1079  const Loop *CurLoop,
1080  const LoopSafetyInfo *SafetyInfo,
1082  const Instruction *CtxI) {
1083  if (isSafeToSpeculativelyExecute(&Inst, CtxI, DT))
1084  return true;
1085 
1086  bool GuaranteedToExecute =
1087  isGuaranteedToExecute(Inst, DT, CurLoop, SafetyInfo);
1088 
1089  if (!GuaranteedToExecute) {
1090  auto *LI = dyn_cast<LoadInst>(&Inst);
1091  if (LI && CurLoop->isLoopInvariant(LI->getPointerOperand()))
1092  ORE->emit([&]() {
1093  return OptimizationRemarkMissed(
1094  DEBUG_TYPE, "LoadWithLoopInvariantAddressCondExecuted", LI)
1095  << "failed to hoist load with loop-invariant address "
1096  "because load is conditionally executed";
1097  });
1098  }
1099 
1100  return GuaranteedToExecute;
1101 }
1102 
1103 namespace {
1104 class LoopPromoter : public LoadAndStorePromoter {
1105  Value *SomePtr; // Designated pointer to store to.
1106  const SmallSetVector<Value *, 8> &PointerMustAliases;
1107  SmallVectorImpl<BasicBlock *> &LoopExitBlocks;
1108  SmallVectorImpl<Instruction *> &LoopInsertPts;
1109  PredIteratorCache &PredCache;
1110  AliasSetTracker &AST;
1111  LoopInfo &LI;
1112  DebugLoc DL;
1113  int Alignment;
1114  bool UnorderedAtomic;
1115  AAMDNodes AATags;
1116 
1117  Value *maybeInsertLCSSAPHI(Value *V, BasicBlock *BB) const {
1118  if (Instruction *I = dyn_cast<Instruction>(V))
1119  if (Loop *L = LI.getLoopFor(I->getParent()))
1120  if (!L->contains(BB)) {
1121  // We need to create an LCSSA PHI node for the incoming value and
1122  // store that.
1123  PHINode *PN = PHINode::Create(I->getType(), PredCache.size(BB),
1124  I->getName() + ".lcssa", &BB->front());
1125  for (BasicBlock *Pred : PredCache.get(BB))
1126  PN->addIncoming(I, Pred);
1127  return PN;
1128  }
1129  return V;
1130  }
1131 
1132 public:
1133  LoopPromoter(Value *SP, ArrayRef<const Instruction *> Insts, SSAUpdater &S,
1134  const SmallSetVector<Value *, 8> &PMA,
1137  AliasSetTracker &ast, LoopInfo &li, DebugLoc dl, int alignment,
1138  bool UnorderedAtomic, const AAMDNodes &AATags)
1139  : LoadAndStorePromoter(Insts, S), SomePtr(SP), PointerMustAliases(PMA),
1140  LoopExitBlocks(LEB), LoopInsertPts(LIP), PredCache(PIC), AST(ast),
1141  LI(li), DL(std::move(dl)), Alignment(alignment),
1142  UnorderedAtomic(UnorderedAtomic), AATags(AATags) {}
1143 
1144  bool isInstInList(Instruction *I,
1145  const SmallVectorImpl<Instruction *> &) const override {
1146  Value *Ptr;
1147  if (LoadInst *LI = dyn_cast<LoadInst>(I))
1148  Ptr = LI->getOperand(0);
1149  else
1150  Ptr = cast<StoreInst>(I)->getPointerOperand();
1151  return PointerMustAliases.count(Ptr);
1152  }
1153 
1154  void doExtraRewritesBeforeFinalDeletion() const override {
1155  // Insert stores after in the loop exit blocks. Each exit block gets a
1156  // store of the live-out values that feed them. Since we've already told
1157  // the SSA updater about the defs in the loop and the preheader
1158  // definition, it is all set and we can start using it.
1159  for (unsigned i = 0, e = LoopExitBlocks.size(); i != e; ++i) {
1160  BasicBlock *ExitBlock = LoopExitBlocks[i];
1161  Value *LiveInValue = SSA.GetValueInMiddleOfBlock(ExitBlock);
1162  LiveInValue = maybeInsertLCSSAPHI(LiveInValue, ExitBlock);
1163  Value *Ptr = maybeInsertLCSSAPHI(SomePtr, ExitBlock);
1164  Instruction *InsertPos = LoopInsertPts[i];
1165  StoreInst *NewSI = new StoreInst(LiveInValue, Ptr, InsertPos);
1166  if (UnorderedAtomic)
1168  NewSI->setAlignment(Alignment);
1169  NewSI->setDebugLoc(DL);
1170  if (AATags)
1171  NewSI->setAAMetadata(AATags);
1172  }
1173  }
1174 
1175  void replaceLoadWithValue(LoadInst *LI, Value *V) const override {
1176  // Update alias analysis.
1177  AST.copyValue(LI, V);
1178  }
1179  void instructionDeleted(Instruction *I) const override { AST.deleteValue(I); }
1180 };
1181 
1182 
1183 /// Return true iff we can prove that a caller of this function can not inspect
1184 /// the contents of the provided object in a well defined program.
1185 bool isKnownNonEscaping(Value *Object, const TargetLibraryInfo *TLI) {
1186  if (isa<AllocaInst>(Object))
1187  // Since the alloca goes out of scope, we know the caller can't retain a
1188  // reference to it and be well defined. Thus, we don't need to check for
1189  // capture.
1190  return true;
1191 
1192  // For all other objects we need to know that the caller can't possibly
1193  // have gotten a reference to the object. There are two components of
1194  // that:
1195  // 1) Object can't be escaped by this function. This is what
1196  // PointerMayBeCaptured checks.
1197  // 2) Object can't have been captured at definition site. For this, we
1198  // need to know the return value is noalias. At the moment, we use a
1199  // weaker condition and handle only AllocLikeFunctions (which are
1200  // known to be noalias). TODO
1201  return isAllocLikeFn(Object, TLI) &&
1202  !PointerMayBeCaptured(Object, true, true);
1203 }
1204 
1205 } // namespace
1206 
1207 /// Try to promote memory values to scalars by sinking stores out of the
1208 /// loop and moving loads to before the loop. We do this by looping over
1209 /// the stores in the loop, looking for stores to Must pointers which are
1210 /// loop invariant.
1211 ///
1213  const SmallSetVector<Value *, 8> &PointerMustAliases,
1214  SmallVectorImpl<BasicBlock *> &ExitBlocks,
1216  LoopInfo *LI, DominatorTree *DT, const TargetLibraryInfo *TLI,
1217  Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo,
1219  // Verify inputs.
1220  assert(LI != nullptr && DT != nullptr && CurLoop != nullptr &&
1221  CurAST != nullptr && SafetyInfo != nullptr &&
1222  "Unexpected Input to promoteLoopAccessesToScalars");
1223 
1224  Value *SomePtr = *PointerMustAliases.begin();
1225  BasicBlock *Preheader = CurLoop->getLoopPreheader();
1226 
1227  // It is not safe to promote a load/store from the loop if the load/store is
1228  // conditional. For example, turning:
1229  //
1230  // for () { if (c) *P += 1; }
1231  //
1232  // into:
1233  //
1234  // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
1235  //
1236  // is not safe, because *P may only be valid to access if 'c' is true.
1237  //
1238  // The safety property divides into two parts:
1239  // p1) The memory may not be dereferenceable on entry to the loop. In this
1240  // case, we can't insert the required load in the preheader.
1241  // p2) The memory model does not allow us to insert a store along any dynamic
1242  // path which did not originally have one.
1243  //
1244  // If at least one store is guaranteed to execute, both properties are
1245  // satisfied, and promotion is legal.
1246  //
1247  // This, however, is not a necessary condition. Even if no store/load is
1248  // guaranteed to execute, we can still establish these properties.
1249  // We can establish (p1) by proving that hoisting the load into the preheader
1250  // is safe (i.e. proving dereferenceability on all paths through the loop). We
1251  // can use any access within the alias set to prove dereferenceability,
1252  // since they're all must alias.
1253  //
1254  // There are two ways establish (p2):
1255  // a) Prove the location is thread-local. In this case the memory model
1256  // requirement does not apply, and stores are safe to insert.
1257  // b) Prove a store dominates every exit block. In this case, if an exit
1258  // blocks is reached, the original dynamic path would have taken us through
1259  // the store, so inserting a store into the exit block is safe. Note that this
1260  // is different from the store being guaranteed to execute. For instance,
1261  // if an exception is thrown on the first iteration of the loop, the original
1262  // store is never executed, but the exit blocks are not executed either.
1263 
1264  bool DereferenceableInPH = false;
1265  bool SafeToInsertStore = false;
1266 
1268 
1269  // We start with an alignment of one and try to find instructions that allow
1270  // us to prove better alignment.
1271  unsigned Alignment = 1;
1272  // Keep track of which types of access we see
1273  bool SawUnorderedAtomic = false;
1274  bool SawNotAtomic = false;
1275  AAMDNodes AATags;
1276 
1277  const DataLayout &MDL = Preheader->getModule()->getDataLayout();
1278 
1279  bool IsKnownThreadLocalObject = false;
1280  if (SafetyInfo->MayThrow) {
1281  // If a loop can throw, we have to insert a store along each unwind edge.
1282  // That said, we can't actually make the unwind edge explicit. Therefore,
1283  // we have to prove that the store is dead along the unwind edge. We do
1284  // this by proving that the caller can't have a reference to the object
1285  // after return and thus can't possibly load from the object.
1286  Value *Object = GetUnderlyingObject(SomePtr, MDL);
1287  if (!isKnownNonEscaping(Object, TLI))
1288  return false;
1289  // Subtlety: Alloca's aren't visible to callers, but *are* potentially
1290  // visible to other threads if captured and used during their lifetimes.
1291  IsKnownThreadLocalObject = !isa<AllocaInst>(Object);
1292  }
1293 
1294  // Check that all of the pointers in the alias set have the same type. We
1295  // cannot (yet) promote a memory location that is loaded and stored in
1296  // different sizes. While we are at it, collect alignment and AA info.
1297  for (Value *ASIV : PointerMustAliases) {
1298  // Check that all of the pointers in the alias set have the same type. We
1299  // cannot (yet) promote a memory location that is loaded and stored in
1300  // different sizes.
1301  if (SomePtr->getType() != ASIV->getType())
1302  return false;
1303 
1304  for (User *U : ASIV->users()) {
1305  // Ignore instructions that are outside the loop.
1306  Instruction *UI = dyn_cast<Instruction>(U);
1307  if (!UI || !CurLoop->contains(UI))
1308  continue;
1309 
1310  // If there is an non-load/store instruction in the loop, we can't promote
1311  // it.
1312  if (LoadInst *Load = dyn_cast<LoadInst>(UI)) {
1313  assert(!Load->isVolatile() && "AST broken");
1314  if (!Load->isUnordered())
1315  return false;
1316 
1317  SawUnorderedAtomic |= Load->isAtomic();
1318  SawNotAtomic |= !Load->isAtomic();
1319 
1320  if (!DereferenceableInPH)
1321  DereferenceableInPH = isSafeToExecuteUnconditionally(
1322  *Load, DT, CurLoop, SafetyInfo, ORE, Preheader->getTerminator());
1323  } else if (const StoreInst *Store = dyn_cast<StoreInst>(UI)) {
1324  // Stores *of* the pointer are not interesting, only stores *to* the
1325  // pointer.
1326  if (UI->getOperand(1) != ASIV)
1327  continue;
1328  assert(!Store->isVolatile() && "AST broken");
1329  if (!Store->isUnordered())
1330  return false;
1331 
1332  SawUnorderedAtomic |= Store->isAtomic();
1333  SawNotAtomic |= !Store->isAtomic();
1334 
1335  // If the store is guaranteed to execute, both properties are satisfied.
1336  // We may want to check if a store is guaranteed to execute even if we
1337  // already know that promotion is safe, since it may have higher
1338  // alignment than any other guaranteed stores, in which case we can
1339  // raise the alignment on the promoted store.
1340  unsigned InstAlignment = Store->getAlignment();
1341  if (!InstAlignment)
1342  InstAlignment =
1343  MDL.getABITypeAlignment(Store->getValueOperand()->getType());
1344 
1345  if (!DereferenceableInPH || !SafeToInsertStore ||
1346  (InstAlignment > Alignment)) {
1347  if (isGuaranteedToExecute(*UI, DT, CurLoop, SafetyInfo)) {
1348  DereferenceableInPH = true;
1349  SafeToInsertStore = true;
1350  Alignment = std::max(Alignment, InstAlignment);
1351  }
1352  }
1353 
1354  // If a store dominates all exit blocks, it is safe to sink.
1355  // As explained above, if an exit block was executed, a dominating
1356  // store must have been executed at least once, so we are not
1357  // introducing stores on paths that did not have them.
1358  // Note that this only looks at explicit exit blocks. If we ever
1359  // start sinking stores into unwind edges (see above), this will break.
1360  if (!SafeToInsertStore)
1361  SafeToInsertStore = llvm::all_of(ExitBlocks, [&](BasicBlock *Exit) {
1362  return DT->dominates(Store->getParent(), Exit);
1363  });
1364 
1365  // If the store is not guaranteed to execute, we may still get
1366  // deref info through it.
1367  if (!DereferenceableInPH) {
1368  DereferenceableInPH = isDereferenceableAndAlignedPointer(
1369  Store->getPointerOperand(), Store->getAlignment(), MDL,
1370  Preheader->getTerminator(), DT);
1371  }
1372  } else
1373  return false; // Not a load or store.
1374 
1375  // Merge the AA tags.
1376  if (LoopUses.empty()) {
1377  // On the first load/store, just take its AA tags.
1378  UI->getAAMetadata(AATags);
1379  } else if (AATags) {
1380  UI->getAAMetadata(AATags, /* Merge = */ true);
1381  }
1382 
1383  LoopUses.push_back(UI);
1384  }
1385  }
1386 
1387  // If we found both an unordered atomic instruction and a non-atomic memory
1388  // access, bail. We can't blindly promote non-atomic to atomic since we
1389  // might not be able to lower the result. We can't downgrade since that
1390  // would violate memory model. Also, align 0 is an error for atomics.
1391  if (SawUnorderedAtomic && SawNotAtomic)
1392  return false;
1393 
1394  // If we couldn't prove we can hoist the load, bail.
1395  if (!DereferenceableInPH)
1396  return false;
1397 
1398  // We know we can hoist the load, but don't have a guaranteed store.
1399  // Check whether the location is thread-local. If it is, then we can insert
1400  // stores along paths which originally didn't have them without violating the
1401  // memory model.
1402  if (!SafeToInsertStore) {
1403  if (IsKnownThreadLocalObject)
1404  SafeToInsertStore = true;
1405  else {
1406  Value *Object = GetUnderlyingObject(SomePtr, MDL);
1407  SafeToInsertStore =
1408  (isAllocLikeFn(Object, TLI) || isa<AllocaInst>(Object)) &&
1409  !PointerMayBeCaptured(Object, true, true);
1410  }
1411  }
1412 
1413  // If we've still failed to prove we can sink the store, give up.
1414  if (!SafeToInsertStore)
1415  return false;
1416 
1417  // Otherwise, this is safe to promote, lets do it!
1418  LLVM_DEBUG(dbgs() << "LICM: Promoting value stored to in loop: " << *SomePtr
1419  << '\n');
1420  ORE->emit([&]() {
1421  return OptimizationRemark(DEBUG_TYPE, "PromoteLoopAccessesToScalar",
1422  LoopUses[0])
1423  << "Moving accesses to memory location out of the loop";
1424  });
1425  ++NumPromoted;
1426 
1427  // Grab a debug location for the inserted loads/stores; given that the
1428  // inserted loads/stores have little relation to the original loads/stores,
1429  // this code just arbitrarily picks a location from one, since any debug
1430  // location is better than none.
1431  DebugLoc DL = LoopUses[0]->getDebugLoc();
1432 
1433  // We use the SSAUpdater interface to insert phi nodes as required.
1435  SSAUpdater SSA(&NewPHIs);
1436  LoopPromoter Promoter(SomePtr, LoopUses, SSA, PointerMustAliases, ExitBlocks,
1437  InsertPts, PIC, *CurAST, *LI, DL, Alignment,
1438  SawUnorderedAtomic, AATags);
1439 
1440  // Set up the preheader to have a definition of the value. It is the live-out
1441  // value from the preheader that uses in the loop will use.
1442  LoadInst *PreheaderLoad = new LoadInst(
1443  SomePtr, SomePtr->getName() + ".promoted", Preheader->getTerminator());
1444  if (SawUnorderedAtomic)
1445  PreheaderLoad->setOrdering(AtomicOrdering::Unordered);
1446  PreheaderLoad->setAlignment(Alignment);
1447  PreheaderLoad->setDebugLoc(DL);
1448  if (AATags)
1449  PreheaderLoad->setAAMetadata(AATags);
1450  SSA.AddAvailableValue(Preheader, PreheaderLoad);
1451 
1452  // Rewrite all the loads in the loop and remember all the definitions from
1453  // stores in the loop.
1454  Promoter.run(LoopUses);
1455 
1456  // If the SSAUpdater didn't use the load in the preheader, just zap it now.
1457  if (PreheaderLoad->use_empty())
1458  PreheaderLoad->eraseFromParent();
1459 
1460  return true;
1461 }
1462 
1463 /// Returns an owning pointer to an alias set which incorporates aliasing info
1464 /// from L and all subloops of L.
1465 /// FIXME: In new pass manager, there is no helper function to handle loop
1466 /// analysis such as cloneBasicBlockAnalysis, so the AST needs to be recomputed
1467 /// from scratch for every loop. Hook up with the helper functions when
1468 /// available in the new pass manager to avoid redundant computation.
1470 LoopInvariantCodeMotion::collectAliasInfoForLoop(Loop *L, LoopInfo *LI,
1471  AliasAnalysis *AA) {
1472  AliasSetTracker *CurAST = nullptr;
1473  SmallVector<Loop *, 4> RecomputeLoops;
1474  for (Loop *InnerL : L->getSubLoops()) {
1475  auto MapI = LoopToAliasSetMap.find(InnerL);
1476  // If the AST for this inner loop is missing it may have been merged into
1477  // some other loop's AST and then that loop unrolled, and so we need to
1478  // recompute it.
1479  if (MapI == LoopToAliasSetMap.end()) {
1480  RecomputeLoops.push_back(InnerL);
1481  continue;
1482  }
1483  AliasSetTracker *InnerAST = MapI->second;
1484 
1485  if (CurAST != nullptr) {
1486  // What if InnerLoop was modified by other passes ?
1487  CurAST->add(*InnerAST);
1488 
1489  // Once we've incorporated the inner loop's AST into ours, we don't need
1490  // the subloop's anymore.
1491  delete InnerAST;
1492  } else {
1493  CurAST = InnerAST;
1494  }
1495  LoopToAliasSetMap.erase(MapI);
1496  }
1497  if (CurAST == nullptr)
1498  CurAST = new AliasSetTracker(*AA);
1499 
1500  auto mergeLoop = [&](Loop *L) {
1501  // Loop over the body of this loop, looking for calls, invokes, and stores.
1502  for (BasicBlock *BB : L->blocks())
1503  CurAST->add(*BB); // Incorporate the specified basic block
1504  };
1505 
1506  // Add everything from the sub loops that are no longer directly available.
1507  for (Loop *InnerL : RecomputeLoops)
1508  mergeLoop(InnerL);
1509 
1510  // And merge in this loop.
1511  mergeLoop(L);
1512 
1513  return CurAST;
1514 }
1515 
1516 /// Simple analysis hook. Clone alias set info.
1517 ///
1518 void LegacyLICMPass::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To,
1519  Loop *L) {
1520  AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1521  if (!AST)
1522  return;
1523 
1524  AST->copyValue(From, To);
1525 }
1526 
1527 /// Simple Analysis hook. Delete value V from alias set
1528 ///
1529 void LegacyLICMPass::deleteAnalysisValue(Value *V, Loop *L) {
1530  AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1531  if (!AST)
1532  return;
1533 
1534  AST->deleteValue(V);
1535 }
1536 
1537 /// Simple Analysis hook. Delete value L from alias set map.
1538 ///
1539 void LegacyLICMPass::deleteAnalysisLoop(Loop *L) {
1540  AliasSetTracker *AST = LICM.getLoopToAliasSetMap().lookup(L);
1541  if (!AST)
1542  return;
1543 
1544  delete AST;
1545  LICM.getLoopToAliasSetMap().erase(L);
1546 }
1547 
1548 /// Return true if the body of this loop may store into the memory
1549 /// location pointed to by V.
1550 ///
1551 static bool pointerInvalidatedByLoop(Value *V, uint64_t Size,
1552  const AAMDNodes &AAInfo,
1553  AliasSetTracker *CurAST) {
1554  // Check to see if any of the basic blocks in CurLoop invalidate *V.
1555  return CurAST->getAliasSetForPointer(V, Size, AAInfo).isMod();
1556 }
1557 
1558 /// Little predicate that returns true if the specified basic block is in
1559 /// a subloop of the current one, not the current one itself.
1560 ///
1561 static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI) {
1562  assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
1563  return LI->getLoopFor(BB) != CurLoop;
1564 }
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
uint64_t CallInst * C
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks &#39;this&#39; from the containing basic block and deletes it.
Definition: Instruction.cpp:68
bool canSplitPredecessors() const
Definition: BasicBlock.cpp:365
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static bool isTriviallyReplaceablePHI(const PHINode &PN, const Instruction &I)
Returns true if a PHINode is a trivially replaceable with an Instruction.
Definition: LICM.cpp:693
Helper class for SSA formation on a set of values defined in multiple blocks.
Definition: SSAUpdater.h:39
Diagnostic information for missed-optimization remarks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * getPointerOperand(Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:687
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
This is the interface for a simple mod/ref and alias analysis over globals.
EltTy front() const
bool hasMetadataOtherThanDebugLoc() const
Return true if this instruction has metadata attached to it other than a debug location.
Definition: Instruction.h:194
void dropUnknownNonDebugMetadata(ArrayRef< unsigned > KnownIDs)
Drop all unknown metadata except for debug locations.
Definition: Metadata.cpp:1199
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:137
bool hasDedicatedExits() const
Return true if no exit block for the loop has a predecessor that is outside the loop.
Definition: LoopInfoImpl.h:86
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
Definition: LoopInfo.cpp:176
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
Definition: SSAUpdater.cpp:67
void add(Value *Ptr, LocationSize Size, const AAMDNodes &AAInfo)
These methods are used to add different types of instructions to the alias sets.
The main scalar evolution driver.
This class represents a function call, abstracting a target machine&#39;s calling convention.
This file contains the declarations for metadata subclasses.
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this load instruction.
Definition: Instructions.h:243
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
Definition: LoopInfoImpl.h:174
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
Definition: Type.cpp:617
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
Definition: Local.cpp:1598
bool onlyReadsMemory(ImmutableCallSite CS)
Checks if the specified call is known to only read from non-volatile memory (or not access memory at ...
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:714
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:908
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
static bool isFreeInLoop(const Instruction &I, const Loop *CurLoop, const TargetTransformInfo *TTI)
Return true if the instruction is free in the loop.
Definition: LICM.cpp:702
STATISTIC(NumFunctions, "Total number of functions")
A debug info location.
Definition: DebugLoc.h:34
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:225
F(f)
static CallInst * Create(Value *Func, ArrayRef< Value *> Args, ArrayRef< OperandBundleDef > Bundles=None, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
An instruction for reading from memory.
Definition: Instructions.h:168
Hexagon Common GEP
iv Induction Variable Users
Definition: IVUsers.cpp:52
void reserve(size_type N)
Definition: SmallVector.h:377
TinyPtrVector - This class is specialized for cases where there are normally 0 or 1 element in a vect...
Definition: TinyPtrVector.h:31
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:295
op_iterator op_begin()
Definition: User.h:230
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
Definition: LoopInfo.cpp:63
DenseMap< BasicBlock *, ColorVector > BlockColors
Definition: MustExecute.h:44
iterator begin()
Instruction iterator methods.
Definition: BasicBlock.h:264
Loop Invariant Code Motion
Definition: LICM.cpp:238
bool formLCSSARecursively(Loop &L, DominatorTree &DT, LoopInfo *LI, ScalarEvolution *SE)
Put a loop nest into LCSSA form.
Definition: LCSSA.cpp:343
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
Definition: BasicBlock.cpp:134
ArrayRef< BasicBlock * > get(BasicBlock *BB)
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:51
Legacy analysis pass which computes MemorySSA.
Definition: MemorySSA.h:918
This is the interface for a SCEV-based alias analysis.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:361
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Definition: LoopInfo.h:684
static bool hoist(Instruction &I, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE)
When an instruction is found to only use loop invariant operands that is safe to hoist, this instruction is called to do the dirty work.
Definition: LICM.cpp:1033
bool hasAllowReciprocal() const
Determine whether the allow-reciprocal flag is set.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
virtual bool doFinalization(Module &)
doFinalization - Virtual method overriden by subclasses to do any necessary clean up after all passes...
Definition: Pass.h:110
Encapsulates MemorySSA, including all data associated with memory accesses.
Definition: MemorySSA.h:680
uint32_t getTagID() const
Return the tag of this operand bundle as an integer.
Definition: InstrTypes.h:1250
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:295
Analysis pass that exposes the LoopInfo for a function.
Definition: LoopInfo.h:939
bool remove(const value_type &X)
Remove an item from the set vector.
Definition: SetVector.h:158
BlockT * getHeader() const
Definition: LoopInfo.h:100
void computeLoopSafetyInfo(LoopSafetyInfo *, Loop *)
Computes safety information for a loop checks loop body & header for the possibility of may throw exc...
Definition: MustExecute.cpp:28
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:237
INITIALIZE_PASS_BEGIN(LegacyLICMPass, "licm", "Loop Invariant Code Motion", false, false) INITIALIZE_PASS_END(LegacyLICMPass
Instruction * clone() const
Create a copy of &#39;this&#39; instruction that is identical in all ways except the following: ...
AliasSet & getAliasSetForPointer(Value *P, LocationSize Size, const AAMDNodes &AAInfo)
Return the alias set that the specified pointer lives in.
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:245
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
static bool pointerInvalidatedByLoop(Value *V, uint64_t Size, const AAMDNodes &AAInfo, AliasSetTracker *CurAST)
Return true if the body of this loop may store into the memory location pointed to by V...
Definition: LICM.cpp:1551
PredIteratorCache - This class is an extremely trivial cache for predecessor iterator queries...
FunctionModRefBehavior
Summary of how a function affects memory in the program.
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
iterator begin()
Get an iterator to the beginning of the SetVector.
Definition: SetVector.h:83
This class represents a no-op cast from one type to another.
Memory SSA
Definition: MemorySSA.cpp:66
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
Definition: Instruction.h:126
An instruction for storing to memory.
Definition: Instructions.h:310
static cl::opt< bool > DisablePromotion("disable-licm-promotion", cl::Hidden, cl::init(false), cl::desc("Disable memory promotion in LICM pass"))
Memory promotion is enabled by default.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:439
bool promoteLoopAccessesToScalars(const SmallSetVector< Value *, 8 > &, SmallVectorImpl< BasicBlock *> &, SmallVectorImpl< Instruction *> &, PredIteratorCache &, LoopInfo *, DominatorTree *, const TargetLibraryInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *)
Try to promote memory values to scalars by sinking stores out of the loop and moving loads to before ...
Definition: LICM.cpp:1212
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
Definition: Dominators.h:142
Value * getOperand(unsigned i) const
Definition: User.h:170
size_type count(const key_type &key) const
Count the number of elements of a given key in the SetVector.
Definition: SetVector.h:211
void forgetLoopDispositions(const Loop *L)
Called when the client has changed the disposition of values in this loop.
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
Checks whether the given location points to constant memory, or if OrLocal is true whether it points ...
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
Definition: Instructions.h:841
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:410
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
Definition: BasicBlock.cpp:189
Wrapper pass for TargetTransformInfo.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
Definition: BasicBlock.cpp:218
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
Definition: Instruction.h:287
void setAAMetadata(const AAMDNodes &N)
Sets the metadata on this instruction from the AAMDNodes structure.
Definition: Metadata.cpp:1265
LLVM Basic Block Representation.
Definition: BasicBlock.h:59
size_t size(BasicBlock *BB) const
bool sinkRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, TargetTransformInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *ORE)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
Definition: LICM.cpp:369
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Definition: Constant.h:42
LLVM_NODISCARD bool empty() const
Definition: SmallPtrSet.h:92
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Definition: SmallVector.h:117
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Definition: BasicBlock.h:276
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
Expected to fold away in lowering.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
Diagnostic information for applied optimization remarks.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Definition: Interval.h:113
Pass * createLICMPass()
Definition: LICM.cpp:241
FunctionModRefBehavior getModRefBehavior(ImmutableCallSite CS)
Return the behavior of the given call site.
Represent the analysis usage information of a pass.
op_iterator op_end()
Definition: User.h:232
bool any_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:915
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
Definition: LICM.cpp:206
Interval::pred_iterator pred_end(Interval *I)
Definition: Interval.h:116
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
static bool canSplitPredecessors(PHINode *PN, LoopSafetyInfo *SafetyInfo)
Definition: LICM.cpp:840
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Definition: SmallPtrSet.h:382
bool isMod() const
void setAlignment(unsigned Align)
static UndefValue * get(Type *T)
Static factory methods - Return an &#39;undef&#39; object of the specified type.
Definition: Constants.cpp:1392
const AMDGPUAS & AS
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
bool PointerMayBeCaptured(const Value *V, bool ReturnCaptures, bool StoreCaptures)
PointerMayBeCaptured - Return true if this pointer value may be captured by the enclosing function (w...
static bool isLoadInvariantInLoop(LoadInst *LI, DominatorTree *DT, Loop *CurLoop)
Definition: LICM.cpp:529
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
Value * GetUnderlyingObject(Value *V, const DataLayout &DL, unsigned MaxLookup=6)
This method strips off any GEP address adjustments and pointer casts from the specified value...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
This function does not perform any non-local loads or stores to memory.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
Definition: LoopInfo.cpp:57
static cl::opt< uint32_t > MaxNumUsesTraversed("licm-max-num-uses-traversed", cl::Hidden, cl::init(8), cl::desc("Max num uses visited for identifying load " "invariance in loop using invariant start (default = 8)"))
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:51
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
const InstListType & getInstList() const
Return the underlying instruction list container.
Definition: BasicBlock.h:329
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Definition: LoopInfo.h:110
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:298
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
void emit(DiagnosticInfoOptimizationBase &OptDiag)
Output the remark via the diagnostic handler and to the optimization record file. ...
#define DEBUG_TYPE
Definition: LICM.cpp:74
static void splitPredecessorsOfLoopExit(PHINode *PN, DominatorTree *DT, LoopInfo *LI, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo)
Definition: LICM.cpp:858
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
iterator end()
Definition: BasicBlock.h:266
An analysis over an "inner" IR unit that provides access to an analysis manager over a "outer" IR uni...
Definition: PassManager.h:1062
Helper class for promoting a collection of loads and stores into SSA Form using the SSAUpdater...
Definition: SSAUpdater.h:133
void copyValue(Value *From, Value *To)
This method should be used whenever a preexisting value in the program is copied or cloned...
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Definition: Dominators.cpp:244
Provides information about what library functions are available for the current target.
unsigned getABITypeAlignment(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
Definition: DataLayout.cpp:722
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
Definition: Metadata.h:642
bool hoistRegion(DomTreeNode *, AliasAnalysis *, LoopInfo *, DominatorTree *, TargetLibraryInfo *, Loop *, AliasSetTracker *, LoopSafetyInfo *, OptimizationRemarkEmitter *ORE)
Walk the specified region of the CFG (defined by all blocks dominated by the specified block...
Definition: LICM.cpp:435
static bool isNotUsedOrFreeInLoop(const Instruction &I, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, TargetTransformInfo *TTI, bool &FreeInLoop)
Return true if the only users of this instruction are outside of the loop.
Definition: LICM.cpp:730
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
Definition: Constants.cpp:684
unsigned getNumIncomingValues() const
Return the number of incoming edges.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:133
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:56
A lightweight accessor for an operand bundle meant to be passed around by value.
Definition: InstrTypes.h:1222
iterator_range< user_iterator > users()
Definition: Value.h:399
static bool isSafeToExecuteUnconditionally(Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, const Instruction *CtxI=nullptr)
Only sink or hoist an instruction if it is not a trapping instruction, or if the instruction is known...
Definition: LICM.cpp:1077
uint64_t getTypeSizeInBits(Type *Ty) const
Size examples:
Definition: DataLayout.h:560
LoopT * getParentLoop() const
Definition: LoopInfo.h:101
const std::vector< LoopT * > & getSubLoops() const
Return the loops contained entirely within this loop.
Definition: LoopInfo.h:131
void setOrdering(AtomicOrdering Ordering)
Sets the ordering constraint of this store instruction.
Definition: Instructions.h:368
static bool onlyAccessesArgPointees(FunctionModRefBehavior MRB)
Checks if functions with the specified behavior are known to read and write at most from objects poin...
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Definition: SmallVector.h:121
iterator insert(iterator where, pointer New)
Definition: ilist.h:228
Captures loop safety information.
Definition: MustExecute.h:39
static Instruction * CloneInstructionInExitBlock(Instruction &I, BasicBlock &ExitBlock, PHINode &PN, const LoopInfo *LI, const LoopSafetyInfo *SafetyInfo)
Definition: LICM.cpp:763
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:653
int getUserCost(const User *U, ArrayRef< const Value *> Operands) const
Estimate the cost of a given IR user when lowered.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:62
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:459
StringRef getName() const
Return a constant reference to the value&#39;s name.
Definition: Value.cpp:224
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
Definition: BasicBlock.h:108
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:73
user_iterator_impl< User > user_iterator
Definition: Value.h:368
bool isAllocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates memory (either malloc...
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass&#39;s AnalysisUsage.
Definition: LoopUtils.cpp:1226
licm
Definition: LICM.cpp:238
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
SmallVector< DomTreeNode *, 16 > collectChildrenInLoop(DomTreeNode *N, const Loop *CurLoop)
Does a BFS from a given node to all of its children inside a given loop.
Definition: LoopUtils.cpp:1325
bool empty() const
Definition: LoopInfo.h:146
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
Definition: Instructions.h:280
static bool inSubLoop(BasicBlock *BB, Loop *CurLoop, LoopInfo *LI)
Little predicate that returns true if the specified basic block is in a subloop of the current one...
Definition: LICM.cpp:1561
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
Definition: Value.h:375
Value * getArgOperand(unsigned i) const
getArgOperand/setArgOperand - Return/set the i-th call argument.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
Definition: Local.cpp:346
LLVM Value Representation.
Definition: Value.h:73
void setAlignment(unsigned Align)
uint64_t getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type...
Definition: DataLayout.h:411
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
Definition: Instruction.cpp:87
void initializeLegacyLICMPassPass(PassRegistry &)
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Definition: Instruction.h:552
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
The legacy pass manager&#39;s analysis pass to compute loop information.
Definition: LoopInfo.h:964
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
Definition: LoopInfoImpl.h:100
This is the interface for LLVM&#39;s primary stateless and local alias analysis.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
Definition: Dominators.h:254
bool isDereferenceableAndAlignedPointer(const Value *V, unsigned Align, const DataLayout &DL, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Returns true if V is always a dereferenceable pointer with alignment greater or equal than requested...
Definition: Loads.cpp:129
bool canSinkOrHoistInst(Instruction &I, AAResults *AA, DominatorTree *DT, Loop *CurLoop, AliasSetTracker *CurAST, LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE=nullptr)
Returns true if the hoister and sinker can handle this instruction.
Definition: LICM.cpp:578
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
Definition: BasicBlock.cpp:138
#define LLVM_DEBUG(X)
Definition: Debug.h:119
op_range incoming_values()
iterator_range< block_iterator > blocks() const
Definition: LoopInfo.h:156
bool isGuaranteedToExecute(const Instruction &Inst, const DominatorTree *DT, const Loop *CurLoop, const LoopSafetyInfo *SafetyInfo)
Returns true if the instruction in a loop is guaranteed to execute at least once (under the assumptio...
static IntegerType * getInt8Ty(LLVMContext &C)
Definition: Type.cpp:174
The optimization diagnostic interface.
static bool sink(Instruction &I, LoopInfo *LI, DominatorTree *DT, const Loop *CurLoop, LoopSafetyInfo *SafetyInfo, OptimizationRemarkEmitter *ORE, bool FreeInLoop)
When an instruction is found to only be used outside of the loop, this function moves it to the exit ...
Definition: LICM.cpp:932
bool use_empty() const
Definition: Value.h:322
unsigned size() const
void deleteValue(Value *PtrVal)
This method is used to remove a pointer value from the AliasSetTracker entirely.
loop versioning Loop Versioning For LICM
A wrapper class for inspecting calls to intrinsic functions.
Definition: IntrinsicInst.h:44
const BasicBlock * getParent() const
Definition: Instruction.h:67
cl::opt< bool > EnableMSSALoopDependency
Enables memory ssa as a dependency for loop passes.
user_iterator user_end()
Definition: Value.h:383
static Instruction * sinkThroughTriviallyReplaceablePHI(PHINode *TPN, Instruction *I, LoopInfo *LI, SmallDenseMap< BasicBlock *, Instruction *, 32 > &SunkCopies, const LoopSafetyInfo *SafetyInfo, const Loop *CurLoop)
Definition: LICM.cpp:823