1 //===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
16 // This pass uses alias analysis for two purposes:
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 mem2reg functionality to construct the appropriate SSA form for the
32 //===----------------------------------------------------------------------===//
34 #define DEBUG_TYPE "licm"
35 #include "llvm/Transforms/Scalar.h"
36 #include "llvm/Constants.h"
37 #include "llvm/DerivedTypes.h"
38 #include "llvm/Instructions.h"
39 #include "llvm/Target/TargetData.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/LoopPass.h"
42 #include "llvm/Analysis/AliasAnalysis.h"
43 #include "llvm/Analysis/AliasSetTracker.h"
44 #include "llvm/Analysis/Dominators.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Transforms/Utils/PromoteMemToReg.h"
47 #include "llvm/Support/CFG.h"
48 #include "llvm/Support/Compiler.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/ADT/Statistic.h"
55 STATISTIC(NumSunk
, "Number of instructions sunk out of loop");
56 STATISTIC(NumHoisted
, "Number of instructions hoisted out of loop");
57 STATISTIC(NumMovedLoads
, "Number of load insts hoisted or sunk");
58 STATISTIC(NumMovedCalls
, "Number of call insts hoisted or sunk");
59 STATISTIC(NumPromoted
, "Number of memory locations promoted to registers");
62 DisablePromotion("disable-licm-promotion", cl::Hidden
,
63 cl::desc("Disable memory promotion in LICM pass"));
65 // This feature is currently disabled by default because CodeGen is not yet
66 // capable of rematerializing these constants in PIC mode, so it can lead to
67 // degraded performance. Compile test/CodeGen/X86/remat-constant.ll with
68 // -relocation-model=pic to see an example of this.
70 EnableLICMConstantMotion("enable-licm-constant-variables", cl::Hidden
,
71 cl::desc("Enable hoisting/sinking of constant "
75 struct VISIBILITY_HIDDEN LICM
: public LoopPass
{
76 static char ID
; // Pass identification, replacement for typeid
77 LICM() : LoopPass(&ID
) {}
79 virtual bool runOnLoop(Loop
*L
, LPPassManager
&LPM
);
81 /// This transformation requires natural loop information & requires that
82 /// loop preheaders be inserted into the CFG...
84 virtual void getAnalysisUsage(AnalysisUsage
&AU
) const {
86 AU
.addRequiredID(LoopSimplifyID
);
87 AU
.addRequired
<LoopInfo
>();
88 AU
.addRequired
<DominatorTree
>();
89 AU
.addRequired
<DominanceFrontier
>(); // For scalar promotion (mem2reg)
90 AU
.addRequired
<AliasAnalysis
>();
91 AU
.addPreserved
<ScalarEvolution
>();
92 AU
.addPreserved
<DominanceFrontier
>();
95 bool doFinalization() {
96 // Free the values stored in the map
97 for (std::map
<Loop
*, AliasSetTracker
*>::iterator
98 I
= LoopToAliasMap
.begin(), E
= LoopToAliasMap
.end(); I
!= E
; ++I
)
101 LoopToAliasMap
.clear();
106 // Various analyses that we use...
107 AliasAnalysis
*AA
; // Current AliasAnalysis information
108 LoopInfo
*LI
; // Current LoopInfo
109 DominatorTree
*DT
; // Dominator Tree for the current Loop...
110 DominanceFrontier
*DF
; // Current Dominance Frontier
112 // State that is updated as we process loops
113 bool Changed
; // Set to true when we change anything.
114 BasicBlock
*Preheader
; // The preheader block of the current loop...
115 Loop
*CurLoop
; // The current loop we are working on...
116 AliasSetTracker
*CurAST
; // AliasSet information for the current loop...
117 std::map
<Loop
*, AliasSetTracker
*> LoopToAliasMap
;
119 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
120 void cloneBasicBlockAnalysis(BasicBlock
*From
, BasicBlock
*To
, Loop
*L
);
122 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
124 void deleteAnalysisValue(Value
*V
, Loop
*L
);
126 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
127 /// dominated by the specified block, and that are in the current loop) in
128 /// reverse depth first order w.r.t the DominatorTree. This allows us to
129 /// visit uses before definitions, allowing us to sink a loop body in one
130 /// pass without iteration.
132 void SinkRegion(DomTreeNode
*N
);
134 /// HoistRegion - Walk the specified region of the CFG (defined by all
135 /// blocks dominated by the specified block, and that are in the current
136 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
137 /// visit definitions before uses, allowing us to hoist a loop body in one
138 /// pass without iteration.
140 void HoistRegion(DomTreeNode
*N
);
142 /// inSubLoop - Little predicate that returns true if the specified basic
143 /// block is in a subloop of the current one, not the current one itself.
145 bool inSubLoop(BasicBlock
*BB
) {
146 assert(CurLoop
->contains(BB
) && "Only valid if BB is IN the loop");
147 for (Loop::iterator I
= CurLoop
->begin(), E
= CurLoop
->end(); I
!= E
; ++I
)
148 if ((*I
)->contains(BB
))
149 return true; // A subloop actually contains this block!
153 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
154 /// specified exit block of the loop is dominated by the specified block
155 /// that is in the body of the loop. We use these constraints to
156 /// dramatically limit the amount of the dominator tree that needs to be
158 bool isExitBlockDominatedByBlockInLoop(BasicBlock
*ExitBlock
,
159 BasicBlock
*BlockInLoop
) const {
160 // If the block in the loop is the loop header, it must be dominated!
161 BasicBlock
*LoopHeader
= CurLoop
->getHeader();
162 if (BlockInLoop
== LoopHeader
)
165 DomTreeNode
*BlockInLoopNode
= DT
->getNode(BlockInLoop
);
166 DomTreeNode
*IDom
= DT
->getNode(ExitBlock
);
168 // Because the exit block is not in the loop, we know we have to get _at
169 // least_ its immediate dominator.
171 // Get next Immediate Dominator.
172 IDom
= IDom
->getIDom();
174 // If we have got to the header of the loop, then the instructions block
175 // did not dominate the exit node, so we can't hoist it.
176 if (IDom
->getBlock() == LoopHeader
)
179 } while (IDom
!= BlockInLoopNode
);
184 /// sink - When an instruction is found to only be used outside of the loop,
185 /// this function moves it to the exit blocks and patches up SSA form as
188 void sink(Instruction
&I
);
190 /// hoist - When an instruction is found to only use loop invariant operands
191 /// that is safe to hoist, this instruction is called to do the dirty work.
193 void hoist(Instruction
&I
);
195 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
196 /// is not a trapping instruction or if it is a trapping instruction and is
197 /// guaranteed to execute.
199 bool isSafeToExecuteUnconditionally(Instruction
&I
);
201 /// pointerInvalidatedByLoop - Return true if the body of this loop may
202 /// store into the memory location pointed to by V.
204 bool pointerInvalidatedByLoop(Value
*V
, unsigned Size
) {
205 // Check to see if any of the basic blocks in CurLoop invalidate *V.
206 return CurAST
->getAliasSetForPointer(V
, Size
).isMod();
209 bool canSinkOrHoistInst(Instruction
&I
);
210 bool isLoopInvariantInst(Instruction
&I
);
211 bool isNotUsedInLoop(Instruction
&I
);
213 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
214 /// to scalars as we can.
216 void PromoteValuesInLoop();
218 /// FindPromotableValuesInLoop - Check the current loop for stores to
219 /// definite pointers, which are not loaded and stored through may aliases.
220 /// If these are found, create an alloca for the value, add it to the
221 /// PromotedValues list, and keep track of the mapping from value to
224 void FindPromotableValuesInLoop(
225 std::vector
<std::pair
<AllocaInst
*, Value
*> > &PromotedValues
,
226 std::map
<Value
*, AllocaInst
*> &Val2AlMap
);
231 static RegisterPass
<LICM
> X("licm", "Loop Invariant Code Motion");
233 Pass
*llvm::createLICMPass() { return new LICM(); }
235 /// Hoist expressions out of the specified loop. Note, alias info for inner
236 /// loop is not preserved so it is not a good idea to run LICM multiple
237 /// times on one loop.
239 bool LICM::runOnLoop(Loop
*L
, LPPassManager
&LPM
) {
242 // Get our Loop and Alias Analysis information...
243 LI
= &getAnalysis
<LoopInfo
>();
244 AA
= &getAnalysis
<AliasAnalysis
>();
245 DF
= &getAnalysis
<DominanceFrontier
>();
246 DT
= &getAnalysis
<DominatorTree
>();
248 CurAST
= new AliasSetTracker(*AA
);
249 // Collect Alias info from subloops
250 for (Loop::iterator LoopItr
= L
->begin(), LoopItrE
= L
->end();
251 LoopItr
!= LoopItrE
; ++LoopItr
) {
252 Loop
*InnerL
= *LoopItr
;
253 AliasSetTracker
*InnerAST
= LoopToAliasMap
[InnerL
];
254 assert (InnerAST
&& "Where is my AST?");
256 // What if InnerLoop was modified by other passes ?
257 CurAST
->add(*InnerAST
);
262 // Get the preheader block to move instructions into...
263 Preheader
= L
->getLoopPreheader();
264 assert(Preheader
&&"Preheader insertion pass guarantees we have a preheader!");
266 // Loop over the body of this loop, looking for calls, invokes, and stores.
267 // Because subloops have already been incorporated into AST, we skip blocks in
270 for (Loop::block_iterator I
= L
->block_begin(), E
= L
->block_end();
273 if (LI
->getLoopFor(BB
) == L
) // Ignore blocks in subloops...
274 CurAST
->add(*BB
); // Incorporate the specified basic block
277 // We want to visit all of the instructions in this loop... that are not parts
278 // of our subloops (they have already had their invariants hoisted out of
279 // their loop, into this loop, so there is no need to process the BODIES of
282 // Traverse the body of the loop in depth first order on the dominator tree so
283 // that we are guaranteed to see definitions before we see uses. This allows
284 // us to sink instructions in one pass, without iteration. After sinking
285 // instructions, we perform another pass to hoist them out of the loop.
287 SinkRegion(DT
->getNode(L
->getHeader()));
288 HoistRegion(DT
->getNode(L
->getHeader()));
290 // Now that all loop invariants have been removed from the loop, promote any
291 // memory references to scalars that we can...
292 if (!DisablePromotion
)
293 PromoteValuesInLoop();
295 // Clear out loops state information for the next iteration
299 LoopToAliasMap
[L
] = CurAST
;
303 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
304 /// dominated by the specified block, and that are in the current loop) in
305 /// reverse depth first order w.r.t the DominatorTree. This allows us to visit
306 /// uses before definitions, allowing us to sink a loop body in one pass without
309 void LICM::SinkRegion(DomTreeNode
*N
) {
310 assert(N
!= 0 && "Null dominator tree node?");
311 BasicBlock
*BB
= N
->getBlock();
313 // If this subregion is not in the top level loop at all, exit.
314 if (!CurLoop
->contains(BB
)) return;
316 // We are processing blocks in reverse dfo, so process children first...
317 const std::vector
<DomTreeNode
*> &Children
= N
->getChildren();
318 for (unsigned i
= 0, e
= Children
.size(); i
!= e
; ++i
)
319 SinkRegion(Children
[i
]);
321 // Only need to process the contents of this block if it is not part of a
322 // subloop (which would already have been processed).
323 if (inSubLoop(BB
)) return;
325 for (BasicBlock::iterator II
= BB
->end(); II
!= BB
->begin(); ) {
326 Instruction
&I
= *--II
;
328 // Check to see if we can sink this instruction to the exit blocks
329 // of the loop. We can do this if the all users of the instruction are
330 // outside of the loop. In this case, it doesn't even matter if the
331 // operands of the instruction are loop invariant.
333 if (isNotUsedInLoop(I
) && canSinkOrHoistInst(I
)) {
341 /// HoistRegion - Walk the specified region of the CFG (defined by all blocks
342 /// dominated by the specified block, and that are in the current loop) in depth
343 /// first order w.r.t the DominatorTree. This allows us to visit definitions
344 /// before uses, allowing us to hoist a loop body in one pass without iteration.
346 void LICM::HoistRegion(DomTreeNode
*N
) {
347 assert(N
!= 0 && "Null dominator tree node?");
348 BasicBlock
*BB
= N
->getBlock();
350 // If this subregion is not in the top level loop at all, exit.
351 if (!CurLoop
->contains(BB
)) return;
353 // Only need to process the contents of this block if it is not part of a
354 // subloop (which would already have been processed).
356 for (BasicBlock::iterator II
= BB
->begin(), E
= BB
->end(); II
!= E
; ) {
357 Instruction
&I
= *II
++;
359 // Try hoisting the instruction out to the preheader. We can only do this
360 // if all of the operands of the instruction are loop invariant and if it
361 // is safe to hoist the instruction.
363 if (isLoopInvariantInst(I
) && canSinkOrHoistInst(I
) &&
364 isSafeToExecuteUnconditionally(I
))
368 const std::vector
<DomTreeNode
*> &Children
= N
->getChildren();
369 for (unsigned i
= 0, e
= Children
.size(); i
!= e
; ++i
)
370 HoistRegion(Children
[i
]);
373 /// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
376 bool LICM::canSinkOrHoistInst(Instruction
&I
) {
377 // Loads have extra constraints we have to verify before we can hoist them.
378 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(&I
)) {
379 if (LI
->isVolatile())
380 return false; // Don't hoist volatile loads!
382 // Loads from constant memory are always safe to move, even if they end up
383 // in the same alias set as something that ends up being modified.
384 if (EnableLICMConstantMotion
&&
385 AA
->pointsToConstantMemory(LI
->getOperand(0)))
388 // Don't hoist loads which have may-aliased stores in loop.
390 if (LI
->getType()->isSized())
391 Size
= AA
->getTargetData().getTypeStoreSize(LI
->getType());
392 return !pointerInvalidatedByLoop(LI
->getOperand(0), Size
);
393 } else if (CallInst
*CI
= dyn_cast
<CallInst
>(&I
)) {
394 // Handle obvious cases efficiently.
395 AliasAnalysis::ModRefBehavior Behavior
= AA
->getModRefBehavior(CI
);
396 if (Behavior
== AliasAnalysis::DoesNotAccessMemory
)
398 else if (Behavior
== AliasAnalysis::OnlyReadsMemory
) {
399 // If this call only reads from memory and there are no writes to memory
400 // in the loop, we can hoist or sink the call as appropriate.
401 bool FoundMod
= false;
402 for (AliasSetTracker::iterator I
= CurAST
->begin(), E
= CurAST
->end();
405 if (!AS
.isForwardingAliasSet() && AS
.isMod()) {
410 if (!FoundMod
) return true;
413 // FIXME: This should use mod/ref information to see if we can hoist or sink
419 // Otherwise these instructions are hoistable/sinkable
420 return isa
<BinaryOperator
>(I
) || isa
<CastInst
>(I
) ||
421 isa
<SelectInst
>(I
) || isa
<GetElementPtrInst
>(I
) || isa
<CmpInst
>(I
) ||
422 isa
<InsertElementInst
>(I
) || isa
<ExtractElementInst
>(I
) ||
423 isa
<ShuffleVectorInst
>(I
);
426 /// isNotUsedInLoop - Return true if the only users of this instruction are
427 /// outside of the loop. If this is true, we can sink the instruction to the
428 /// exit blocks of the loop.
430 bool LICM::isNotUsedInLoop(Instruction
&I
) {
431 for (Value::use_iterator UI
= I
.use_begin(), E
= I
.use_end(); UI
!= E
; ++UI
) {
432 Instruction
*User
= cast
<Instruction
>(*UI
);
433 if (PHINode
*PN
= dyn_cast
<PHINode
>(User
)) {
434 // PHI node uses occur in predecessor blocks!
435 for (unsigned i
= 0, e
= PN
->getNumIncomingValues(); i
!= e
; ++i
)
436 if (PN
->getIncomingValue(i
) == &I
)
437 if (CurLoop
->contains(PN
->getIncomingBlock(i
)))
439 } else if (CurLoop
->contains(User
->getParent())) {
447 /// isLoopInvariantInst - Return true if all operands of this instruction are
448 /// loop invariant. We also filter out non-hoistable instructions here just for
451 bool LICM::isLoopInvariantInst(Instruction
&I
) {
452 // The instruction is loop invariant if all of its operands are loop-invariant
453 for (unsigned i
= 0, e
= I
.getNumOperands(); i
!= e
; ++i
)
454 if (!CurLoop
->isLoopInvariant(I
.getOperand(i
)))
457 // If we got this far, the instruction is loop invariant!
461 /// sink - When an instruction is found to only be used outside of the loop,
462 /// this function moves it to the exit blocks and patches up SSA form as needed.
463 /// This method is guaranteed to remove the original instruction from its
464 /// position, and may either delete it or move it to outside of the loop.
466 void LICM::sink(Instruction
&I
) {
467 DOUT
<< "LICM sinking instruction: " << I
;
469 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
470 CurLoop
->getExitBlocks(ExitBlocks
);
472 if (isa
<LoadInst
>(I
)) ++NumMovedLoads
;
473 else if (isa
<CallInst
>(I
)) ++NumMovedCalls
;
477 // The case where there is only a single exit node of this loop is common
478 // enough that we handle it as a special (more efficient) case. It is more
479 // efficient to handle because there are no PHI nodes that need to be placed.
480 if (ExitBlocks
.size() == 1) {
481 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks
[0], I
.getParent())) {
482 // Instruction is not used, just delete it.
483 CurAST
->deleteValue(&I
);
484 if (!I
.use_empty()) // If I has users in unreachable blocks, eliminate.
485 I
.replaceAllUsesWith(UndefValue::get(I
.getType()));
488 // Move the instruction to the start of the exit block, after any PHI
490 I
.removeFromParent();
492 BasicBlock::iterator InsertPt
= ExitBlocks
[0]->getFirstNonPHI();
493 ExitBlocks
[0]->getInstList().insert(InsertPt
, &I
);
495 } else if (ExitBlocks
.empty()) {
496 // The instruction is actually dead if there ARE NO exit blocks.
497 CurAST
->deleteValue(&I
);
498 if (!I
.use_empty()) // If I has users in unreachable blocks, eliminate.
499 I
.replaceAllUsesWith(UndefValue::get(I
.getType()));
502 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
503 // do all of the hard work of inserting PHI nodes as necessary. We convert
504 // the value into a stack object to get it to do this.
506 // Firstly, we create a stack object to hold the value...
509 if (I
.getType() != Type::VoidTy
) {
510 AI
= new AllocaInst(I
.getType(), 0, I
.getName(),
511 I
.getParent()->getParent()->getEntryBlock().begin());
515 // Secondly, insert load instructions for each use of the instruction
516 // outside of the loop.
517 while (!I
.use_empty()) {
518 Instruction
*U
= cast
<Instruction
>(I
.use_back());
520 // If the user is a PHI Node, we actually have to insert load instructions
521 // in all predecessor blocks, not in the PHI block itself!
522 if (PHINode
*UPN
= dyn_cast
<PHINode
>(U
)) {
523 // Only insert into each predecessor once, so that we don't have
524 // different incoming values from the same block!
525 std::map
<BasicBlock
*, Value
*> InsertedBlocks
;
526 for (unsigned i
= 0, e
= UPN
->getNumIncomingValues(); i
!= e
; ++i
)
527 if (UPN
->getIncomingValue(i
) == &I
) {
528 BasicBlock
*Pred
= UPN
->getIncomingBlock(i
);
529 Value
*&PredVal
= InsertedBlocks
[Pred
];
531 // Insert a new load instruction right before the terminator in
532 // the predecessor block.
533 PredVal
= new LoadInst(AI
, "", Pred
->getTerminator());
534 CurAST
->add(cast
<LoadInst
>(PredVal
));
537 UPN
->setIncomingValue(i
, PredVal
);
541 LoadInst
*L
= new LoadInst(AI
, "", U
);
542 U
->replaceUsesOfWith(&I
, L
);
547 // Thirdly, insert a copy of the instruction in each exit block of the loop
548 // that is dominated by the instruction, storing the result into the memory
549 // location. Be careful not to insert the instruction into any particular
550 // basic block more than once.
551 std::set
<BasicBlock
*> InsertedBlocks
;
552 BasicBlock
*InstOrigBB
= I
.getParent();
554 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
) {
555 BasicBlock
*ExitBlock
= ExitBlocks
[i
];
557 if (isExitBlockDominatedByBlockInLoop(ExitBlock
, InstOrigBB
)) {
558 // If we haven't already processed this exit block, do so now.
559 if (InsertedBlocks
.insert(ExitBlock
).second
) {
560 // Insert the code after the last PHI node...
561 BasicBlock::iterator InsertPt
= ExitBlock
->getFirstNonPHI();
563 // If this is the first exit block processed, just move the original
564 // instruction, otherwise clone the original instruction and insert
567 if (InsertedBlocks
.size() == 1) {
568 I
.removeFromParent();
569 ExitBlock
->getInstList().insert(InsertPt
, &I
);
573 CurAST
->copyValue(&I
, New
);
574 if (!I
.getName().empty())
575 New
->setName(I
.getName()+".le");
576 ExitBlock
->getInstList().insert(InsertPt
, New
);
579 // Now that we have inserted the instruction, store it into the alloca
580 if (AI
) new StoreInst(New
, AI
, InsertPt
);
585 // If the instruction doesn't dominate any exit blocks, it must be dead.
586 if (InsertedBlocks
.empty()) {
587 CurAST
->deleteValue(&I
);
591 // Finally, promote the fine value to SSA form.
593 std::vector
<AllocaInst
*> Allocas
;
594 Allocas
.push_back(AI
);
595 PromoteMemToReg(Allocas
, *DT
, *DF
, CurAST
);
600 /// hoist - When an instruction is found to only use loop invariant operands
601 /// that is safe to hoist, this instruction is called to do the dirty work.
603 void LICM::hoist(Instruction
&I
) {
604 DOUT
<< "LICM hoisting to " << Preheader
->getName() << ": " << I
;
606 // Remove the instruction from its current basic block... but don't delete the
608 I
.removeFromParent();
610 // Insert the new node in Preheader, before the terminator.
611 Preheader
->getInstList().insert(Preheader
->getTerminator(), &I
);
613 if (isa
<LoadInst
>(I
)) ++NumMovedLoads
;
614 else if (isa
<CallInst
>(I
)) ++NumMovedCalls
;
619 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
620 /// not a trapping instruction or if it is a trapping instruction and is
621 /// guaranteed to execute.
623 bool LICM::isSafeToExecuteUnconditionally(Instruction
&Inst
) {
624 // If it is not a trapping instruction, it is always safe to hoist.
625 if (!Inst
.isTrapping()) return true;
627 // Otherwise we have to check to make sure that the instruction dominates all
628 // of the exit blocks. If it doesn't, then there is a path out of the loop
629 // which does not execute this instruction, so we can't hoist it.
631 // If the instruction is in the header block for the loop (which is very
632 // common), it is always guaranteed to dominate the exit blocks. Since this
633 // is a common case, and can save some work, check it now.
634 if (Inst
.getParent() == CurLoop
->getHeader())
637 // It's always safe to load from a global or alloca.
638 if (isa
<LoadInst
>(Inst
))
639 if (isa
<AllocationInst
>(Inst
.getOperand(0)) ||
640 isa
<GlobalVariable
>(Inst
.getOperand(0)))
643 // Get the exit blocks for the current loop.
644 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
645 CurLoop
->getExitBlocks(ExitBlocks
);
647 // For each exit block, get the DT node and walk up the DT until the
648 // instruction's basic block is found or we exit the loop.
649 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
)
650 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks
[i
], Inst
.getParent()))
657 /// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
658 /// stores out of the loop and moving loads to before the loop. We do this by
659 /// looping over the stores in the loop, looking for stores to Must pointers
660 /// which are loop invariant. We promote these memory locations to use allocas
661 /// instead. These allocas can easily be raised to register values by the
662 /// PromoteMem2Reg functionality.
664 void LICM::PromoteValuesInLoop() {
665 // PromotedValues - List of values that are promoted out of the loop. Each
666 // value has an alloca instruction for it, and a canonical version of the
668 std::vector
<std::pair
<AllocaInst
*, Value
*> > PromotedValues
;
669 std::map
<Value
*, AllocaInst
*> ValueToAllocaMap
; // Map of ptr to alloca
671 FindPromotableValuesInLoop(PromotedValues
, ValueToAllocaMap
);
672 if (ValueToAllocaMap
.empty()) return; // If there are values to promote.
675 NumPromoted
+= PromotedValues
.size();
677 std::vector
<Value
*> PointerValueNumbers
;
679 // Emit a copy from the value into the alloca'd value in the loop preheader
680 TerminatorInst
*LoopPredInst
= Preheader
->getTerminator();
681 for (unsigned i
= 0, e
= PromotedValues
.size(); i
!= e
; ++i
) {
682 Value
*Ptr
= PromotedValues
[i
].second
;
684 // If we are promoting a pointer value, update alias information for the
686 Value
*LoadValue
= 0;
687 if (isa
<PointerType
>(cast
<PointerType
>(Ptr
->getType())->getElementType())) {
688 // Locate a load or store through the pointer, and assign the same value
689 // to LI as we are loading or storing. Since we know that the value is
690 // stored in this loop, this will always succeed.
691 for (Value::use_iterator UI
= Ptr
->use_begin(), E
= Ptr
->use_end();
693 if (LoadInst
*LI
= dyn_cast
<LoadInst
>(*UI
)) {
696 } else if (StoreInst
*SI
= dyn_cast
<StoreInst
>(*UI
)) {
697 if (SI
->getOperand(1) == Ptr
) {
698 LoadValue
= SI
->getOperand(0);
702 assert(LoadValue
&& "No store through the pointer found!");
703 PointerValueNumbers
.push_back(LoadValue
); // Remember this for later.
706 // Load from the memory we are promoting.
707 LoadInst
*LI
= new LoadInst(Ptr
, Ptr
->getName()+".promoted", LoopPredInst
);
709 if (LoadValue
) CurAST
->copyValue(LoadValue
, LI
);
711 // Store into the temporary alloca.
712 new StoreInst(LI
, PromotedValues
[i
].first
, LoopPredInst
);
715 // Scan the basic blocks in the loop, replacing uses of our pointers with
716 // uses of the allocas in question.
718 for (Loop::block_iterator I
= CurLoop
->block_begin(),
719 E
= CurLoop
->block_end(); I
!= E
; ++I
) {
721 // Rewrite all loads and stores in the block of the pointer...
722 for (BasicBlock::iterator II
= BB
->begin(), E
= BB
->end(); II
!= E
; ++II
) {
723 if (LoadInst
*L
= dyn_cast
<LoadInst
>(II
)) {
724 std::map
<Value
*, AllocaInst
*>::iterator
725 I
= ValueToAllocaMap
.find(L
->getOperand(0));
726 if (I
!= ValueToAllocaMap
.end())
727 L
->setOperand(0, I
->second
); // Rewrite load instruction...
728 } else if (StoreInst
*S
= dyn_cast
<StoreInst
>(II
)) {
729 std::map
<Value
*, AllocaInst
*>::iterator
730 I
= ValueToAllocaMap
.find(S
->getOperand(1));
731 if (I
!= ValueToAllocaMap
.end())
732 S
->setOperand(1, I
->second
); // Rewrite store instruction...
737 // Now that the body of the loop uses the allocas instead of the original
738 // memory locations, insert code to copy the alloca value back into the
739 // original memory location on all exits from the loop. Note that we only
740 // want to insert one copy of the code in each exit block, though the loop may
741 // exit to the same block more than once.
743 SmallPtrSet
<BasicBlock
*, 16> ProcessedBlocks
;
745 SmallVector
<BasicBlock
*, 8> ExitBlocks
;
746 CurLoop
->getExitBlocks(ExitBlocks
);
747 for (unsigned i
= 0, e
= ExitBlocks
.size(); i
!= e
; ++i
) {
748 if (!ProcessedBlocks
.insert(ExitBlocks
[i
]))
751 // Copy all of the allocas into their memory locations.
752 BasicBlock::iterator BI
= ExitBlocks
[i
]->getFirstNonPHI();
753 Instruction
*InsertPos
= BI
;
755 for (unsigned i
= 0, e
= PromotedValues
.size(); i
!= e
; ++i
) {
756 // Load from the alloca.
757 LoadInst
*LI
= new LoadInst(PromotedValues
[i
].first
, "", InsertPos
);
759 // If this is a pointer type, update alias info appropriately.
760 if (isa
<PointerType
>(LI
->getType()))
761 CurAST
->copyValue(PointerValueNumbers
[PVN
++], LI
);
763 // Store into the memory we promoted.
764 new StoreInst(LI
, PromotedValues
[i
].second
, InsertPos
);
768 // Now that we have done the deed, use the mem2reg functionality to promote
769 // all of the new allocas we just created into real SSA registers.
771 std::vector
<AllocaInst
*> PromotedAllocas
;
772 PromotedAllocas
.reserve(PromotedValues
.size());
773 for (unsigned i
= 0, e
= PromotedValues
.size(); i
!= e
; ++i
)
774 PromotedAllocas
.push_back(PromotedValues
[i
].first
);
775 PromoteMemToReg(PromotedAllocas
, *DT
, *DF
, CurAST
);
778 /// FindPromotableValuesInLoop - Check the current loop for stores to definite
779 /// pointers, which are not loaded and stored through may aliases and are safe
780 /// for promotion. If these are found, create an alloca for the value, add it
781 /// to the PromotedValues list, and keep track of the mapping from value to
783 void LICM::FindPromotableValuesInLoop(
784 std::vector
<std::pair
<AllocaInst
*, Value
*> > &PromotedValues
,
785 std::map
<Value
*, AllocaInst
*> &ValueToAllocaMap
) {
786 Instruction
*FnStart
= CurLoop
->getHeader()->getParent()->begin()->begin();
788 // Loop over all of the alias sets in the tracker object.
789 for (AliasSetTracker::iterator I
= CurAST
->begin(), E
= CurAST
->end();
792 // We can promote this alias set if it has a store, if it is a "Must" alias
793 // set, if the pointer is loop invariant, and if we are not eliminating any
794 // volatile loads or stores.
795 if (AS
.isForwardingAliasSet() || !AS
.isMod() || !AS
.isMustAlias() ||
796 AS
.isVolatile() || !CurLoop
->isLoopInvariant(AS
.begin()->getValue()))
799 assert(!AS
.empty() &&
800 "Must alias set should have at least one pointer element in it!");
801 Value
*V
= AS
.begin()->getValue();
803 // Check that all of the pointers in the alias set have the same type. We
804 // cannot (yet) promote a memory location that is loaded and stored in
807 bool PointerOk
= true;
808 for (AliasSet::iterator I
= AS
.begin(), E
= AS
.end(); I
!= E
; ++I
)
809 if (V
->getType() != I
->getValue()->getType()) {
817 // It isn't safe to promote a load/store from the loop if the load/store is
818 // conditional. For example, turning:
820 // for () { if (c) *P += 1; }
824 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
826 // is not safe, because *P may only be valid to access if 'c' is true.
828 // It is safe to promote P if all uses are direct load/stores and if at
829 // least one is guaranteed to be executed.
830 bool GuaranteedToExecute
= false;
831 bool InvalidInst
= false;
832 for (Value::use_iterator UI
= V
->use_begin(), UE
= V
->use_end();
834 // Ignore instructions not in this loop.
835 Instruction
*Use
= dyn_cast
<Instruction
>(*UI
);
836 if (!Use
|| !CurLoop
->contains(Use
->getParent()))
839 if (!isa
<LoadInst
>(Use
) && !isa
<StoreInst
>(Use
)) {
844 if (!GuaranteedToExecute
)
845 GuaranteedToExecute
= isSafeToExecuteUnconditionally(*Use
);
848 // If there is an non-load/store instruction in the loop, we can't promote
849 // it. If there isn't a guaranteed-to-execute instruction, we can't
851 if (InvalidInst
|| !GuaranteedToExecute
)
854 const Type
*Ty
= cast
<PointerType
>(V
->getType())->getElementType();
855 AllocaInst
*AI
= new AllocaInst(Ty
, 0, V
->getName()+".tmp", FnStart
);
856 PromotedValues
.push_back(std::make_pair(AI
, V
));
858 // Update the AST and alias analysis.
859 CurAST
->copyValue(V
, AI
);
861 for (AliasSet::iterator I
= AS
.begin(), E
= AS
.end(); I
!= E
; ++I
)
862 ValueToAllocaMap
.insert(std::make_pair(I
->getValue(), AI
));
864 DOUT
<< "LICM: Promoting value: " << *V
<< "\n";
868 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
869 void LICM::cloneBasicBlockAnalysis(BasicBlock
*From
, BasicBlock
*To
, Loop
*L
) {
870 AliasSetTracker
*AST
= LoopToAliasMap
[L
];
874 AST
->copyValue(From
, To
);
877 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
879 void LICM::deleteAnalysisValue(Value
*V
, Loop
*L
) {
880 AliasSetTracker
*AST
= LoopToAliasMap
[L
];