blob: 13440c13b653ebe6b6c55ec877efe023a7109eb8 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- LICM.cpp - Loop Invariant Code Motion Pass ------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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 mem2reg functionality to construct the appropriate SSA form for the
30// variable.
31//
32//===----------------------------------------------------------------------===//
33
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"
Devang Patel05b69282007-07-30 20:19:59 +000045#include "llvm/Analysis/ScalarEvolution.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046#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"
52#include <algorithm>
53using namespace llvm;
54
55STATISTIC(NumSunk , "Number of instructions sunk out of loop");
56STATISTIC(NumHoisted , "Number of instructions hoisted out of loop");
57STATISTIC(NumMovedLoads, "Number of load insts hoisted or sunk");
58STATISTIC(NumMovedCalls, "Number of call insts hoisted or sunk");
59STATISTIC(NumPromoted , "Number of memory locations promoted to registers");
60
Dan Gohman089efff2008-05-13 00:00:25 +000061static cl::opt<bool>
62DisablePromotion("disable-licm-promotion", cl::Hidden,
63 cl::desc("Disable memory promotion in LICM pass"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064
Dan Gohman089efff2008-05-13 00:00:25 +000065namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000066 struct VISIBILITY_HIDDEN LICM : public LoopPass {
67 static char ID; // Pass identification, replacement for typeid
68 LICM() : LoopPass((intptr_t)&ID) {}
69
70 virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
71
72 /// This transformation requires natural loop information & requires that
73 /// loop preheaders be inserted into the CFG...
74 ///
75 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.setPreservesCFG();
77 AU.addRequiredID(LoopSimplifyID);
78 AU.addRequired<LoopInfo>();
79 AU.addRequired<DominatorTree>();
80 AU.addRequired<DominanceFrontier>(); // For scalar promotion (mem2reg)
81 AU.addRequired<AliasAnalysis>();
Devang Patel05b69282007-07-30 20:19:59 +000082 AU.addPreserved<ScalarEvolution>();
83 AU.addPreserved<DominanceFrontier>();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084 }
85
86 bool doFinalization() {
Anton Korobeynikovb421ad42007-11-25 23:52:02 +000087 // Free the values stored in the map
88 for (std::map<Loop *, AliasSetTracker *>::iterator
89 I = LoopToAliasMap.begin(), E = LoopToAliasMap.end(); I != E; ++I)
90 delete I->second;
91
Dan Gohmanf17a25c2007-07-18 16:29:46 +000092 LoopToAliasMap.clear();
93 return false;
94 }
95
96 private:
97 // Various analyses that we use...
98 AliasAnalysis *AA; // Current AliasAnalysis information
99 LoopInfo *LI; // Current LoopInfo
100 DominatorTree *DT; // Dominator Tree for the current Loop...
101 DominanceFrontier *DF; // Current Dominance Frontier
102
103 // State that is updated as we process loops
104 bool Changed; // Set to true when we change anything.
105 BasicBlock *Preheader; // The preheader block of the current loop...
106 Loop *CurLoop; // The current loop we are working on...
107 AliasSetTracker *CurAST; // AliasSet information for the current loop...
108 std::map<Loop *, AliasSetTracker *> LoopToAliasMap;
109
Devang Patel09e66c02007-07-31 08:01:41 +0000110 /// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
111 void cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L);
112
113 /// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
114 /// set.
115 void deleteAnalysisValue(Value *V, Loop *L);
116
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000117 /// SinkRegion - Walk the specified region of the CFG (defined by all blocks
118 /// dominated by the specified block, and that are in the current loop) in
119 /// reverse depth first order w.r.t the DominatorTree. This allows us to
120 /// visit uses before definitions, allowing us to sink a loop body in one
121 /// pass without iteration.
122 ///
123 void SinkRegion(DomTreeNode *N);
124
125 /// HoistRegion - Walk the specified region of the CFG (defined by all
126 /// blocks dominated by the specified block, and that are in the current
127 /// loop) in depth first order w.r.t the DominatorTree. This allows us to
128 /// visit definitions before uses, allowing us to hoist a loop body in one
129 /// pass without iteration.
130 ///
131 void HoistRegion(DomTreeNode *N);
132
133 /// inSubLoop - Little predicate that returns true if the specified basic
134 /// block is in a subloop of the current one, not the current one itself.
135 ///
136 bool inSubLoop(BasicBlock *BB) {
137 assert(CurLoop->contains(BB) && "Only valid if BB is IN the loop");
138 for (Loop::iterator I = CurLoop->begin(), E = CurLoop->end(); I != E; ++I)
139 if ((*I)->contains(BB))
140 return true; // A subloop actually contains this block!
141 return false;
142 }
143
144 /// isExitBlockDominatedByBlockInLoop - This method checks to see if the
145 /// specified exit block of the loop is dominated by the specified block
146 /// that is in the body of the loop. We use these constraints to
147 /// dramatically limit the amount of the dominator tree that needs to be
148 /// searched.
149 bool isExitBlockDominatedByBlockInLoop(BasicBlock *ExitBlock,
150 BasicBlock *BlockInLoop) const {
151 // If the block in the loop is the loop header, it must be dominated!
152 BasicBlock *LoopHeader = CurLoop->getHeader();
153 if (BlockInLoop == LoopHeader)
154 return true;
155
156 DomTreeNode *BlockInLoopNode = DT->getNode(BlockInLoop);
157 DomTreeNode *IDom = DT->getNode(ExitBlock);
158
159 // Because the exit block is not in the loop, we know we have to get _at
160 // least_ its immediate dominator.
161 do {
162 // Get next Immediate Dominator.
163 IDom = IDom->getIDom();
164
165 // If we have got to the header of the loop, then the instructions block
166 // did not dominate the exit node, so we can't hoist it.
167 if (IDom->getBlock() == LoopHeader)
168 return false;
169
170 } while (IDom != BlockInLoopNode);
171
172 return true;
173 }
174
175 /// sink - When an instruction is found to only be used outside of the loop,
176 /// this function moves it to the exit blocks and patches up SSA form as
177 /// needed.
178 ///
179 void sink(Instruction &I);
180
181 /// hoist - When an instruction is found to only use loop invariant operands
182 /// that is safe to hoist, this instruction is called to do the dirty work.
183 ///
184 void hoist(Instruction &I);
185
186 /// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it
187 /// is not a trapping instruction or if it is a trapping instruction and is
188 /// guaranteed to execute.
189 ///
190 bool isSafeToExecuteUnconditionally(Instruction &I);
191
192 /// pointerInvalidatedByLoop - Return true if the body of this loop may
193 /// store into the memory location pointed to by V.
194 ///
195 bool pointerInvalidatedByLoop(Value *V, unsigned Size) {
196 // Check to see if any of the basic blocks in CurLoop invalidate *V.
197 return CurAST->getAliasSetForPointer(V, Size).isMod();
198 }
199
200 bool canSinkOrHoistInst(Instruction &I);
201 bool isLoopInvariantInst(Instruction &I);
202 bool isNotUsedInLoop(Instruction &I);
203
204 /// PromoteValuesInLoop - Look at the stores in the loop and promote as many
205 /// to scalars as we can.
206 ///
207 void PromoteValuesInLoop();
208
209 /// FindPromotableValuesInLoop - Check the current loop for stores to
210 /// definite pointers, which are not loaded and stored through may aliases.
211 /// If these are found, create an alloca for the value, add it to the
212 /// PromotedValues list, and keep track of the mapping from value to
213 /// alloca...
214 ///
215 void FindPromotableValuesInLoop(
216 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
217 std::map<Value*, AllocaInst*> &Val2AlMap);
218 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219}
220
Dan Gohman089efff2008-05-13 00:00:25 +0000221char LICM::ID = 0;
222static RegisterPass<LICM> X("licm", "Loop Invariant Code Motion");
223
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000224LoopPass *llvm::createLICMPass() { return new LICM(); }
225
Devang Patelb6858ae2007-07-31 16:52:25 +0000226/// Hoist expressions out of the specified loop. Note, alias info for inner
227/// loop is not preserved so it is not a good idea to run LICM multiple
228/// times on one loop.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000229///
230bool LICM::runOnLoop(Loop *L, LPPassManager &LPM) {
231 Changed = false;
232
233 // Get our Loop and Alias Analysis information...
234 LI = &getAnalysis<LoopInfo>();
235 AA = &getAnalysis<AliasAnalysis>();
236 DF = &getAnalysis<DominanceFrontier>();
237 DT = &getAnalysis<DominatorTree>();
238
239 CurAST = new AliasSetTracker(*AA);
240 // Collect Alias info from subloops
241 for (Loop::iterator LoopItr = L->begin(), LoopItrE = L->end();
242 LoopItr != LoopItrE; ++LoopItr) {
243 Loop *InnerL = *LoopItr;
244 AliasSetTracker *InnerAST = LoopToAliasMap[InnerL];
245 assert (InnerAST && "Where is my AST?");
246
247 // What if InnerLoop was modified by other passes ?
248 CurAST->add(*InnerAST);
249 }
250
251 CurLoop = L;
252
253 // Get the preheader block to move instructions into...
254 Preheader = L->getLoopPreheader();
255 assert(Preheader&&"Preheader insertion pass guarantees we have a preheader!");
256
257 // Loop over the body of this loop, looking for calls, invokes, and stores.
258 // Because subloops have already been incorporated into AST, we skip blocks in
259 // subloops.
260 //
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000261 for (Loop::block_iterator I = L->block_begin(), E = L->block_end();
262 I != E; ++I) {
263 BasicBlock *BB = *I;
264 if (LI->getLoopFor(BB) == L) // Ignore blocks in subloops...
265 CurAST->add(*BB); // Incorporate the specified basic block
266 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267
268 // We want to visit all of the instructions in this loop... that are not parts
269 // of our subloops (they have already had their invariants hoisted out of
270 // their loop, into this loop, so there is no need to process the BODIES of
271 // the subloops).
272 //
273 // Traverse the body of the loop in depth first order on the dominator tree so
274 // that we are guaranteed to see definitions before we see uses. This allows
Nick Lewyckyd97cbf12007-08-18 15:08:56 +0000275 // us to sink instructions in one pass, without iteration. After sinking
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000276 // instructions, we perform another pass to hoist them out of the loop.
277 //
278 SinkRegion(DT->getNode(L->getHeader()));
279 HoistRegion(DT->getNode(L->getHeader()));
280
281 // Now that all loop invariants have been removed from the loop, promote any
282 // memory references to scalars that we can...
283 if (!DisablePromotion)
284 PromoteValuesInLoop();
285
286 // Clear out loops state information for the next iteration
287 CurLoop = 0;
288 Preheader = 0;
289
290 LoopToAliasMap[L] = CurAST;
291 return Changed;
292}
293
294/// SinkRegion - Walk the specified region of the CFG (defined by all blocks
295/// dominated by the specified block, and that are in the current loop) in
296/// reverse depth first order w.r.t the DominatorTree. This allows us to visit
297/// uses before definitions, allowing us to sink a loop body in one pass without
298/// iteration.
299///
300void LICM::SinkRegion(DomTreeNode *N) {
301 assert(N != 0 && "Null dominator tree node?");
302 BasicBlock *BB = N->getBlock();
303
304 // If this subregion is not in the top level loop at all, exit.
305 if (!CurLoop->contains(BB)) return;
306
307 // We are processing blocks in reverse dfo, so process children first...
308 const std::vector<DomTreeNode*> &Children = N->getChildren();
309 for (unsigned i = 0, e = Children.size(); i != e; ++i)
310 SinkRegion(Children[i]);
311
312 // Only need to process the contents of this block if it is not part of a
313 // subloop (which would already have been processed).
314 if (inSubLoop(BB)) return;
315
316 for (BasicBlock::iterator II = BB->end(); II != BB->begin(); ) {
317 Instruction &I = *--II;
318
319 // Check to see if we can sink this instruction to the exit blocks
320 // of the loop. We can do this if the all users of the instruction are
321 // outside of the loop. In this case, it doesn't even matter if the
322 // operands of the instruction are loop invariant.
323 //
324 if (isNotUsedInLoop(I) && canSinkOrHoistInst(I)) {
325 ++II;
326 sink(I);
327 }
328 }
329}
330
331
332/// HoistRegion - Walk the specified region of the CFG (defined by all blocks
333/// dominated by the specified block, and that are in the current loop) in depth
334/// first order w.r.t the DominatorTree. This allows us to visit definitions
335/// before uses, allowing us to hoist a loop body in one pass without iteration.
336///
337void LICM::HoistRegion(DomTreeNode *N) {
338 assert(N != 0 && "Null dominator tree node?");
339 BasicBlock *BB = N->getBlock();
340
341 // If this subregion is not in the top level loop at all, exit.
342 if (!CurLoop->contains(BB)) return;
343
344 // Only need to process the contents of this block if it is not part of a
345 // subloop (which would already have been processed).
346 if (!inSubLoop(BB))
347 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ) {
348 Instruction &I = *II++;
349
350 // Try hoisting the instruction out to the preheader. We can only do this
351 // if all of the operands of the instruction are loop invariant and if it
352 // is safe to hoist the instruction.
353 //
354 if (isLoopInvariantInst(I) && canSinkOrHoistInst(I) &&
355 isSafeToExecuteUnconditionally(I))
356 hoist(I);
357 }
358
359 const std::vector<DomTreeNode*> &Children = N->getChildren();
360 for (unsigned i = 0, e = Children.size(); i != e; ++i)
361 HoistRegion(Children[i]);
362}
363
364/// canSinkOrHoistInst - Return true if the hoister and sinker can handle this
365/// instruction.
366///
367bool LICM::canSinkOrHoistInst(Instruction &I) {
368 // Loads have extra constraints we have to verify before we can hoist them.
369 if (LoadInst *LI = dyn_cast<LoadInst>(&I)) {
370 if (LI->isVolatile())
371 return false; // Don't hoist volatile loads!
372
Chris Lattner12cf43f2008-07-23 05:06:28 +0000373 // Loads from constant memory are always safe to move, even if they end up
374 // in the same alias set as something that ends up being modified.
375 if (AA->pointsToConstantMemory(LI->getOperand(0)))
376 return true;
377
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 // Don't hoist loads which have may-aliased stores in loop.
379 unsigned Size = 0;
380 if (LI->getType()->isSized())
Duncan Sandsf99fdc62007-11-01 20:53:16 +0000381 Size = AA->getTargetData().getTypeStoreSize(LI->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382 return !pointerInvalidatedByLoop(LI->getOperand(0), Size);
383 } else if (CallInst *CI = dyn_cast<CallInst>(&I)) {
384 // Handle obvious cases efficiently.
Duncan Sands00b24b52007-12-01 07:51:45 +0000385 AliasAnalysis::ModRefBehavior Behavior = AA->getModRefBehavior(CI);
386 if (Behavior == AliasAnalysis::DoesNotAccessMemory)
387 return true;
388 else if (Behavior == AliasAnalysis::OnlyReadsMemory) {
389 // If this call only reads from memory and there are no writes to memory
390 // in the loop, we can hoist or sink the call as appropriate.
391 bool FoundMod = false;
392 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
393 I != E; ++I) {
394 AliasSet &AS = *I;
395 if (!AS.isForwardingAliasSet() && AS.isMod()) {
396 FoundMod = true;
397 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000398 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000399 }
Duncan Sands00b24b52007-12-01 07:51:45 +0000400 if (!FoundMod) return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 }
402
403 // FIXME: This should use mod/ref information to see if we can hoist or sink
404 // the call.
405
406 return false;
407 }
408
409 // Otherwise these instructions are hoistable/sinkable
410 return isa<BinaryOperator>(I) || isa<CastInst>(I) ||
411 isa<SelectInst>(I) || isa<GetElementPtrInst>(I) || isa<CmpInst>(I) ||
412 isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
413 isa<ShuffleVectorInst>(I);
414}
415
416/// isNotUsedInLoop - Return true if the only users of this instruction are
417/// outside of the loop. If this is true, we can sink the instruction to the
418/// exit blocks of the loop.
419///
420bool LICM::isNotUsedInLoop(Instruction &I) {
421 for (Value::use_iterator UI = I.use_begin(), E = I.use_end(); UI != E; ++UI) {
422 Instruction *User = cast<Instruction>(*UI);
423 if (PHINode *PN = dyn_cast<PHINode>(User)) {
424 // PHI node uses occur in predecessor blocks!
425 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
426 if (PN->getIncomingValue(i) == &I)
427 if (CurLoop->contains(PN->getIncomingBlock(i)))
428 return false;
429 } else if (CurLoop->contains(User->getParent())) {
430 return false;
431 }
432 }
433 return true;
434}
435
436
437/// isLoopInvariantInst - Return true if all operands of this instruction are
438/// loop invariant. We also filter out non-hoistable instructions here just for
439/// efficiency.
440///
441bool LICM::isLoopInvariantInst(Instruction &I) {
442 // The instruction is loop invariant if all of its operands are loop-invariant
443 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
444 if (!CurLoop->isLoopInvariant(I.getOperand(i)))
445 return false;
446
447 // If we got this far, the instruction is loop invariant!
448 return true;
449}
450
451/// sink - When an instruction is found to only be used outside of the loop,
452/// this function moves it to the exit blocks and patches up SSA form as needed.
453/// This method is guaranteed to remove the original instruction from its
454/// position, and may either delete it or move it to outside of the loop.
455///
456void LICM::sink(Instruction &I) {
457 DOUT << "LICM sinking instruction: " << I;
458
Devang Patel02451fa2007-08-21 00:31:24 +0000459 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000460 CurLoop->getExitBlocks(ExitBlocks);
461
462 if (isa<LoadInst>(I)) ++NumMovedLoads;
463 else if (isa<CallInst>(I)) ++NumMovedCalls;
464 ++NumSunk;
465 Changed = true;
466
467 // The case where there is only a single exit node of this loop is common
468 // enough that we handle it as a special (more efficient) case. It is more
469 // efficient to handle because there are no PHI nodes that need to be placed.
470 if (ExitBlocks.size() == 1) {
471 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[0], I.getParent())) {
472 // Instruction is not used, just delete it.
473 CurAST->deleteValue(&I);
474 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
475 I.replaceAllUsesWith(UndefValue::get(I.getType()));
476 I.eraseFromParent();
477 } else {
478 // Move the instruction to the start of the exit block, after any PHI
479 // nodes in it.
480 I.removeFromParent();
481
Dan Gohman514277c2008-05-23 21:05:58 +0000482 BasicBlock::iterator InsertPt = ExitBlocks[0]->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483 ExitBlocks[0]->getInstList().insert(InsertPt, &I);
484 }
Dan Gohman301f4052008-01-29 13:02:09 +0000485 } else if (ExitBlocks.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 // The instruction is actually dead if there ARE NO exit blocks.
487 CurAST->deleteValue(&I);
488 if (!I.use_empty()) // If I has users in unreachable blocks, eliminate.
489 I.replaceAllUsesWith(UndefValue::get(I.getType()));
490 I.eraseFromParent();
491 } else {
492 // Otherwise, if we have multiple exits, use the PromoteMem2Reg function to
493 // do all of the hard work of inserting PHI nodes as necessary. We convert
494 // the value into a stack object to get it to do this.
495
496 // Firstly, we create a stack object to hold the value...
497 AllocaInst *AI = 0;
498
499 if (I.getType() != Type::VoidTy) {
500 AI = new AllocaInst(I.getType(), 0, I.getName(),
501 I.getParent()->getParent()->getEntryBlock().begin());
502 CurAST->add(AI);
503 }
504
505 // Secondly, insert load instructions for each use of the instruction
506 // outside of the loop.
507 while (!I.use_empty()) {
508 Instruction *U = cast<Instruction>(I.use_back());
509
510 // If the user is a PHI Node, we actually have to insert load instructions
511 // in all predecessor blocks, not in the PHI block itself!
512 if (PHINode *UPN = dyn_cast<PHINode>(U)) {
513 // Only insert into each predecessor once, so that we don't have
514 // different incoming values from the same block!
515 std::map<BasicBlock*, Value*> InsertedBlocks;
516 for (unsigned i = 0, e = UPN->getNumIncomingValues(); i != e; ++i)
517 if (UPN->getIncomingValue(i) == &I) {
518 BasicBlock *Pred = UPN->getIncomingBlock(i);
519 Value *&PredVal = InsertedBlocks[Pred];
520 if (!PredVal) {
521 // Insert a new load instruction right before the terminator in
522 // the predecessor block.
523 PredVal = new LoadInst(AI, "", Pred->getTerminator());
524 CurAST->add(cast<LoadInst>(PredVal));
525 }
526
527 UPN->setIncomingValue(i, PredVal);
528 }
529
530 } else {
531 LoadInst *L = new LoadInst(AI, "", U);
532 U->replaceUsesOfWith(&I, L);
533 CurAST->add(L);
534 }
535 }
536
537 // Thirdly, insert a copy of the instruction in each exit block of the loop
538 // that is dominated by the instruction, storing the result into the memory
539 // location. Be careful not to insert the instruction into any particular
540 // basic block more than once.
541 std::set<BasicBlock*> InsertedBlocks;
542 BasicBlock *InstOrigBB = I.getParent();
543
544 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
545 BasicBlock *ExitBlock = ExitBlocks[i];
546
547 if (isExitBlockDominatedByBlockInLoop(ExitBlock, InstOrigBB)) {
548 // If we haven't already processed this exit block, do so now.
549 if (InsertedBlocks.insert(ExitBlock).second) {
550 // Insert the code after the last PHI node...
Dan Gohman514277c2008-05-23 21:05:58 +0000551 BasicBlock::iterator InsertPt = ExitBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000552
553 // If this is the first exit block processed, just move the original
554 // instruction, otherwise clone the original instruction and insert
555 // the copy.
556 Instruction *New;
557 if (InsertedBlocks.size() == 1) {
558 I.removeFromParent();
559 ExitBlock->getInstList().insert(InsertPt, &I);
560 New = &I;
561 } else {
562 New = I.clone();
563 CurAST->copyValue(&I, New);
564 if (!I.getName().empty())
565 New->setName(I.getName()+".le");
566 ExitBlock->getInstList().insert(InsertPt, New);
567 }
568
569 // Now that we have inserted the instruction, store it into the alloca
570 if (AI) new StoreInst(New, AI, InsertPt);
571 }
572 }
573 }
574
575 // If the instruction doesn't dominate any exit blocks, it must be dead.
576 if (InsertedBlocks.empty()) {
577 CurAST->deleteValue(&I);
578 I.eraseFromParent();
579 }
580
581 // Finally, promote the fine value to SSA form.
582 if (AI) {
583 std::vector<AllocaInst*> Allocas;
584 Allocas.push_back(AI);
585 PromoteMemToReg(Allocas, *DT, *DF, CurAST);
586 }
587 }
588}
589
590/// hoist - When an instruction is found to only use loop invariant operands
591/// that is safe to hoist, this instruction is called to do the dirty work.
592///
593void LICM::hoist(Instruction &I) {
594 DOUT << "LICM hoisting to " << Preheader->getName() << ": " << I;
595
596 // Remove the instruction from its current basic block... but don't delete the
597 // instruction.
598 I.removeFromParent();
599
600 // Insert the new node in Preheader, before the terminator.
601 Preheader->getInstList().insert(Preheader->getTerminator(), &I);
602
603 if (isa<LoadInst>(I)) ++NumMovedLoads;
604 else if (isa<CallInst>(I)) ++NumMovedCalls;
605 ++NumHoisted;
606 Changed = true;
607}
608
609/// isSafeToExecuteUnconditionally - Only sink or hoist an instruction if it is
610/// not a trapping instruction or if it is a trapping instruction and is
611/// guaranteed to execute.
612///
613bool LICM::isSafeToExecuteUnconditionally(Instruction &Inst) {
614 // If it is not a trapping instruction, it is always safe to hoist.
615 if (!Inst.isTrapping()) return true;
616
617 // Otherwise we have to check to make sure that the instruction dominates all
618 // of the exit blocks. If it doesn't, then there is a path out of the loop
619 // which does not execute this instruction, so we can't hoist it.
620
621 // If the instruction is in the header block for the loop (which is very
622 // common), it is always guaranteed to dominate the exit blocks. Since this
623 // is a common case, and can save some work, check it now.
624 if (Inst.getParent() == CurLoop->getHeader())
625 return true;
626
627 // It's always safe to load from a global or alloca.
628 if (isa<LoadInst>(Inst))
629 if (isa<AllocationInst>(Inst.getOperand(0)) ||
630 isa<GlobalVariable>(Inst.getOperand(0)))
631 return true;
632
633 // Get the exit blocks for the current loop.
Devang Patel02451fa2007-08-21 00:31:24 +0000634 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635 CurLoop->getExitBlocks(ExitBlocks);
636
637 // For each exit block, get the DT node and walk up the DT until the
638 // instruction's basic block is found or we exit the loop.
639 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i)
640 if (!isExitBlockDominatedByBlockInLoop(ExitBlocks[i], Inst.getParent()))
641 return false;
642
643 return true;
644}
645
646
647/// PromoteValuesInLoop - Try to promote memory values to scalars by sinking
648/// stores out of the loop and moving loads to before the loop. We do this by
649/// looping over the stores in the loop, looking for stores to Must pointers
650/// which are loop invariant. We promote these memory locations to use allocas
651/// instead. These allocas can easily be raised to register values by the
652/// PromoteMem2Reg functionality.
653///
654void LICM::PromoteValuesInLoop() {
655 // PromotedValues - List of values that are promoted out of the loop. Each
656 // value has an alloca instruction for it, and a canonical version of the
657 // pointer.
658 std::vector<std::pair<AllocaInst*, Value*> > PromotedValues;
659 std::map<Value*, AllocaInst*> ValueToAllocaMap; // Map of ptr to alloca
660
661 FindPromotableValuesInLoop(PromotedValues, ValueToAllocaMap);
662 if (ValueToAllocaMap.empty()) return; // If there are values to promote.
663
664 Changed = true;
665 NumPromoted += PromotedValues.size();
666
667 std::vector<Value*> PointerValueNumbers;
668
669 // Emit a copy from the value into the alloca'd value in the loop preheader
670 TerminatorInst *LoopPredInst = Preheader->getTerminator();
671 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
672 Value *Ptr = PromotedValues[i].second;
673
674 // If we are promoting a pointer value, update alias information for the
675 // inserted load.
676 Value *LoadValue = 0;
677 if (isa<PointerType>(cast<PointerType>(Ptr->getType())->getElementType())) {
678 // Locate a load or store through the pointer, and assign the same value
679 // to LI as we are loading or storing. Since we know that the value is
680 // stored in this loop, this will always succeed.
681 for (Value::use_iterator UI = Ptr->use_begin(), E = Ptr->use_end();
682 UI != E; ++UI)
683 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
684 LoadValue = LI;
685 break;
686 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
687 if (SI->getOperand(1) == Ptr) {
688 LoadValue = SI->getOperand(0);
689 break;
690 }
691 }
692 assert(LoadValue && "No store through the pointer found!");
693 PointerValueNumbers.push_back(LoadValue); // Remember this for later.
694 }
695
696 // Load from the memory we are promoting.
697 LoadInst *LI = new LoadInst(Ptr, Ptr->getName()+".promoted", LoopPredInst);
698
699 if (LoadValue) CurAST->copyValue(LoadValue, LI);
700
701 // Store into the temporary alloca.
702 new StoreInst(LI, PromotedValues[i].first, LoopPredInst);
703 }
704
705 // Scan the basic blocks in the loop, replacing uses of our pointers with
706 // uses of the allocas in question.
707 //
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000708 for (Loop::block_iterator I = CurLoop->block_begin(),
709 E = CurLoop->block_end(); I != E; ++I) {
710 BasicBlock *BB = *I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711 // Rewrite all loads and stores in the block of the pointer...
Dan Gohman4d2e8ae2008-06-22 20:18:58 +0000712 for (BasicBlock::iterator II = BB->begin(), E = BB->end(); II != E; ++II) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 if (LoadInst *L = dyn_cast<LoadInst>(II)) {
714 std::map<Value*, AllocaInst*>::iterator
715 I = ValueToAllocaMap.find(L->getOperand(0));
716 if (I != ValueToAllocaMap.end())
717 L->setOperand(0, I->second); // Rewrite load instruction...
718 } else if (StoreInst *S = dyn_cast<StoreInst>(II)) {
719 std::map<Value*, AllocaInst*>::iterator
720 I = ValueToAllocaMap.find(S->getOperand(1));
721 if (I != ValueToAllocaMap.end())
722 S->setOperand(1, I->second); // Rewrite store instruction...
723 }
724 }
725 }
726
727 // Now that the body of the loop uses the allocas instead of the original
728 // memory locations, insert code to copy the alloca value back into the
729 // original memory location on all exits from the loop. Note that we only
730 // want to insert one copy of the code in each exit block, though the loop may
731 // exit to the same block more than once.
732 //
Chris Lattnera5f1b672008-05-22 03:22:42 +0000733 SmallPtrSet<BasicBlock*, 16> ProcessedBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734
Devang Patel02451fa2007-08-21 00:31:24 +0000735 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000736 CurLoop->getExitBlocks(ExitBlocks);
Chris Lattnera5f1b672008-05-22 03:22:42 +0000737 for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
738 if (!ProcessedBlocks.insert(ExitBlocks[i]))
739 continue;
740
741 // Copy all of the allocas into their memory locations.
Dan Gohman514277c2008-05-23 21:05:58 +0000742 BasicBlock::iterator BI = ExitBlocks[i]->getFirstNonPHI();
Chris Lattnera5f1b672008-05-22 03:22:42 +0000743 Instruction *InsertPos = BI;
744 unsigned PVN = 0;
745 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i) {
746 // Load from the alloca.
747 LoadInst *LI = new LoadInst(PromotedValues[i].first, "", InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000748
Chris Lattnera5f1b672008-05-22 03:22:42 +0000749 // If this is a pointer type, update alias info appropriately.
750 if (isa<PointerType>(LI->getType()))
751 CurAST->copyValue(PointerValueNumbers[PVN++], LI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000752
Chris Lattnera5f1b672008-05-22 03:22:42 +0000753 // Store into the memory we promoted.
754 new StoreInst(LI, PromotedValues[i].second, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 }
Chris Lattnera5f1b672008-05-22 03:22:42 +0000756 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000757
758 // Now that we have done the deed, use the mem2reg functionality to promote
759 // all of the new allocas we just created into real SSA registers.
760 //
761 std::vector<AllocaInst*> PromotedAllocas;
762 PromotedAllocas.reserve(PromotedValues.size());
763 for (unsigned i = 0, e = PromotedValues.size(); i != e; ++i)
764 PromotedAllocas.push_back(PromotedValues[i].first);
765 PromoteMemToReg(PromotedAllocas, *DT, *DF, CurAST);
766}
767
768/// FindPromotableValuesInLoop - Check the current loop for stores to definite
Devang Patelf8209df2007-09-19 20:18:51 +0000769/// pointers, which are not loaded and stored through may aliases and are safe
770/// for promotion. If these are found, create an alloca for the value, add it
771/// to the PromotedValues list, and keep track of the mapping from value to
772/// alloca.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000773void LICM::FindPromotableValuesInLoop(
774 std::vector<std::pair<AllocaInst*, Value*> > &PromotedValues,
775 std::map<Value*, AllocaInst*> &ValueToAllocaMap) {
776 Instruction *FnStart = CurLoop->getHeader()->getParent()->begin()->begin();
777
Chris Lattnera5f1b672008-05-22 03:22:42 +0000778 SmallVector<BasicBlock*, 4> ExitingBlocks;
779 CurLoop->getExitingBlocks(ExitingBlocks);
Devang Patelf8209df2007-09-19 20:18:51 +0000780
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 // Loop over all of the alias sets in the tracker object.
782 for (AliasSetTracker::iterator I = CurAST->begin(), E = CurAST->end();
783 I != E; ++I) {
784 AliasSet &AS = *I;
785 // We can promote this alias set if it has a store, if it is a "Must" alias
786 // set, if the pointer is loop invariant, and if we are not eliminating any
787 // volatile loads or stores.
Chris Lattner3e9bf262008-05-22 00:53:38 +0000788 if (AS.isForwardingAliasSet() || !AS.isMod() || !AS.isMustAlias() ||
789 AS.isVolatile() || !CurLoop->isLoopInvariant(AS.begin()->first))
790 continue;
791
792 assert(!AS.empty() &&
793 "Must alias set should have at least one pointer element in it!");
794 Value *V = AS.begin()->first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795
Chris Lattner3e9bf262008-05-22 00:53:38 +0000796 // Check that all of the pointers in the alias set have the same type. We
797 // cannot (yet) promote a memory location that is loaded and stored in
798 // different sizes.
799 {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000800 bool PointerOk = true;
801 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
802 if (V->getType() != I->first->getType()) {
803 PointerOk = false;
804 break;
805 }
Chris Lattner3e9bf262008-05-22 00:53:38 +0000806 if (!PointerOk)
807 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 }
Chris Lattner3e9bf262008-05-22 00:53:38 +0000809
Chris Lattnera5f1b672008-05-22 03:22:42 +0000810 // It isn't safe to promote a load/store from the loop if the load/store is
811 // conditional. For example, turning:
812 //
813 // for () { if (c) *P += 1; }
814 //
815 // into:
816 //
817 // tmp = *P; for () { if (c) tmp +=1; } *P = tmp;
818 //
819 // is not safe, because *P may only be valid to access if 'c' is true.
820 //
821 // It is safe to promote P if all uses are direct load/stores and if at
822 // least one is guaranteed to be executed.
823 bool GuaranteedToExecute = false;
824 bool InvalidInst = false;
825 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
826 UI != UE; ++UI) {
827 // Ignore instructions not in this loop.
Chris Lattner3e9bf262008-05-22 00:53:38 +0000828 Instruction *Use = dyn_cast<Instruction>(*UI);
829 if (!Use || !CurLoop->contains(Use->getParent()))
830 continue;
Chris Lattner3e9bf262008-05-22 00:53:38 +0000831
Chris Lattnera5f1b672008-05-22 03:22:42 +0000832 if (!isa<LoadInst>(Use) && !isa<StoreInst>(Use)) {
833 InvalidInst = true;
Chris Lattner3e9bf262008-05-22 00:53:38 +0000834 break;
Chris Lattnera5f1b672008-05-22 03:22:42 +0000835 }
836
837 if (!GuaranteedToExecute)
838 GuaranteedToExecute = isSafeToExecuteUnconditionally(*Use);
Chris Lattner3e9bf262008-05-22 00:53:38 +0000839 }
840
Chris Lattnera5f1b672008-05-22 03:22:42 +0000841 // If there is an non-load/store instruction in the loop, we can't promote
842 // it. If there isn't a guaranteed-to-execute instruction, we can't
843 // promote.
844 if (InvalidInst || !GuaranteedToExecute)
Chris Lattner3e9bf262008-05-22 00:53:38 +0000845 continue;
846
847 const Type *Ty = cast<PointerType>(V->getType())->getElementType();
848 AllocaInst *AI = new AllocaInst(Ty, 0, V->getName()+".tmp", FnStart);
849 PromotedValues.push_back(std::make_pair(AI, V));
850
851 // Update the AST and alias analysis.
852 CurAST->copyValue(V, AI);
853
854 for (AliasSet::iterator I = AS.begin(), E = AS.end(); I != E; ++I)
855 ValueToAllocaMap.insert(std::make_pair(I->first, AI));
856
857 DOUT << "LICM: Promoting value: " << *V << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000858 }
859}
Devang Patel09e66c02007-07-31 08:01:41 +0000860
861/// cloneBasicBlockAnalysis - Simple Analysis hook. Clone alias set info.
862void LICM::cloneBasicBlockAnalysis(BasicBlock *From, BasicBlock *To, Loop *L) {
863 AliasSetTracker *AST = LoopToAliasMap[L];
864 if (!AST)
865 return;
866
867 AST->copyValue(From, To);
868}
869
870/// deleteAnalysisValue - Simple Analysis hook. Delete value V from alias
871/// set.
872void LICM::deleteAnalysisValue(Value *V, Loop *L) {
873 AliasSetTracker *AST = LoopToAliasMap[L];
874 if (!AST)
875 return;
876
877 AST->deleteValue(V);
878}