Taken into account Duncan's comments for r149481 dated by 2nd Feb 2012:
[oota-llvm.git] / lib / Transforms / Scalar / CodeGenPrepare.cpp
1 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
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 munges the code in the input function to better prepare it for
11 // SelectionDAG-based code generation. This works around limitations in it's
12 // basic-block-at-a-time approach. It should eventually be removed.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "codegenprepare"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Function.h"
21 #include "llvm/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/InstructionSimplify.h"
27 #include "llvm/Analysis/ProfileInfo.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLibraryInfo.h"
30 #include "llvm/Target/TargetLowering.h"
31 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
32 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
33 #include "llvm/Transforms/Utils/Local.h"
34 #include "llvm/Transforms/Utils/BuildLibCalls.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/SmallSet.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/Assembly/Writer.h"
39 #include "llvm/Support/CallSite.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Debug.h"
42 #include "llvm/Support/GetElementPtrTypeIterator.h"
43 #include "llvm/Support/PatternMatch.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/IRBuilder.h"
46 #include "llvm/Support/ValueHandle.h"
47 using namespace llvm;
48 using namespace llvm::PatternMatch;
49
50 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
51 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
52 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
53 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
54                       "sunken Cmps");
55 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
56                        "of sunken Casts");
57 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
58                           "computations were sunk");
59 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
60 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
61 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
62 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
63
64 static cl::opt<bool> DisableBranchOpts(
65   "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
66   cl::desc("Disable branch optimizations in CodeGenPrepare"));
67
68 // FIXME: Remove this abomination once all of the tests pass without it!
69 static cl::opt<bool> DisableDeleteDeadBlocks(
70   "disable-cgp-delete-dead-blocks", cl::Hidden, cl::init(false),
71   cl::desc("Disable deleting dead blocks in CodeGenPrepare"));
72
73 namespace {
74   class CodeGenPrepare : public FunctionPass {
75     /// TLI - Keep a pointer of a TargetLowering to consult for determining
76     /// transformation profitability.
77     const TargetLowering *TLI;
78     const TargetLibraryInfo *TLInfo;
79     DominatorTree *DT;
80     ProfileInfo *PFI;
81     
82     /// CurInstIterator - As we scan instructions optimizing them, this is the
83     /// next instruction to optimize.  Xforms that can invalidate this should
84     /// update it.
85     BasicBlock::iterator CurInstIterator;
86
87     /// Keeps track of non-local addresses that have been sunk into a block.
88     /// This allows us to avoid inserting duplicate code for blocks with
89     /// multiple load/stores of the same address.
90     DenseMap<Value*, Value*> SunkAddrs;
91
92     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
93     /// be updated.
94     bool ModifiedDT;
95
96   public:
97     static char ID; // Pass identification, replacement for typeid
98     explicit CodeGenPrepare(const TargetLowering *tli = 0)
99       : FunctionPass(ID), TLI(tli) {
100         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
101       }
102     bool runOnFunction(Function &F);
103
104     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
105       AU.addPreserved<DominatorTree>();
106       AU.addPreserved<ProfileInfo>();
107       AU.addRequired<TargetLibraryInfo>();
108     }
109
110   private:
111     bool EliminateMostlyEmptyBlocks(Function &F);
112     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
113     void EliminateMostlyEmptyBlock(BasicBlock *BB);
114     bool OptimizeBlock(BasicBlock &BB);
115     bool OptimizeInst(Instruction *I);
116     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
117     bool OptimizeInlineAsmInst(CallInst *CS);
118     bool OptimizeCallInst(CallInst *CI);
119     bool MoveExtToFormExtLoad(Instruction *I);
120     bool OptimizeExtUses(Instruction *I);
121     bool DupRetToEnableTailCallOpts(ReturnInst *RI);
122     bool PlaceDbgValues(Function &F);
123   };
124 }
125
126 char CodeGenPrepare::ID = 0;
127 INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
128                 "Optimize for code generation", false, false)
129 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
130 INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
131                 "Optimize for code generation", false, false)
132
133 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
134   return new CodeGenPrepare(TLI);
135 }
136
137 bool CodeGenPrepare::runOnFunction(Function &F) {
138   bool EverMadeChange = false;
139
140   ModifiedDT = false;
141   TLInfo = &getAnalysis<TargetLibraryInfo>();
142   DT = getAnalysisIfAvailable<DominatorTree>();
143   PFI = getAnalysisIfAvailable<ProfileInfo>();
144
145   // First pass, eliminate blocks that contain only PHI nodes and an
146   // unconditional branch.
147   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
148
149   // llvm.dbg.value is far away from the value then iSel may not be able
150   // handle it properly. iSel will drop llvm.dbg.value if it can not 
151   // find a node corresponding to the value.
152   EverMadeChange |= PlaceDbgValues(F);
153
154   bool MadeChange = true;
155   while (MadeChange) {
156     MadeChange = false;
157     for (Function::iterator I = F.begin(), E = F.end(); I != E; ) {
158       BasicBlock *BB = I++;
159       MadeChange |= OptimizeBlock(*BB);
160     }
161     EverMadeChange |= MadeChange;
162   }
163
164   SunkAddrs.clear();
165
166   if (!DisableBranchOpts) {
167     MadeChange = false;
168     SmallPtrSet<BasicBlock*, 8> WorkList;
169     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
170       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
171       MadeChange |= ConstantFoldTerminator(BB, true);
172       if (!MadeChange) continue;
173
174       for (SmallVectorImpl<BasicBlock*>::iterator
175              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
176         if (pred_begin(*II) == pred_end(*II))
177           WorkList.insert(*II);
178     }
179
180     if (!DisableDeleteDeadBlocks)
181       for (SmallPtrSet<BasicBlock*, 8>::iterator
182              I = WorkList.begin(), E = WorkList.end(); I != E; ++I)
183         DeleteDeadBlock(*I);
184
185     if (MadeChange)
186       ModifiedDT = true;
187     EverMadeChange |= MadeChange;
188   }
189
190   if (ModifiedDT && DT)
191     DT->DT->recalculate(F);
192
193   return EverMadeChange;
194 }
195
196 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
197 /// debug info directives, and an unconditional branch.  Passes before isel
198 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
199 /// isel.  Start by eliminating these blocks so we can split them the way we
200 /// want them.
201 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
202   bool MadeChange = false;
203   // Note that this intentionally skips the entry block.
204   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
205     BasicBlock *BB = I++;
206
207     // If this block doesn't end with an uncond branch, ignore it.
208     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
209     if (!BI || !BI->isUnconditional())
210       continue;
211
212     // If the instruction before the branch (skipping debug info) isn't a phi
213     // node, then other stuff is happening here.
214     BasicBlock::iterator BBI = BI;
215     if (BBI != BB->begin()) {
216       --BBI;
217       while (isa<DbgInfoIntrinsic>(BBI)) {
218         if (BBI == BB->begin())
219           break;
220         --BBI;
221       }
222       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
223         continue;
224     }
225
226     // Do not break infinite loops.
227     BasicBlock *DestBB = BI->getSuccessor(0);
228     if (DestBB == BB)
229       continue;
230
231     if (!CanMergeBlocks(BB, DestBB))
232       continue;
233
234     EliminateMostlyEmptyBlock(BB);
235     MadeChange = true;
236   }
237   return MadeChange;
238 }
239
240 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
241 /// single uncond branch between them, and BB contains no other non-phi
242 /// instructions.
243 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
244                                     const BasicBlock *DestBB) const {
245   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
246   // the successor.  If there are more complex condition (e.g. preheaders),
247   // don't mess around with them.
248   BasicBlock::const_iterator BBI = BB->begin();
249   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
250     for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
251          UI != E; ++UI) {
252       const Instruction *User = cast<Instruction>(*UI);
253       if (User->getParent() != DestBB || !isa<PHINode>(User))
254         return false;
255       // If User is inside DestBB block and it is a PHINode then check
256       // incoming value. If incoming value is not from BB then this is
257       // a complex condition (e.g. preheaders) we want to avoid here.
258       if (User->getParent() == DestBB) {
259         if (const PHINode *UPN = dyn_cast<PHINode>(User))
260           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
261             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
262             if (Insn && Insn->getParent() == BB &&
263                 Insn->getParent() != UPN->getIncomingBlock(I))
264               return false;
265           }
266       }
267     }
268   }
269
270   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
271   // and DestBB may have conflicting incoming values for the block.  If so, we
272   // can't merge the block.
273   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
274   if (!DestBBPN) return true;  // no conflict.
275
276   // Collect the preds of BB.
277   SmallPtrSet<const BasicBlock*, 16> BBPreds;
278   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
279     // It is faster to get preds from a PHI than with pred_iterator.
280     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
281       BBPreds.insert(BBPN->getIncomingBlock(i));
282   } else {
283     BBPreds.insert(pred_begin(BB), pred_end(BB));
284   }
285
286   // Walk the preds of DestBB.
287   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
288     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
289     if (BBPreds.count(Pred)) {   // Common predecessor?
290       BBI = DestBB->begin();
291       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
292         const Value *V1 = PN->getIncomingValueForBlock(Pred);
293         const Value *V2 = PN->getIncomingValueForBlock(BB);
294
295         // If V2 is a phi node in BB, look up what the mapped value will be.
296         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
297           if (V2PN->getParent() == BB)
298             V2 = V2PN->getIncomingValueForBlock(Pred);
299
300         // If there is a conflict, bail out.
301         if (V1 != V2) return false;
302       }
303     }
304   }
305
306   return true;
307 }
308
309
310 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
311 /// an unconditional branch in it.
312 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
313   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
314   BasicBlock *DestBB = BI->getSuccessor(0);
315
316   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
317
318   // If the destination block has a single pred, then this is a trivial edge,
319   // just collapse it.
320   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
321     if (SinglePred != DestBB) {
322       // Remember if SinglePred was the entry block of the function.  If so, we
323       // will need to move BB back to the entry position.
324       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
325       MergeBasicBlockIntoOnlyPred(DestBB, this);
326
327       if (isEntry && BB != &BB->getParent()->getEntryBlock())
328         BB->moveBefore(&BB->getParent()->getEntryBlock());
329       
330       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
331       return;
332     }
333   }
334
335   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
336   // to handle the new incoming edges it is about to have.
337   PHINode *PN;
338   for (BasicBlock::iterator BBI = DestBB->begin();
339        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
340     // Remove the incoming value for BB, and remember it.
341     Value *InVal = PN->removeIncomingValue(BB, false);
342
343     // Two options: either the InVal is a phi node defined in BB or it is some
344     // value that dominates BB.
345     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
346     if (InValPhi && InValPhi->getParent() == BB) {
347       // Add all of the input values of the input PHI as inputs of this phi.
348       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
349         PN->addIncoming(InValPhi->getIncomingValue(i),
350                         InValPhi->getIncomingBlock(i));
351     } else {
352       // Otherwise, add one instance of the dominating value for each edge that
353       // we will be adding.
354       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
355         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
356           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
357       } else {
358         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
359           PN->addIncoming(InVal, *PI);
360       }
361     }
362   }
363
364   // The PHIs are now updated, change everything that refers to BB to use
365   // DestBB and remove BB.
366   BB->replaceAllUsesWith(DestBB);
367   if (DT && !ModifiedDT) {
368     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
369     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
370     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
371     DT->changeImmediateDominator(DestBB, NewIDom);
372     DT->eraseNode(BB);
373   }
374   if (PFI) {
375     PFI->replaceAllUses(BB, DestBB);
376     PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
377   }
378   BB->eraseFromParent();
379   ++NumBlocksElim;
380
381   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
382 }
383
384 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
385 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
386 /// sink it into user blocks to reduce the number of virtual
387 /// registers that must be created and coalesced.
388 ///
389 /// Return true if any changes are made.
390 ///
391 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
392   // If this is a noop copy,
393   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
394   EVT DstVT = TLI.getValueType(CI->getType());
395
396   // This is an fp<->int conversion?
397   if (SrcVT.isInteger() != DstVT.isInteger())
398     return false;
399
400   // If this is an extension, it will be a zero or sign extension, which
401   // isn't a noop.
402   if (SrcVT.bitsLT(DstVT)) return false;
403
404   // If these values will be promoted, find out what they will be promoted
405   // to.  This helps us consider truncates on PPC as noop copies when they
406   // are.
407   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
408       TargetLowering::TypePromoteInteger)
409     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
410   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
411       TargetLowering::TypePromoteInteger)
412     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
413
414   // If, after promotion, these are the same types, this is a noop copy.
415   if (SrcVT != DstVT)
416     return false;
417
418   BasicBlock *DefBB = CI->getParent();
419
420   /// InsertedCasts - Only insert a cast in each block once.
421   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
422
423   bool MadeChange = false;
424   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
425        UI != E; ) {
426     Use &TheUse = UI.getUse();
427     Instruction *User = cast<Instruction>(*UI);
428
429     // Figure out which BB this cast is used in.  For PHI's this is the
430     // appropriate predecessor block.
431     BasicBlock *UserBB = User->getParent();
432     if (PHINode *PN = dyn_cast<PHINode>(User)) {
433       UserBB = PN->getIncomingBlock(UI);
434     }
435
436     // Preincrement use iterator so we don't invalidate it.
437     ++UI;
438
439     // If this user is in the same block as the cast, don't change the cast.
440     if (UserBB == DefBB) continue;
441
442     // If we have already inserted a cast into this block, use it.
443     CastInst *&InsertedCast = InsertedCasts[UserBB];
444
445     if (!InsertedCast) {
446       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
447       InsertedCast =
448         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
449                          InsertPt);
450       MadeChange = true;
451     }
452
453     // Replace a use of the cast with a use of the new cast.
454     TheUse = InsertedCast;
455     ++NumCastUses;
456   }
457
458   // If we removed all uses, nuke the cast.
459   if (CI->use_empty()) {
460     CI->eraseFromParent();
461     MadeChange = true;
462   }
463
464   return MadeChange;
465 }
466
467 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
468 /// the number of virtual registers that must be created and coalesced.  This is
469 /// a clear win except on targets with multiple condition code registers
470 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
471 ///
472 /// Return true if any changes are made.
473 static bool OptimizeCmpExpression(CmpInst *CI) {
474   BasicBlock *DefBB = CI->getParent();
475
476   /// InsertedCmp - Only insert a cmp in each block once.
477   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
478
479   bool MadeChange = false;
480   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
481        UI != E; ) {
482     Use &TheUse = UI.getUse();
483     Instruction *User = cast<Instruction>(*UI);
484
485     // Preincrement use iterator so we don't invalidate it.
486     ++UI;
487
488     // Don't bother for PHI nodes.
489     if (isa<PHINode>(User))
490       continue;
491
492     // Figure out which BB this cmp is used in.
493     BasicBlock *UserBB = User->getParent();
494
495     // If this user is in the same block as the cmp, don't change the cmp.
496     if (UserBB == DefBB) continue;
497
498     // If we have already inserted a cmp into this block, use it.
499     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
500
501     if (!InsertedCmp) {
502       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
503       InsertedCmp =
504         CmpInst::Create(CI->getOpcode(),
505                         CI->getPredicate(),  CI->getOperand(0),
506                         CI->getOperand(1), "", InsertPt);
507       MadeChange = true;
508     }
509
510     // Replace a use of the cmp with a use of the new cmp.
511     TheUse = InsertedCmp;
512     ++NumCmpUses;
513   }
514
515   // If we removed all uses, nuke the cmp.
516   if (CI->use_empty())
517     CI->eraseFromParent();
518
519   return MadeChange;
520 }
521
522 namespace {
523 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
524 protected:
525   void replaceCall(Value *With) {
526     CI->replaceAllUsesWith(With);
527     CI->eraseFromParent();
528   }
529   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
530       if (ConstantInt *SizeCI =
531                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
532         return SizeCI->isAllOnesValue();
533     return false;
534   }
535 };
536 } // end anonymous namespace
537
538 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
539   BasicBlock *BB = CI->getParent();
540   
541   // Lower inline assembly if we can.
542   // If we found an inline asm expession, and if the target knows how to
543   // lower it to normal LLVM code, do so now.
544   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
545     if (TLI->ExpandInlineAsm(CI)) {
546       // Avoid invalidating the iterator.
547       CurInstIterator = BB->begin();
548       // Avoid processing instructions out of order, which could cause
549       // reuse before a value is defined.
550       SunkAddrs.clear();
551       return true;
552     }
553     // Sink address computing for memory operands into the block.
554     if (OptimizeInlineAsmInst(CI))
555       return true;
556   }
557   
558   // Lower all uses of llvm.objectsize.*
559   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
560   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
561     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
562     Type *ReturnTy = CI->getType();
563     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);    
564     
565     // Substituting this can cause recursive simplifications, which can
566     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
567     // happens.
568     WeakVH IterHandle(CurInstIterator);
569     
570     ReplaceAndSimplifyAllUses(CI, RetVal, TLI ? TLI->getTargetData() : 0,
571                               TLInfo, ModifiedDT ? 0 : DT);
572
573     // If the iterator instruction was recursively deleted, start over at the
574     // start of the block.
575     if (IterHandle != CurInstIterator) {
576       CurInstIterator = BB->begin();
577       SunkAddrs.clear();
578     }
579     return true;
580   }
581
582   // From here on out we're working with named functions.
583   if (CI->getCalledFunction() == 0) return false;
584
585   // We'll need TargetData from here on out.
586   const TargetData *TD = TLI ? TLI->getTargetData() : 0;
587   if (!TD) return false;
588   
589   // Lower all default uses of _chk calls.  This is very similar
590   // to what InstCombineCalls does, but here we are only lowering calls
591   // that have the default "don't know" as the objectsize.  Anything else
592   // should be left alone.
593   CodeGenPrepareFortifiedLibCalls Simplifier;
594   return Simplifier.fold(CI, TD);
595 }
596
597 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
598 /// instructions to the predecessor to enable tail call optimizations. The
599 /// case it is currently looking for is:
600 /// bb0:
601 ///   %tmp0 = tail call i32 @f0()
602 ///   br label %return
603 /// bb1:
604 ///   %tmp1 = tail call i32 @f1()
605 ///   br label %return
606 /// bb2:
607 ///   %tmp2 = tail call i32 @f2()
608 ///   br label %return
609 /// return:
610 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
611 ///   ret i32 %retval
612 ///
613 /// =>
614 ///
615 /// bb0:
616 ///   %tmp0 = tail call i32 @f0()
617 ///   ret i32 %tmp0
618 /// bb1:
619 ///   %tmp1 = tail call i32 @f1()
620 ///   ret i32 %tmp1
621 /// bb2:
622 ///   %tmp2 = tail call i32 @f2()
623 ///   ret i32 %tmp2
624 ///
625 bool CodeGenPrepare::DupRetToEnableTailCallOpts(ReturnInst *RI) {
626   if (!TLI)
627     return false;
628
629   Value *V = RI->getReturnValue();
630   PHINode *PN = V ? dyn_cast<PHINode>(V) : NULL;
631   if (V && !PN)
632     return false;
633
634   BasicBlock *BB = RI->getParent();
635   if (PN && PN->getParent() != BB)
636     return false;
637
638   // It's not safe to eliminate the sign / zero extension of the return value.
639   // See llvm::isInTailCallPosition().
640   const Function *F = BB->getParent();
641   Attributes CallerRetAttr = F->getAttributes().getRetAttributes();
642   if ((CallerRetAttr & Attribute::ZExt) || (CallerRetAttr & Attribute::SExt))
643     return false;
644
645   // Make sure there are no instructions between the PHI and return, or that the
646   // return is the first instruction in the block.
647   if (PN) {
648     BasicBlock::iterator BI = BB->begin();
649     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
650     if (&*BI != RI)
651       return false;
652   } else {
653     BasicBlock::iterator BI = BB->begin();
654     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
655     if (&*BI != RI)
656       return false;
657   }
658
659   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
660   /// call.
661   SmallVector<CallInst*, 4> TailCalls;
662   if (PN) {
663     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
664       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
665       // Make sure the phi value is indeed produced by the tail call.
666       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
667           TLI->mayBeEmittedAsTailCall(CI))
668         TailCalls.push_back(CI);
669     }
670   } else {
671     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
672     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
673       if (!VisitedBBs.insert(*PI))
674         continue;
675
676       BasicBlock::InstListType &InstList = (*PI)->getInstList();
677       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
678       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
679       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
680       if (RI == RE)
681         continue;
682
683       CallInst *CI = dyn_cast<CallInst>(&*RI);
684       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
685         TailCalls.push_back(CI);
686     }
687   }
688
689   bool Changed = false;
690   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
691     CallInst *CI = TailCalls[i];
692     CallSite CS(CI);
693
694     // Conservatively require the attributes of the call to match those of the
695     // return. Ignore noalias because it doesn't affect the call sequence.
696     Attributes CalleeRetAttr = CS.getAttributes().getRetAttributes();
697     if ((CalleeRetAttr ^ CallerRetAttr) & ~Attribute::NoAlias)
698       continue;
699
700     // Make sure the call instruction is followed by an unconditional branch to
701     // the return block.
702     BasicBlock *CallBB = CI->getParent();
703     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
704     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
705       continue;
706
707     // Duplicate the return into CallBB.
708     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
709     ModifiedDT = Changed = true;
710     ++NumRetsDup;
711   }
712
713   // If we eliminated all predecessors of the block, delete the block now.
714   if (Changed && pred_begin(BB) == pred_end(BB))
715     BB->eraseFromParent();
716
717   return Changed;
718 }
719
720 //===----------------------------------------------------------------------===//
721 // Memory Optimization
722 //===----------------------------------------------------------------------===//
723
724 /// IsNonLocalValue - Return true if the specified values are defined in a
725 /// different basic block than BB.
726 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
727   if (Instruction *I = dyn_cast<Instruction>(V))
728     return I->getParent() != BB;
729   return false;
730 }
731
732 /// OptimizeMemoryInst - Load and Store Instructions often have
733 /// addressing modes that can do significant amounts of computation.  As such,
734 /// instruction selection will try to get the load or store to do as much
735 /// computation as possible for the program.  The problem is that isel can only
736 /// see within a single block.  As such, we sink as much legal addressing mode
737 /// stuff into the block as possible.
738 ///
739 /// This method is used to optimize both load/store and inline asms with memory
740 /// operands.
741 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
742                                         Type *AccessTy) {
743   Value *Repl = Addr;
744   
745   // Try to collapse single-value PHI nodes.  This is necessary to undo 
746   // unprofitable PRE transformations.
747   SmallVector<Value*, 8> worklist;
748   SmallPtrSet<Value*, 16> Visited;
749   worklist.push_back(Addr);
750   
751   // Use a worklist to iteratively look through PHI nodes, and ensure that
752   // the addressing mode obtained from the non-PHI roots of the graph
753   // are equivalent.
754   Value *Consensus = 0;
755   unsigned NumUsesConsensus = 0;
756   bool IsNumUsesConsensusValid = false;
757   SmallVector<Instruction*, 16> AddrModeInsts;
758   ExtAddrMode AddrMode;
759   while (!worklist.empty()) {
760     Value *V = worklist.back();
761     worklist.pop_back();
762     
763     // Break use-def graph loops.
764     if (!Visited.insert(V)) {
765       Consensus = 0;
766       break;
767     }
768     
769     // For a PHI node, push all of its incoming values.
770     if (PHINode *P = dyn_cast<PHINode>(V)) {
771       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
772         worklist.push_back(P->getIncomingValue(i));
773       continue;
774     }
775     
776     // For non-PHIs, determine the addressing mode being computed.
777     SmallVector<Instruction*, 16> NewAddrModeInsts;
778     ExtAddrMode NewAddrMode =
779       AddressingModeMatcher::Match(V, AccessTy, MemoryInst,
780                                    NewAddrModeInsts, *TLI);
781
782     // This check is broken into two cases with very similar code to avoid using
783     // getNumUses() as much as possible. Some values have a lot of uses, so
784     // calling getNumUses() unconditionally caused a significant compile-time
785     // regression.
786     if (!Consensus) {
787       Consensus = V;
788       AddrMode = NewAddrMode;
789       AddrModeInsts = NewAddrModeInsts;
790       continue;
791     } else if (NewAddrMode == AddrMode) {
792       if (!IsNumUsesConsensusValid) {
793         NumUsesConsensus = Consensus->getNumUses();
794         IsNumUsesConsensusValid = true;
795       }
796
797       // Ensure that the obtained addressing mode is equivalent to that obtained
798       // for all other roots of the PHI traversal.  Also, when choosing one
799       // such root as representative, select the one with the most uses in order
800       // to keep the cost modeling heuristics in AddressingModeMatcher
801       // applicable.
802       unsigned NumUses = V->getNumUses();
803       if (NumUses > NumUsesConsensus) {
804         Consensus = V;
805         NumUsesConsensus = NumUses;
806         AddrModeInsts = NewAddrModeInsts;
807       }
808       continue;
809     }
810     
811     Consensus = 0;
812     break;
813   }
814   
815   // If the addressing mode couldn't be determined, or if multiple different
816   // ones were determined, bail out now.
817   if (!Consensus) return false;
818   
819   // Check to see if any of the instructions supersumed by this addr mode are
820   // non-local to I's BB.
821   bool AnyNonLocal = false;
822   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
823     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
824       AnyNonLocal = true;
825       break;
826     }
827   }
828
829   // If all the instructions matched are already in this BB, don't do anything.
830   if (!AnyNonLocal) {
831     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
832     return false;
833   }
834
835   // Insert this computation right after this user.  Since our caller is
836   // scanning from the top of the BB to the bottom, reuse of the expr are
837   // guaranteed to happen later.
838   IRBuilder<> Builder(MemoryInst);
839
840   // Now that we determined the addressing expression we want to use and know
841   // that we have to sink it into this block.  Check to see if we have already
842   // done this for some other load/store instr in this block.  If so, reuse the
843   // computation.
844   Value *&SunkAddr = SunkAddrs[Addr];
845   if (SunkAddr) {
846     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
847                  << *MemoryInst);
848     if (SunkAddr->getType() != Addr->getType())
849       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
850   } else {
851     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
852                  << *MemoryInst);
853     Type *IntPtrTy =
854           TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
855
856     Value *Result = 0;
857
858     // Start with the base register. Do this first so that subsequent address
859     // matching finds it last, which will prevent it from trying to match it
860     // as the scaled value in case it happens to be a mul. That would be
861     // problematic if we've sunk a different mul for the scale, because then
862     // we'd end up sinking both muls.
863     if (AddrMode.BaseReg) {
864       Value *V = AddrMode.BaseReg;
865       if (V->getType()->isPointerTy())
866         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
867       if (V->getType() != IntPtrTy)
868         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
869       Result = V;
870     }
871
872     // Add the scale value.
873     if (AddrMode.Scale) {
874       Value *V = AddrMode.ScaledReg;
875       if (V->getType() == IntPtrTy) {
876         // done.
877       } else if (V->getType()->isPointerTy()) {
878         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
879       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
880                  cast<IntegerType>(V->getType())->getBitWidth()) {
881         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
882       } else {
883         V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
884       }
885       if (AddrMode.Scale != 1)
886         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
887                               "sunkaddr");
888       if (Result)
889         Result = Builder.CreateAdd(Result, V, "sunkaddr");
890       else
891         Result = V;
892     }
893
894     // Add in the BaseGV if present.
895     if (AddrMode.BaseGV) {
896       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
897       if (Result)
898         Result = Builder.CreateAdd(Result, V, "sunkaddr");
899       else
900         Result = V;
901     }
902
903     // Add in the Base Offset if present.
904     if (AddrMode.BaseOffs) {
905       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
906       if (Result)
907         Result = Builder.CreateAdd(Result, V, "sunkaddr");
908       else
909         Result = V;
910     }
911
912     if (Result == 0)
913       SunkAddr = Constant::getNullValue(Addr->getType());
914     else
915       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
916   }
917
918   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
919
920   // If we have no uses, recursively delete the value and all dead instructions
921   // using it.
922   if (Repl->use_empty()) {
923     // This can cause recursive deletion, which can invalidate our iterator.
924     // Use a WeakVH to hold onto it in case this happens.
925     WeakVH IterHandle(CurInstIterator);
926     BasicBlock *BB = CurInstIterator->getParent();
927     
928     RecursivelyDeleteTriviallyDeadInstructions(Repl);
929
930     if (IterHandle != CurInstIterator) {
931       // If the iterator instruction was recursively deleted, start over at the
932       // start of the block.
933       CurInstIterator = BB->begin();
934       SunkAddrs.clear();
935     } else {
936       // This address is now available for reassignment, so erase the table
937       // entry; we don't want to match some completely different instruction.
938       SunkAddrs[Addr] = 0;
939     }    
940   }
941   ++NumMemoryInsts;
942   return true;
943 }
944
945 /// OptimizeInlineAsmInst - If there are any memory operands, use
946 /// OptimizeMemoryInst to sink their address computing into the block when
947 /// possible / profitable.
948 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
949   bool MadeChange = false;
950
951   TargetLowering::AsmOperandInfoVector 
952     TargetConstraints = TLI->ParseConstraints(CS);
953   unsigned ArgNo = 0;
954   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
955     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
956     
957     // Compute the constraint code and ConstraintType to use.
958     TLI->ComputeConstraintToUse(OpInfo, SDValue());
959
960     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
961         OpInfo.isIndirect) {
962       Value *OpVal = CS->getArgOperand(ArgNo++);
963       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
964     } else if (OpInfo.Type == InlineAsm::isInput)
965       ArgNo++;
966   }
967
968   return MadeChange;
969 }
970
971 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
972 /// basic block as the load, unless conditions are unfavorable. This allows
973 /// SelectionDAG to fold the extend into the load.
974 ///
975 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
976   // Look for a load being extended.
977   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
978   if (!LI) return false;
979
980   // If they're already in the same block, there's nothing to do.
981   if (LI->getParent() == I->getParent())
982     return false;
983
984   // If the load has other users and the truncate is not free, this probably
985   // isn't worthwhile.
986   if (!LI->hasOneUse() &&
987       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
988               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
989       !TLI->isTruncateFree(I->getType(), LI->getType()))
990     return false;
991
992   // Check whether the target supports casts folded into loads.
993   unsigned LType;
994   if (isa<ZExtInst>(I))
995     LType = ISD::ZEXTLOAD;
996   else {
997     assert(isa<SExtInst>(I) && "Unexpected ext type!");
998     LType = ISD::SEXTLOAD;
999   }
1000   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
1001     return false;
1002
1003   // Move the extend into the same block as the load, so that SelectionDAG
1004   // can fold it.
1005   I->removeFromParent();
1006   I->insertAfter(LI);
1007   ++NumExtsMoved;
1008   return true;
1009 }
1010
1011 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1012   BasicBlock *DefBB = I->getParent();
1013
1014   // If the result of a {s|z}ext and its source are both live out, rewrite all
1015   // other uses of the source with result of extension.
1016   Value *Src = I->getOperand(0);
1017   if (Src->hasOneUse())
1018     return false;
1019
1020   // Only do this xform if truncating is free.
1021   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1022     return false;
1023
1024   // Only safe to perform the optimization if the source is also defined in
1025   // this block.
1026   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1027     return false;
1028
1029   bool DefIsLiveOut = false;
1030   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1031        UI != E; ++UI) {
1032     Instruction *User = cast<Instruction>(*UI);
1033
1034     // Figure out which BB this ext is used in.
1035     BasicBlock *UserBB = User->getParent();
1036     if (UserBB == DefBB) continue;
1037     DefIsLiveOut = true;
1038     break;
1039   }
1040   if (!DefIsLiveOut)
1041     return false;
1042
1043   // Make sure non of the uses are PHI nodes.
1044   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1045        UI != E; ++UI) {
1046     Instruction *User = cast<Instruction>(*UI);
1047     BasicBlock *UserBB = User->getParent();
1048     if (UserBB == DefBB) continue;
1049     // Be conservative. We don't want this xform to end up introducing
1050     // reloads just before load / store instructions.
1051     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1052       return false;
1053   }
1054
1055   // InsertedTruncs - Only insert one trunc in each block once.
1056   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1057
1058   bool MadeChange = false;
1059   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1060        UI != E; ++UI) {
1061     Use &TheUse = UI.getUse();
1062     Instruction *User = cast<Instruction>(*UI);
1063
1064     // Figure out which BB this ext is used in.
1065     BasicBlock *UserBB = User->getParent();
1066     if (UserBB == DefBB) continue;
1067
1068     // Both src and def are live in this block. Rewrite the use.
1069     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1070
1071     if (!InsertedTrunc) {
1072       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
1073       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1074     }
1075
1076     // Replace a use of the {s|z}ext source with a use of the result.
1077     TheUse = InsertedTrunc;
1078     ++NumExtUses;
1079     MadeChange = true;
1080   }
1081
1082   return MadeChange;
1083 }
1084
1085 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
1086   if (PHINode *P = dyn_cast<PHINode>(I)) {
1087     // It is possible for very late stage optimizations (such as SimplifyCFG)
1088     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
1089     // trivial PHI, go ahead and zap it here.
1090     if (Value *V = SimplifyInstruction(P)) {
1091       P->replaceAllUsesWith(V);
1092       P->eraseFromParent();
1093       ++NumPHIsElim;
1094       return true;
1095     }
1096     return false;
1097   }
1098   
1099   if (CastInst *CI = dyn_cast<CastInst>(I)) {
1100     // If the source of the cast is a constant, then this should have
1101     // already been constant folded.  The only reason NOT to constant fold
1102     // it is if something (e.g. LSR) was careful to place the constant
1103     // evaluation in a block other than then one that uses it (e.g. to hoist
1104     // the address of globals out of a loop).  If this is the case, we don't
1105     // want to forward-subst the cast.
1106     if (isa<Constant>(CI->getOperand(0)))
1107       return false;
1108
1109     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
1110       return true;
1111
1112     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
1113       bool MadeChange = MoveExtToFormExtLoad(I);
1114       return MadeChange | OptimizeExtUses(I);
1115     }
1116     return false;
1117   }
1118   
1119   if (CmpInst *CI = dyn_cast<CmpInst>(I))
1120     return OptimizeCmpExpression(CI);
1121   
1122   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1123     if (TLI)
1124       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
1125     return false;
1126   }
1127   
1128   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1129     if (TLI)
1130       return OptimizeMemoryInst(I, SI->getOperand(1),
1131                                 SI->getOperand(0)->getType());
1132     return false;
1133   }
1134   
1135   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1136     if (GEPI->hasAllZeroIndices()) {
1137       /// The GEP operand must be a pointer, so must its result -> BitCast
1138       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1139                                         GEPI->getName(), GEPI);
1140       GEPI->replaceAllUsesWith(NC);
1141       GEPI->eraseFromParent();
1142       ++NumGEPsElim;
1143       OptimizeInst(NC);
1144       return true;
1145     }
1146     return false;
1147   }
1148   
1149   if (CallInst *CI = dyn_cast<CallInst>(I))
1150     return OptimizeCallInst(CI);
1151
1152   if (ReturnInst *RI = dyn_cast<ReturnInst>(I))
1153     return DupRetToEnableTailCallOpts(RI);
1154
1155   return false;
1156 }
1157
1158 // In this pass we look for GEP and cast instructions that are used
1159 // across basic blocks and rewrite them to improve basic-block-at-a-time
1160 // selection.
1161 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1162   SunkAddrs.clear();
1163   bool MadeChange = false;
1164
1165   CurInstIterator = BB.begin();
1166   for (BasicBlock::iterator E = BB.end(); CurInstIterator != E; )
1167     MadeChange |= OptimizeInst(CurInstIterator++);
1168
1169   return MadeChange;
1170 }
1171
1172 // llvm.dbg.value is far away from the value then iSel may not be able
1173 // handle it properly. iSel will drop llvm.dbg.value if it can not 
1174 // find a node corresponding to the value.
1175 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
1176   bool MadeChange = false;
1177   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
1178     Instruction *PrevNonDbgInst = NULL;
1179     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
1180       Instruction *Insn = BI; ++BI;
1181       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
1182       if (!DVI) {
1183         PrevNonDbgInst = Insn;
1184         continue;
1185       }
1186
1187       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
1188       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
1189         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
1190         DVI->removeFromParent();
1191         if (isa<PHINode>(VI))
1192           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
1193         else
1194           DVI->insertAfter(VI);
1195         MadeChange = true;
1196         ++NumDbgValueMoved;
1197       }
1198     }
1199   }
1200   return MadeChange;
1201 }