[CodeGenPrepare] Undo changes that happened for the profitability check.
[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/ADT/DenseMap.h"
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/Statistic.h"
21 #include "llvm/ADT/ValueMap.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/IRBuilder.h"
29 #include "llvm/IR/InlineAsm.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/IntrinsicInst.h"
32 #include "llvm/Pass.h"
33 #include "llvm/Support/CallSite.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/GetElementPtrTypeIterator.h"
37 #include "llvm/Support/PatternMatch.h"
38 #include "llvm/Support/ValueHandle.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Target/TargetLibraryInfo.h"
41 #include "llvm/Target/TargetLowering.h"
42 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
43 #include "llvm/Transforms/Utils/BuildLibCalls.h"
44 #include "llvm/Transforms/Utils/BypassSlowDivision.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 using namespace llvm;
47 using namespace llvm::PatternMatch;
48
49 STATISTIC(NumBlocksElim, "Number of blocks eliminated");
50 STATISTIC(NumPHIsElim,   "Number of trivial PHIs eliminated");
51 STATISTIC(NumGEPsElim,   "Number of GEPs converted to casts");
52 STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
53                       "sunken Cmps");
54 STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
55                        "of sunken Casts");
56 STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
57                           "computations were sunk");
58 STATISTIC(NumExtsMoved,  "Number of [s|z]ext instructions combined with loads");
59 STATISTIC(NumExtUses,    "Number of uses of [s|z]ext instructions optimized");
60 STATISTIC(NumRetsDup,    "Number of return instructions duplicated");
61 STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
62 STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
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 static cl::opt<bool> DisableSelectToBranch(
69   "disable-cgp-select2branch", cl::Hidden, cl::init(false),
70   cl::desc("Disable select to branch conversion."));
71
72 namespace {
73 typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
74 typedef DenseMap<Instruction *, Type *> InstrToOrigTy;
75
76   class CodeGenPrepare : public FunctionPass {
77     /// TLI - Keep a pointer of a TargetLowering to consult for determining
78     /// transformation profitability.
79     const TargetMachine *TM;
80     const TargetLowering *TLI;
81     const TargetLibraryInfo *TLInfo;
82     DominatorTree *DT;
83
84     /// CurInstIterator - As we scan instructions optimizing them, this is the
85     /// next instruction to optimize.  Xforms that can invalidate this should
86     /// update it.
87     BasicBlock::iterator CurInstIterator;
88
89     /// Keeps track of non-local addresses that have been sunk into a block.
90     /// This allows us to avoid inserting duplicate code for blocks with
91     /// multiple load/stores of the same address.
92     ValueMap<Value*, Value*> SunkAddrs;
93
94     /// Keeps track of all truncates inserted for the current function.
95     SetOfInstrs InsertedTruncsSet;
96     /// Keeps track of the type of the related instruction before their
97     /// promotion for the current function.
98     InstrToOrigTy PromotedInsts;
99
100     /// ModifiedDT - If CFG is modified in anyway, dominator tree may need to
101     /// be updated.
102     bool ModifiedDT;
103
104     /// OptSize - True if optimizing for size.
105     bool OptSize;
106
107   public:
108     static char ID; // Pass identification, replacement for typeid
109     explicit CodeGenPrepare(const TargetMachine *TM = 0)
110       : FunctionPass(ID), TM(TM), TLI(0) {
111         initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
112       }
113     bool runOnFunction(Function &F);
114
115     const char *getPassName() const { return "CodeGen Prepare"; }
116
117     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118       AU.addPreserved<DominatorTreeWrapperPass>();
119       AU.addRequired<TargetLibraryInfo>();
120     }
121
122   private:
123     bool EliminateFallThrough(Function &F);
124     bool EliminateMostlyEmptyBlocks(Function &F);
125     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
126     void EliminateMostlyEmptyBlock(BasicBlock *BB);
127     bool OptimizeBlock(BasicBlock &BB);
128     bool OptimizeInst(Instruction *I);
129     bool OptimizeMemoryInst(Instruction *I, Value *Addr, Type *AccessTy);
130     bool OptimizeInlineAsmInst(CallInst *CS);
131     bool OptimizeCallInst(CallInst *CI);
132     bool MoveExtToFormExtLoad(Instruction *I);
133     bool OptimizeExtUses(Instruction *I);
134     bool OptimizeSelectInst(SelectInst *SI);
135     bool DupRetToEnableTailCallOpts(BasicBlock *BB);
136     bool PlaceDbgValues(Function &F);
137   };
138 }
139
140 char CodeGenPrepare::ID = 0;
141 static void *initializeCodeGenPreparePassOnce(PassRegistry &Registry) {
142   initializeTargetLibraryInfoPass(Registry);
143   PassInfo *PI = new PassInfo(
144       "Optimize for code generation", "codegenprepare", &CodeGenPrepare::ID,
145       PassInfo::NormalCtor_t(callDefaultCtor<CodeGenPrepare>), false, false,
146       PassInfo::TargetMachineCtor_t(callTargetMachineCtor<CodeGenPrepare>));
147   Registry.registerPass(*PI, true);
148   return PI;
149 }
150
151 void llvm::initializeCodeGenPreparePass(PassRegistry &Registry) {
152   CALL_ONCE_INITIALIZATION(initializeCodeGenPreparePassOnce)
153 }
154
155 FunctionPass *llvm::createCodeGenPreparePass(const TargetMachine *TM) {
156   return new CodeGenPrepare(TM);
157 }
158
159 bool CodeGenPrepare::runOnFunction(Function &F) {
160   bool EverMadeChange = false;
161   // Clear per function information.
162   InsertedTruncsSet.clear();
163   PromotedInsts.clear();
164
165   ModifiedDT = false;
166   if (TM) TLI = TM->getTargetLowering();
167   TLInfo = &getAnalysis<TargetLibraryInfo>();
168   DominatorTreeWrapperPass *DTWP =
169       getAnalysisIfAvailable<DominatorTreeWrapperPass>();
170   DT = DTWP ? &DTWP->getDomTree() : 0;
171   OptSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
172                                            Attribute::OptimizeForSize);
173
174   /// This optimization identifies DIV instructions that can be
175   /// profitably bypassed and carried out with a shorter, faster divide.
176   if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
177     const DenseMap<unsigned int, unsigned int> &BypassWidths =
178        TLI->getBypassSlowDivWidths();
179     for (Function::iterator I = F.begin(); I != F.end(); I++)
180       EverMadeChange |= bypassSlowDivision(F, I, BypassWidths);
181   }
182
183   // Eliminate blocks that contain only PHI nodes and an
184   // unconditional branch.
185   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
186
187   // llvm.dbg.value is far away from the value then iSel may not be able
188   // handle it properly. iSel will drop llvm.dbg.value if it can not
189   // find a node corresponding to the value.
190   EverMadeChange |= PlaceDbgValues(F);
191
192   bool MadeChange = true;
193   while (MadeChange) {
194     MadeChange = false;
195     for (Function::iterator I = F.begin(); I != F.end(); ) {
196       BasicBlock *BB = I++;
197       MadeChange |= OptimizeBlock(*BB);
198     }
199     EverMadeChange |= MadeChange;
200   }
201
202   SunkAddrs.clear();
203
204   if (!DisableBranchOpts) {
205     MadeChange = false;
206     SmallPtrSet<BasicBlock*, 8> WorkList;
207     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
208       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
209       MadeChange |= ConstantFoldTerminator(BB, true);
210       if (!MadeChange) continue;
211
212       for (SmallVectorImpl<BasicBlock*>::iterator
213              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
214         if (pred_begin(*II) == pred_end(*II))
215           WorkList.insert(*II);
216     }
217
218     // Delete the dead blocks and any of their dead successors.
219     MadeChange |= !WorkList.empty();
220     while (!WorkList.empty()) {
221       BasicBlock *BB = *WorkList.begin();
222       WorkList.erase(BB);
223       SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
224
225       DeleteDeadBlock(BB);
226
227       for (SmallVectorImpl<BasicBlock*>::iterator
228              II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
229         if (pred_begin(*II) == pred_end(*II))
230           WorkList.insert(*II);
231     }
232
233     // Merge pairs of basic blocks with unconditional branches, connected by
234     // a single edge.
235     if (EverMadeChange || MadeChange)
236       MadeChange |= EliminateFallThrough(F);
237
238     if (MadeChange)
239       ModifiedDT = true;
240     EverMadeChange |= MadeChange;
241   }
242
243   if (ModifiedDT && DT)
244     DT->recalculate(F);
245
246   return EverMadeChange;
247 }
248
249 /// EliminateFallThrough - Merge basic blocks which are connected
250 /// by a single edge, where one of the basic blocks has a single successor
251 /// pointing to the other basic block, which has a single predecessor.
252 bool CodeGenPrepare::EliminateFallThrough(Function &F) {
253   bool Changed = false;
254   // Scan all of the blocks in the function, except for the entry block.
255   for (Function::iterator I = llvm::next(F.begin()), E = F.end(); I != E; ) {
256     BasicBlock *BB = I++;
257     // If the destination block has a single pred, then this is a trivial
258     // edge, just collapse it.
259     BasicBlock *SinglePred = BB->getSinglePredecessor();
260
261     // Don't merge if BB's address is taken.
262     if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
263
264     BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
265     if (Term && !Term->isConditional()) {
266       Changed = true;
267       DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
268       // Remember if SinglePred was the entry block of the function.
269       // If so, we will need to move BB back to the entry position.
270       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
271       MergeBasicBlockIntoOnlyPred(BB, this);
272
273       if (isEntry && BB != &BB->getParent()->getEntryBlock())
274         BB->moveBefore(&BB->getParent()->getEntryBlock());
275
276       // We have erased a block. Update the iterator.
277       I = BB;
278     }
279   }
280   return Changed;
281 }
282
283 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
284 /// debug info directives, and an unconditional branch.  Passes before isel
285 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
286 /// isel.  Start by eliminating these blocks so we can split them the way we
287 /// want them.
288 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
289   bool MadeChange = false;
290   // Note that this intentionally skips the entry block.
291   for (Function::iterator I = llvm::next(F.begin()), E = F.end(); I != E; ) {
292     BasicBlock *BB = I++;
293
294     // If this block doesn't end with an uncond branch, ignore it.
295     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
296     if (!BI || !BI->isUnconditional())
297       continue;
298
299     // If the instruction before the branch (skipping debug info) isn't a phi
300     // node, then other stuff is happening here.
301     BasicBlock::iterator BBI = BI;
302     if (BBI != BB->begin()) {
303       --BBI;
304       while (isa<DbgInfoIntrinsic>(BBI)) {
305         if (BBI == BB->begin())
306           break;
307         --BBI;
308       }
309       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
310         continue;
311     }
312
313     // Do not break infinite loops.
314     BasicBlock *DestBB = BI->getSuccessor(0);
315     if (DestBB == BB)
316       continue;
317
318     if (!CanMergeBlocks(BB, DestBB))
319       continue;
320
321     EliminateMostlyEmptyBlock(BB);
322     MadeChange = true;
323   }
324   return MadeChange;
325 }
326
327 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
328 /// single uncond branch between them, and BB contains no other non-phi
329 /// instructions.
330 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
331                                     const BasicBlock *DestBB) const {
332   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
333   // the successor.  If there are more complex condition (e.g. preheaders),
334   // don't mess around with them.
335   BasicBlock::const_iterator BBI = BB->begin();
336   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
337     for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
338          UI != E; ++UI) {
339       const Instruction *User = cast<Instruction>(*UI);
340       if (User->getParent() != DestBB || !isa<PHINode>(User))
341         return false;
342       // If User is inside DestBB block and it is a PHINode then check
343       // incoming value. If incoming value is not from BB then this is
344       // a complex condition (e.g. preheaders) we want to avoid here.
345       if (User->getParent() == DestBB) {
346         if (const PHINode *UPN = dyn_cast<PHINode>(User))
347           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
348             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
349             if (Insn && Insn->getParent() == BB &&
350                 Insn->getParent() != UPN->getIncomingBlock(I))
351               return false;
352           }
353       }
354     }
355   }
356
357   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
358   // and DestBB may have conflicting incoming values for the block.  If so, we
359   // can't merge the block.
360   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
361   if (!DestBBPN) return true;  // no conflict.
362
363   // Collect the preds of BB.
364   SmallPtrSet<const BasicBlock*, 16> BBPreds;
365   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
366     // It is faster to get preds from a PHI than with pred_iterator.
367     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
368       BBPreds.insert(BBPN->getIncomingBlock(i));
369   } else {
370     BBPreds.insert(pred_begin(BB), pred_end(BB));
371   }
372
373   // Walk the preds of DestBB.
374   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
375     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
376     if (BBPreds.count(Pred)) {   // Common predecessor?
377       BBI = DestBB->begin();
378       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
379         const Value *V1 = PN->getIncomingValueForBlock(Pred);
380         const Value *V2 = PN->getIncomingValueForBlock(BB);
381
382         // If V2 is a phi node in BB, look up what the mapped value will be.
383         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
384           if (V2PN->getParent() == BB)
385             V2 = V2PN->getIncomingValueForBlock(Pred);
386
387         // If there is a conflict, bail out.
388         if (V1 != V2) return false;
389       }
390     }
391   }
392
393   return true;
394 }
395
396
397 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
398 /// an unconditional branch in it.
399 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
400   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
401   BasicBlock *DestBB = BI->getSuccessor(0);
402
403   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
404
405   // If the destination block has a single pred, then this is a trivial edge,
406   // just collapse it.
407   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
408     if (SinglePred != DestBB) {
409       // Remember if SinglePred was the entry block of the function.  If so, we
410       // will need to move BB back to the entry position.
411       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
412       MergeBasicBlockIntoOnlyPred(DestBB, this);
413
414       if (isEntry && BB != &BB->getParent()->getEntryBlock())
415         BB->moveBefore(&BB->getParent()->getEntryBlock());
416
417       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
418       return;
419     }
420   }
421
422   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
423   // to handle the new incoming edges it is about to have.
424   PHINode *PN;
425   for (BasicBlock::iterator BBI = DestBB->begin();
426        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
427     // Remove the incoming value for BB, and remember it.
428     Value *InVal = PN->removeIncomingValue(BB, false);
429
430     // Two options: either the InVal is a phi node defined in BB or it is some
431     // value that dominates BB.
432     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
433     if (InValPhi && InValPhi->getParent() == BB) {
434       // Add all of the input values of the input PHI as inputs of this phi.
435       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
436         PN->addIncoming(InValPhi->getIncomingValue(i),
437                         InValPhi->getIncomingBlock(i));
438     } else {
439       // Otherwise, add one instance of the dominating value for each edge that
440       // we will be adding.
441       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
442         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
443           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
444       } else {
445         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
446           PN->addIncoming(InVal, *PI);
447       }
448     }
449   }
450
451   // The PHIs are now updated, change everything that refers to BB to use
452   // DestBB and remove BB.
453   BB->replaceAllUsesWith(DestBB);
454   if (DT && !ModifiedDT) {
455     BasicBlock *BBIDom  = DT->getNode(BB)->getIDom()->getBlock();
456     BasicBlock *DestBBIDom = DT->getNode(DestBB)->getIDom()->getBlock();
457     BasicBlock *NewIDom = DT->findNearestCommonDominator(BBIDom, DestBBIDom);
458     DT->changeImmediateDominator(DestBB, NewIDom);
459     DT->eraseNode(BB);
460   }
461   BB->eraseFromParent();
462   ++NumBlocksElim;
463
464   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
465 }
466
467 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
468 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
469 /// sink it into user blocks to reduce the number of virtual
470 /// registers that must be created and coalesced.
471 ///
472 /// Return true if any changes are made.
473 ///
474 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
475   // If this is a noop copy,
476   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
477   EVT DstVT = TLI.getValueType(CI->getType());
478
479   // This is an fp<->int conversion?
480   if (SrcVT.isInteger() != DstVT.isInteger())
481     return false;
482
483   // If this is an extension, it will be a zero or sign extension, which
484   // isn't a noop.
485   if (SrcVT.bitsLT(DstVT)) return false;
486
487   // If these values will be promoted, find out what they will be promoted
488   // to.  This helps us consider truncates on PPC as noop copies when they
489   // are.
490   if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
491       TargetLowering::TypePromoteInteger)
492     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
493   if (TLI.getTypeAction(CI->getContext(), DstVT) ==
494       TargetLowering::TypePromoteInteger)
495     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
496
497   // If, after promotion, these are the same types, this is a noop copy.
498   if (SrcVT != DstVT)
499     return false;
500
501   BasicBlock *DefBB = CI->getParent();
502
503   /// InsertedCasts - Only insert a cast in each block once.
504   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
505
506   bool MadeChange = false;
507   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
508        UI != E; ) {
509     Use &TheUse = UI.getUse();
510     Instruction *User = cast<Instruction>(*UI);
511
512     // Figure out which BB this cast is used in.  For PHI's this is the
513     // appropriate predecessor block.
514     BasicBlock *UserBB = User->getParent();
515     if (PHINode *PN = dyn_cast<PHINode>(User)) {
516       UserBB = PN->getIncomingBlock(UI);
517     }
518
519     // Preincrement use iterator so we don't invalidate it.
520     ++UI;
521
522     // If this user is in the same block as the cast, don't change the cast.
523     if (UserBB == DefBB) continue;
524
525     // If we have already inserted a cast into this block, use it.
526     CastInst *&InsertedCast = InsertedCasts[UserBB];
527
528     if (!InsertedCast) {
529       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
530       InsertedCast =
531         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
532                          InsertPt);
533       MadeChange = true;
534     }
535
536     // Replace a use of the cast with a use of the new cast.
537     TheUse = InsertedCast;
538     ++NumCastUses;
539   }
540
541   // If we removed all uses, nuke the cast.
542   if (CI->use_empty()) {
543     CI->eraseFromParent();
544     MadeChange = true;
545   }
546
547   return MadeChange;
548 }
549
550 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
551 /// the number of virtual registers that must be created and coalesced.  This is
552 /// a clear win except on targets with multiple condition code registers
553 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
554 ///
555 /// Return true if any changes are made.
556 static bool OptimizeCmpExpression(CmpInst *CI) {
557   BasicBlock *DefBB = CI->getParent();
558
559   /// InsertedCmp - Only insert a cmp in each block once.
560   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
561
562   bool MadeChange = false;
563   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
564        UI != E; ) {
565     Use &TheUse = UI.getUse();
566     Instruction *User = cast<Instruction>(*UI);
567
568     // Preincrement use iterator so we don't invalidate it.
569     ++UI;
570
571     // Don't bother for PHI nodes.
572     if (isa<PHINode>(User))
573       continue;
574
575     // Figure out which BB this cmp is used in.
576     BasicBlock *UserBB = User->getParent();
577
578     // If this user is in the same block as the cmp, don't change the cmp.
579     if (UserBB == DefBB) continue;
580
581     // If we have already inserted a cmp into this block, use it.
582     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
583
584     if (!InsertedCmp) {
585       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
586       InsertedCmp =
587         CmpInst::Create(CI->getOpcode(),
588                         CI->getPredicate(),  CI->getOperand(0),
589                         CI->getOperand(1), "", InsertPt);
590       MadeChange = true;
591     }
592
593     // Replace a use of the cmp with a use of the new cmp.
594     TheUse = InsertedCmp;
595     ++NumCmpUses;
596   }
597
598   // If we removed all uses, nuke the cmp.
599   if (CI->use_empty())
600     CI->eraseFromParent();
601
602   return MadeChange;
603 }
604
605 namespace {
606 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
607 protected:
608   void replaceCall(Value *With) {
609     CI->replaceAllUsesWith(With);
610     CI->eraseFromParent();
611   }
612   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
613       if (ConstantInt *SizeCI =
614                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
615         return SizeCI->isAllOnesValue();
616     return false;
617   }
618 };
619 } // end anonymous namespace
620
621 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
622   BasicBlock *BB = CI->getParent();
623
624   // Lower inline assembly if we can.
625   // If we found an inline asm expession, and if the target knows how to
626   // lower it to normal LLVM code, do so now.
627   if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
628     if (TLI->ExpandInlineAsm(CI)) {
629       // Avoid invalidating the iterator.
630       CurInstIterator = BB->begin();
631       // Avoid processing instructions out of order, which could cause
632       // reuse before a value is defined.
633       SunkAddrs.clear();
634       return true;
635     }
636     // Sink address computing for memory operands into the block.
637     if (OptimizeInlineAsmInst(CI))
638       return true;
639   }
640
641   // Lower all uses of llvm.objectsize.*
642   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
643   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
644     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
645     Type *ReturnTy = CI->getType();
646     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
647
648     // Substituting this can cause recursive simplifications, which can
649     // invalidate our iterator.  Use a WeakVH to hold onto it in case this
650     // happens.
651     WeakVH IterHandle(CurInstIterator);
652
653     replaceAndRecursivelySimplify(CI, RetVal, TLI ? TLI->getDataLayout() : 0,
654                                   TLInfo, ModifiedDT ? 0 : DT);
655
656     // If the iterator instruction was recursively deleted, start over at the
657     // start of the block.
658     if (IterHandle != CurInstIterator) {
659       CurInstIterator = BB->begin();
660       SunkAddrs.clear();
661     }
662     return true;
663   }
664
665   if (II && TLI) {
666     SmallVector<Value*, 2> PtrOps;
667     Type *AccessTy;
668     if (TLI->GetAddrModeArguments(II, PtrOps, AccessTy))
669       while (!PtrOps.empty())
670         if (OptimizeMemoryInst(II, PtrOps.pop_back_val(), AccessTy))
671           return true;
672   }
673
674   // From here on out we're working with named functions.
675   if (CI->getCalledFunction() == 0) return false;
676
677   // We'll need DataLayout from here on out.
678   const DataLayout *TD = TLI ? TLI->getDataLayout() : 0;
679   if (!TD) return false;
680
681   // Lower all default uses of _chk calls.  This is very similar
682   // to what InstCombineCalls does, but here we are only lowering calls
683   // that have the default "don't know" as the objectsize.  Anything else
684   // should be left alone.
685   CodeGenPrepareFortifiedLibCalls Simplifier;
686   return Simplifier.fold(CI, TD, TLInfo);
687 }
688
689 /// DupRetToEnableTailCallOpts - Look for opportunities to duplicate return
690 /// instructions to the predecessor to enable tail call optimizations. The
691 /// case it is currently looking for is:
692 /// @code
693 /// bb0:
694 ///   %tmp0 = tail call i32 @f0()
695 ///   br label %return
696 /// bb1:
697 ///   %tmp1 = tail call i32 @f1()
698 ///   br label %return
699 /// bb2:
700 ///   %tmp2 = tail call i32 @f2()
701 ///   br label %return
702 /// return:
703 ///   %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
704 ///   ret i32 %retval
705 /// @endcode
706 ///
707 /// =>
708 ///
709 /// @code
710 /// bb0:
711 ///   %tmp0 = tail call i32 @f0()
712 ///   ret i32 %tmp0
713 /// bb1:
714 ///   %tmp1 = tail call i32 @f1()
715 ///   ret i32 %tmp1
716 /// bb2:
717 ///   %tmp2 = tail call i32 @f2()
718 ///   ret i32 %tmp2
719 /// @endcode
720 bool CodeGenPrepare::DupRetToEnableTailCallOpts(BasicBlock *BB) {
721   if (!TLI)
722     return false;
723
724   ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator());
725   if (!RI)
726     return false;
727
728   PHINode *PN = 0;
729   BitCastInst *BCI = 0;
730   Value *V = RI->getReturnValue();
731   if (V) {
732     BCI = dyn_cast<BitCastInst>(V);
733     if (BCI)
734       V = BCI->getOperand(0);
735
736     PN = dyn_cast<PHINode>(V);
737     if (!PN)
738       return false;
739   }
740
741   if (PN && PN->getParent() != BB)
742     return false;
743
744   // It's not safe to eliminate the sign / zero extension of the return value.
745   // See llvm::isInTailCallPosition().
746   const Function *F = BB->getParent();
747   AttributeSet CallerAttrs = F->getAttributes();
748   if (CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::ZExt) ||
749       CallerAttrs.hasAttribute(AttributeSet::ReturnIndex, Attribute::SExt))
750     return false;
751
752   // Make sure there are no instructions between the PHI and return, or that the
753   // return is the first instruction in the block.
754   if (PN) {
755     BasicBlock::iterator BI = BB->begin();
756     do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
757     if (&*BI == BCI)
758       // Also skip over the bitcast.
759       ++BI;
760     if (&*BI != RI)
761       return false;
762   } else {
763     BasicBlock::iterator BI = BB->begin();
764     while (isa<DbgInfoIntrinsic>(BI)) ++BI;
765     if (&*BI != RI)
766       return false;
767   }
768
769   /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
770   /// call.
771   SmallVector<CallInst*, 4> TailCalls;
772   if (PN) {
773     for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
774       CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
775       // Make sure the phi value is indeed produced by the tail call.
776       if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
777           TLI->mayBeEmittedAsTailCall(CI))
778         TailCalls.push_back(CI);
779     }
780   } else {
781     SmallPtrSet<BasicBlock*, 4> VisitedBBs;
782     for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
783       if (!VisitedBBs.insert(*PI))
784         continue;
785
786       BasicBlock::InstListType &InstList = (*PI)->getInstList();
787       BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
788       BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
789       do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
790       if (RI == RE)
791         continue;
792
793       CallInst *CI = dyn_cast<CallInst>(&*RI);
794       if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI))
795         TailCalls.push_back(CI);
796     }
797   }
798
799   bool Changed = false;
800   for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
801     CallInst *CI = TailCalls[i];
802     CallSite CS(CI);
803
804     // Conservatively require the attributes of the call to match those of the
805     // return. Ignore noalias because it doesn't affect the call sequence.
806     AttributeSet CalleeAttrs = CS.getAttributes();
807     if (AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
808           removeAttribute(Attribute::NoAlias) !=
809         AttrBuilder(CalleeAttrs, AttributeSet::ReturnIndex).
810           removeAttribute(Attribute::NoAlias))
811       continue;
812
813     // Make sure the call instruction is followed by an unconditional branch to
814     // the return block.
815     BasicBlock *CallBB = CI->getParent();
816     BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
817     if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
818       continue;
819
820     // Duplicate the return into CallBB.
821     (void)FoldReturnIntoUncondBranch(RI, BB, CallBB);
822     ModifiedDT = Changed = true;
823     ++NumRetsDup;
824   }
825
826   // If we eliminated all predecessors of the block, delete the block now.
827   if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
828     BB->eraseFromParent();
829
830   return Changed;
831 }
832
833 //===----------------------------------------------------------------------===//
834 // Memory Optimization
835 //===----------------------------------------------------------------------===//
836
837 namespace {
838
839 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
840 /// which holds actual Value*'s for register values.
841 struct ExtAddrMode : public TargetLowering::AddrMode {
842   Value *BaseReg;
843   Value *ScaledReg;
844   ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
845   void print(raw_ostream &OS) const;
846   void dump() const;
847
848   bool operator==(const ExtAddrMode& O) const {
849     return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
850            (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
851            (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
852   }
853 };
854
855 #ifndef NDEBUG
856 static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
857   AM.print(OS);
858   return OS;
859 }
860 #endif
861
862 void ExtAddrMode::print(raw_ostream &OS) const {
863   bool NeedPlus = false;
864   OS << "[";
865   if (BaseGV) {
866     OS << (NeedPlus ? " + " : "")
867        << "GV:";
868     BaseGV->printAsOperand(OS, /*PrintType=*/false);
869     NeedPlus = true;
870   }
871
872   if (BaseOffs)
873     OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
874
875   if (BaseReg) {
876     OS << (NeedPlus ? " + " : "")
877        << "Base:";
878     BaseReg->printAsOperand(OS, /*PrintType=*/false);
879     NeedPlus = true;
880   }
881   if (Scale) {
882     OS << (NeedPlus ? " + " : "")
883        << Scale << "*";
884     ScaledReg->printAsOperand(OS, /*PrintType=*/false);
885   }
886
887   OS << ']';
888 }
889
890 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
891 void ExtAddrMode::dump() const {
892   print(dbgs());
893   dbgs() << '\n';
894 }
895 #endif
896
897 /// \brief This class provides transaction based operation on the IR.
898 /// Every change made through this class is recorded in the internal state and
899 /// can be undone (rollback) until commit is called.
900 class TypePromotionTransaction {
901
902   /// \brief This represents the common interface of the individual transaction.
903   /// Each class implements the logic for doing one specific modification on
904   /// the IR via the TypePromotionTransaction.
905   class TypePromotionAction {
906   protected:
907     /// The Instruction modified.
908     Instruction *Inst;
909
910   public:
911     /// \brief Constructor of the action.
912     /// The constructor performs the related action on the IR.
913     TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
914
915     virtual ~TypePromotionAction() {}
916
917     /// \brief Undo the modification done by this action.
918     /// When this method is called, the IR must be in the same state as it was
919     /// before this action was applied.
920     /// \pre Undoing the action works if and only if the IR is in the exact same
921     /// state as it was directly after this action was applied.
922     virtual void undo() = 0;
923
924     /// \brief Advocate every change made by this action.
925     /// When the results on the IR of the action are to be kept, it is important
926     /// to call this function, otherwise hidden information may be kept forever.
927     virtual void commit() {
928       // Nothing to be done, this action is not doing anything.
929     }
930   };
931
932   /// \brief Utility to remember the position of an instruction.
933   class InsertionHandler {
934     /// Position of an instruction.
935     /// Either an instruction:
936     /// - Is the first in a basic block: BB is used.
937     /// - Has a previous instructon: PrevInst is used.
938     union {
939       Instruction *PrevInst;
940       BasicBlock *BB;
941     } Point;
942     /// Remember whether or not the instruction had a previous instruction.
943     bool HasPrevInstruction;
944
945   public:
946     /// \brief Record the position of \p Inst.
947     InsertionHandler(Instruction *Inst) {
948       BasicBlock::iterator It = Inst;
949       HasPrevInstruction = (It != (Inst->getParent()->begin()));
950       if (HasPrevInstruction)
951         Point.PrevInst = --It;
952       else
953         Point.BB = Inst->getParent();
954     }
955
956     /// \brief Insert \p Inst at the recorded position.
957     void insert(Instruction *Inst) {
958       if (HasPrevInstruction) {
959         if (Inst->getParent())
960           Inst->removeFromParent();
961         Inst->insertAfter(Point.PrevInst);
962       } else {
963         Instruction *Position = Point.BB->getFirstInsertionPt();
964         if (Inst->getParent())
965           Inst->moveBefore(Position);
966         else
967           Inst->insertBefore(Position);
968       }
969     }
970   };
971
972   /// \brief Move an instruction before another.
973   class InstructionMoveBefore : public TypePromotionAction {
974     /// Original position of the instruction.
975     InsertionHandler Position;
976
977   public:
978     /// \brief Move \p Inst before \p Before.
979     InstructionMoveBefore(Instruction *Inst, Instruction *Before)
980         : TypePromotionAction(Inst), Position(Inst) {
981       DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
982       Inst->moveBefore(Before);
983     }
984
985     /// \brief Move the instruction back to its original position.
986     void undo() {
987       DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
988       Position.insert(Inst);
989     }
990   };
991
992   /// \brief Set the operand of an instruction with a new value.
993   class OperandSetter : public TypePromotionAction {
994     /// Original operand of the instruction.
995     Value *Origin;
996     /// Index of the modified instruction.
997     unsigned Idx;
998
999   public:
1000     /// \brief Set \p Idx operand of \p Inst with \p NewVal.
1001     OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
1002         : TypePromotionAction(Inst), Idx(Idx) {
1003       DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
1004                    << "for:" << *Inst << "\n"
1005                    << "with:" << *NewVal << "\n");
1006       Origin = Inst->getOperand(Idx);
1007       Inst->setOperand(Idx, NewVal);
1008     }
1009
1010     /// \brief Restore the original value of the instruction.
1011     void undo() {
1012       DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
1013                    << "for: " << *Inst << "\n"
1014                    << "with: " << *Origin << "\n");
1015       Inst->setOperand(Idx, Origin);
1016     }
1017   };
1018
1019   /// \brief Hide the operands of an instruction.
1020   /// Do as if this instruction was not using any of its operands.
1021   class OperandsHider : public TypePromotionAction {
1022     /// The list of original operands.
1023     SmallVector<Value *, 4> OriginalValues;
1024
1025   public:
1026     /// \brief Remove \p Inst from the uses of the operands of \p Inst.
1027     OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
1028       DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
1029       unsigned NumOpnds = Inst->getNumOperands();
1030       OriginalValues.reserve(NumOpnds);
1031       for (unsigned It = 0; It < NumOpnds; ++It) {
1032         // Save the current operand.
1033         Value *Val = Inst->getOperand(It);
1034         OriginalValues.push_back(Val);
1035         // Set a dummy one.
1036         // We could use OperandSetter here, but that would implied an overhead
1037         // that we are not willing to pay.
1038         Inst->setOperand(It, UndefValue::get(Val->getType()));
1039       }
1040     }
1041
1042     /// \brief Restore the original list of uses.
1043     void undo() {
1044       DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
1045       for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
1046         Inst->setOperand(It, OriginalValues[It]);
1047     }
1048   };
1049
1050   /// \brief Build a truncate instruction.
1051   class TruncBuilder : public TypePromotionAction {
1052   public:
1053     /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
1054     /// result.
1055     /// trunc Opnd to Ty.
1056     TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
1057       IRBuilder<> Builder(Opnd);
1058       Inst = cast<Instruction>(Builder.CreateTrunc(Opnd, Ty, "promoted"));
1059       DEBUG(dbgs() << "Do: TruncBuilder: " << *Inst << "\n");
1060     }
1061
1062     /// \brief Get the built instruction.
1063     Instruction *getBuiltInstruction() { return Inst; }
1064
1065     /// \brief Remove the built instruction.
1066     void undo() {
1067       DEBUG(dbgs() << "Undo: TruncBuilder: " << *Inst << "\n");
1068       Inst->eraseFromParent();
1069     }
1070   };
1071
1072   /// \brief Build a sign extension instruction.
1073   class SExtBuilder : public TypePromotionAction {
1074   public:
1075     /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
1076     /// result.
1077     /// sext Opnd to Ty.
1078     SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
1079         : TypePromotionAction(Inst) {
1080       IRBuilder<> Builder(InsertPt);
1081       Inst = cast<Instruction>(Builder.CreateSExt(Opnd, Ty, "promoted"));
1082       DEBUG(dbgs() << "Do: SExtBuilder: " << *Inst << "\n");
1083     }
1084
1085     /// \brief Get the built instruction.
1086     Instruction *getBuiltInstruction() { return Inst; }
1087
1088     /// \brief Remove the built instruction.
1089     void undo() {
1090       DEBUG(dbgs() << "Undo: SExtBuilder: " << *Inst << "\n");
1091       Inst->eraseFromParent();
1092     }
1093   };
1094
1095   /// \brief Mutate an instruction to another type.
1096   class TypeMutator : public TypePromotionAction {
1097     /// Record the original type.
1098     Type *OrigTy;
1099
1100   public:
1101     /// \brief Mutate the type of \p Inst into \p NewTy.
1102     TypeMutator(Instruction *Inst, Type *NewTy)
1103         : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
1104       DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
1105                    << "\n");
1106       Inst->mutateType(NewTy);
1107     }
1108
1109     /// \brief Mutate the instruction back to its original type.
1110     void undo() {
1111       DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
1112                    << "\n");
1113       Inst->mutateType(OrigTy);
1114     }
1115   };
1116
1117   /// \brief Replace the uses of an instruction by another instruction.
1118   class UsesReplacer : public TypePromotionAction {
1119     /// Helper structure to keep track of the replaced uses.
1120     struct InstructionAndIdx {
1121       /// The instruction using the instruction.
1122       Instruction *Inst;
1123       /// The index where this instruction is used for Inst.
1124       unsigned Idx;
1125       InstructionAndIdx(Instruction *Inst, unsigned Idx)
1126           : Inst(Inst), Idx(Idx) {}
1127     };
1128
1129     /// Keep track of the original uses (pair Instruction, Index).
1130     SmallVector<InstructionAndIdx, 4> OriginalUses;
1131     typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
1132
1133   public:
1134     /// \brief Replace all the use of \p Inst by \p New.
1135     UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
1136       DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
1137                    << "\n");
1138       // Record the original uses.
1139       for (Value::use_iterator UseIt = Inst->use_begin(),
1140                                EndIt = Inst->use_end();
1141            UseIt != EndIt; ++UseIt) {
1142         Instruction *Use = cast<Instruction>(*UseIt);
1143         OriginalUses.push_back(InstructionAndIdx(Use, UseIt.getOperandNo()));
1144       }
1145       // Now, we can replace the uses.
1146       Inst->replaceAllUsesWith(New);
1147     }
1148
1149     /// \brief Reassign the original uses of Inst to Inst.
1150     void undo() {
1151       DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
1152       for (use_iterator UseIt = OriginalUses.begin(),
1153                         EndIt = OriginalUses.end();
1154            UseIt != EndIt; ++UseIt) {
1155         UseIt->Inst->setOperand(UseIt->Idx, Inst);
1156       }
1157     }
1158   };
1159
1160   /// \brief Remove an instruction from the IR.
1161   class InstructionRemover : public TypePromotionAction {
1162     /// Original position of the instruction.
1163     InsertionHandler Inserter;
1164     /// Helper structure to hide all the link to the instruction. In other
1165     /// words, this helps to do as if the instruction was removed.
1166     OperandsHider Hider;
1167     /// Keep track of the uses replaced, if any.
1168     UsesReplacer *Replacer;
1169
1170   public:
1171     /// \brief Remove all reference of \p Inst and optinally replace all its
1172     /// uses with New.
1173     /// \pre If !Inst->use_empty(), then New != NULL
1174     InstructionRemover(Instruction *Inst, Value *New = NULL)
1175         : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
1176           Replacer(NULL) {
1177       if (New)
1178         Replacer = new UsesReplacer(Inst, New);
1179       DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
1180       Inst->removeFromParent();
1181     }
1182
1183     ~InstructionRemover() { delete Replacer; }
1184
1185     /// \brief Really remove the instruction.
1186     void commit() { delete Inst; }
1187
1188     /// \brief Resurrect the instruction and reassign it to the proper uses if
1189     /// new value was provided when build this action.
1190     void undo() {
1191       DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
1192       Inserter.insert(Inst);
1193       if (Replacer)
1194         Replacer->undo();
1195       Hider.undo();
1196     }
1197   };
1198
1199 public:
1200   /// Restoration point.
1201   /// The restoration point is a pointer to an action instead of an iterator
1202   /// because the iterator may be invalidated but not the pointer.
1203   typedef const TypePromotionAction *ConstRestorationPt;
1204   /// Advocate every changes made in that transaction.
1205   void commit();
1206   /// Undo all the changes made after the given point.
1207   void rollback(ConstRestorationPt Point);
1208   /// Get the current restoration point.
1209   ConstRestorationPt getRestorationPoint() const;
1210
1211   /// \name API for IR modification with state keeping to support rollback.
1212   /// @{
1213   /// Same as Instruction::setOperand.
1214   void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
1215   /// Same as Instruction::eraseFromParent.
1216   void eraseInstruction(Instruction *Inst, Value *NewVal = NULL);
1217   /// Same as Value::replaceAllUsesWith.
1218   void replaceAllUsesWith(Instruction *Inst, Value *New);
1219   /// Same as Value::mutateType.
1220   void mutateType(Instruction *Inst, Type *NewTy);
1221   /// Same as IRBuilder::createTrunc.
1222   Instruction *createTrunc(Instruction *Opnd, Type *Ty);
1223   /// Same as IRBuilder::createSExt.
1224   Instruction *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
1225   /// Same as Instruction::moveBefore.
1226   void moveBefore(Instruction *Inst, Instruction *Before);
1227   /// @}
1228
1229   ~TypePromotionTransaction();
1230
1231 private:
1232   /// The ordered list of actions made so far.
1233   SmallVector<TypePromotionAction *, 16> Actions;
1234   typedef SmallVectorImpl<TypePromotionAction *>::iterator CommitPt;
1235 };
1236
1237 void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
1238                                           Value *NewVal) {
1239   Actions.push_back(
1240       new TypePromotionTransaction::OperandSetter(Inst, Idx, NewVal));
1241 }
1242
1243 void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
1244                                                 Value *NewVal) {
1245   Actions.push_back(
1246       new TypePromotionTransaction::InstructionRemover(Inst, NewVal));
1247 }
1248
1249 void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
1250                                                   Value *New) {
1251   Actions.push_back(new TypePromotionTransaction::UsesReplacer(Inst, New));
1252 }
1253
1254 void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
1255   Actions.push_back(new TypePromotionTransaction::TypeMutator(Inst, NewTy));
1256 }
1257
1258 Instruction *TypePromotionTransaction::createTrunc(Instruction *Opnd,
1259                                                    Type *Ty) {
1260   TruncBuilder *TB = new TruncBuilder(Opnd, Ty);
1261   Actions.push_back(TB);
1262   return TB->getBuiltInstruction();
1263 }
1264
1265 Instruction *TypePromotionTransaction::createSExt(Instruction *Inst,
1266                                                   Value *Opnd, Type *Ty) {
1267   SExtBuilder *SB = new SExtBuilder(Inst, Opnd, Ty);
1268   Actions.push_back(SB);
1269   return SB->getBuiltInstruction();
1270 }
1271
1272 void TypePromotionTransaction::moveBefore(Instruction *Inst,
1273                                           Instruction *Before) {
1274   Actions.push_back(
1275       new TypePromotionTransaction::InstructionMoveBefore(Inst, Before));
1276 }
1277
1278 TypePromotionTransaction::ConstRestorationPt
1279 TypePromotionTransaction::getRestorationPoint() const {
1280   return Actions.rbegin() != Actions.rend() ? *Actions.rbegin() : NULL;
1281 }
1282
1283 void TypePromotionTransaction::commit() {
1284   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
1285        ++It) {
1286     (*It)->commit();
1287     delete *It;
1288   }
1289   Actions.clear();
1290 }
1291
1292 void TypePromotionTransaction::rollback(
1293     TypePromotionTransaction::ConstRestorationPt Point) {
1294   while (!Actions.empty() && Point != (*Actions.rbegin())) {
1295     TypePromotionAction *Curr = Actions.pop_back_val();
1296     Curr->undo();
1297     delete Curr;
1298   }
1299 }
1300
1301 TypePromotionTransaction::~TypePromotionTransaction() {
1302   for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt; ++It)
1303     delete *It;
1304   Actions.clear();
1305 }
1306
1307 /// \brief A helper class for matching addressing modes.
1308 ///
1309 /// This encapsulates the logic for matching the target-legal addressing modes.
1310 class AddressingModeMatcher {
1311   SmallVectorImpl<Instruction*> &AddrModeInsts;
1312   const TargetLowering &TLI;
1313
1314   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
1315   /// the memory instruction that we're computing this address for.
1316   Type *AccessTy;
1317   Instruction *MemoryInst;
1318
1319   /// AddrMode - This is the addressing mode that we're building up.  This is
1320   /// part of the return value of this addressing mode matching stuff.
1321   ExtAddrMode &AddrMode;
1322
1323   /// The truncate instruction inserted by other CodeGenPrepare optimizations.
1324   const SetOfInstrs &InsertedTruncs;
1325   /// A map from the instructions to their type before promotion.
1326   InstrToOrigTy &PromotedInsts;
1327   /// The ongoing transaction where every action should be registered.
1328   TypePromotionTransaction &TPT;
1329
1330   /// IgnoreProfitability - This is set to true when we should not do
1331   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
1332   /// always returns true.
1333   bool IgnoreProfitability;
1334
1335   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
1336                         const TargetLowering &T, Type *AT,
1337                         Instruction *MI, ExtAddrMode &AM,
1338                         const SetOfInstrs &InsertedTruncs,
1339                         InstrToOrigTy &PromotedInsts,
1340                         TypePromotionTransaction &TPT)
1341       : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM),
1342         InsertedTruncs(InsertedTruncs), PromotedInsts(PromotedInsts), TPT(TPT) {
1343     IgnoreProfitability = false;
1344   }
1345 public:
1346
1347   /// Match - Find the maximal addressing mode that a load/store of V can fold,
1348   /// give an access type of AccessTy.  This returns a list of involved
1349   /// instructions in AddrModeInsts.
1350   /// \p InsertedTruncs The truncate instruction inserted by other
1351   /// CodeGenPrepare
1352   /// optimizations.
1353   /// \p PromotedInsts maps the instructions to their type before promotion.
1354   /// \p The ongoing transaction where every action should be registered.
1355   static ExtAddrMode Match(Value *V, Type *AccessTy,
1356                            Instruction *MemoryInst,
1357                            SmallVectorImpl<Instruction*> &AddrModeInsts,
1358                            const TargetLowering &TLI,
1359                            const SetOfInstrs &InsertedTruncs,
1360                            InstrToOrigTy &PromotedInsts,
1361                            TypePromotionTransaction &TPT) {
1362     ExtAddrMode Result;
1363
1364     bool Success = AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
1365                                          MemoryInst, Result, InsertedTruncs,
1366                                          PromotedInsts, TPT).MatchAddr(V, 0);
1367     (void)Success; assert(Success && "Couldn't select *anything*?");
1368     return Result;
1369   }
1370 private:
1371   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
1372   bool MatchAddr(Value *V, unsigned Depth);
1373   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
1374                           bool *MovedAway = NULL);
1375   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
1376                                             ExtAddrMode &AMBefore,
1377                                             ExtAddrMode &AMAfter);
1378   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
1379 };
1380
1381 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
1382 /// Return true and update AddrMode if this addr mode is legal for the target,
1383 /// false if not.
1384 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
1385                                              unsigned Depth) {
1386   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
1387   // mode.  Just process that directly.
1388   if (Scale == 1)
1389     return MatchAddr(ScaleReg, Depth);
1390
1391   // If the scale is 0, it takes nothing to add this.
1392   if (Scale == 0)
1393     return true;
1394
1395   // If we already have a scale of this value, we can add to it, otherwise, we
1396   // need an available scale field.
1397   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
1398     return false;
1399
1400   ExtAddrMode TestAddrMode = AddrMode;
1401
1402   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
1403   // [A+B + A*7] -> [B+A*8].
1404   TestAddrMode.Scale += Scale;
1405   TestAddrMode.ScaledReg = ScaleReg;
1406
1407   // If the new address isn't legal, bail out.
1408   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
1409     return false;
1410
1411   // It was legal, so commit it.
1412   AddrMode = TestAddrMode;
1413
1414   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
1415   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
1416   // X*Scale + C*Scale to addr mode.
1417   ConstantInt *CI = 0; Value *AddLHS = 0;
1418   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
1419       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
1420     TestAddrMode.ScaledReg = AddLHS;
1421     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
1422
1423     // If this addressing mode is legal, commit it and remember that we folded
1424     // this instruction.
1425     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
1426       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
1427       AddrMode = TestAddrMode;
1428       return true;
1429     }
1430   }
1431
1432   // Otherwise, not (x+c)*scale, just return what we have.
1433   return true;
1434 }
1435
1436 /// MightBeFoldableInst - This is a little filter, which returns true if an
1437 /// addressing computation involving I might be folded into a load/store
1438 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
1439 /// the set of instructions that MatchOperationAddr can.
1440 static bool MightBeFoldableInst(Instruction *I) {
1441   switch (I->getOpcode()) {
1442   case Instruction::BitCast:
1443     // Don't touch identity bitcasts.
1444     if (I->getType() == I->getOperand(0)->getType())
1445       return false;
1446     return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
1447   case Instruction::PtrToInt:
1448     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1449     return true;
1450   case Instruction::IntToPtr:
1451     // We know the input is intptr_t, so this is foldable.
1452     return true;
1453   case Instruction::Add:
1454     return true;
1455   case Instruction::Mul:
1456   case Instruction::Shl:
1457     // Can only handle X*C and X << C.
1458     return isa<ConstantInt>(I->getOperand(1));
1459   case Instruction::GetElementPtr:
1460     return true;
1461   default:
1462     return false;
1463   }
1464 }
1465
1466 /// \brief Hepler class to perform type promotion.
1467 class TypePromotionHelper {
1468   /// \brief Utility function to check whether or not a sign extension of
1469   /// \p Inst with \p ConsideredSExtType can be moved through \p Inst by either
1470   /// using the operands of \p Inst or promoting \p Inst.
1471   /// In other words, check if:
1472   /// sext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredSExtType.
1473   /// #1 Promotion applies:
1474   /// ConsideredSExtType Inst (sext opnd1 to ConsideredSExtType, ...).
1475   /// #2 Operand reuses:
1476   /// sext opnd1 to ConsideredSExtType.
1477   /// \p PromotedInsts maps the instructions to their type before promotion.
1478   static bool canGetThrough(const Instruction *Inst, Type *ConsideredSExtType,
1479                             const InstrToOrigTy &PromotedInsts);
1480
1481   /// \brief Utility function to determine if \p OpIdx should be promoted when
1482   /// promoting \p Inst.
1483   static bool shouldSExtOperand(const Instruction *Inst, int OpIdx) {
1484     if (isa<SelectInst>(Inst) && OpIdx == 0)
1485       return false;
1486     return true;
1487   }
1488
1489   /// \brief Utility function to promote the operand of \p SExt when this
1490   /// operand is a promotable trunc or sext.
1491   /// \p PromotedInsts maps the instructions to their type before promotion.
1492   /// \p CreatedInsts[out] contains how many non-free instructions have been
1493   /// created to promote the operand of SExt.
1494   /// Should never be called directly.
1495   /// \return The promoted value which is used instead of SExt.
1496   static Value *promoteOperandForTruncAndSExt(Instruction *SExt,
1497                                               TypePromotionTransaction &TPT,
1498                                               InstrToOrigTy &PromotedInsts,
1499                                               unsigned &CreatedInsts);
1500
1501   /// \brief Utility function to promote the operand of \p SExt when this
1502   /// operand is promotable and is not a supported trunc or sext.
1503   /// \p PromotedInsts maps the instructions to their type before promotion.
1504   /// \p CreatedInsts[out] contains how many non-free instructions have been
1505   /// created to promote the operand of SExt.
1506   /// Should never be called directly.
1507   /// \return The promoted value which is used instead of SExt.
1508   static Value *promoteOperandForOther(Instruction *SExt,
1509                                        TypePromotionTransaction &TPT,
1510                                        InstrToOrigTy &PromotedInsts,
1511                                        unsigned &CreatedInsts);
1512
1513 public:
1514   /// Type for the utility function that promotes the operand of SExt.
1515   typedef Value *(*Action)(Instruction *SExt, TypePromotionTransaction &TPT,
1516                            InstrToOrigTy &PromotedInsts,
1517                            unsigned &CreatedInsts);
1518   /// \brief Given a sign extend instruction \p SExt, return the approriate
1519   /// action to promote the operand of \p SExt instead of using SExt.
1520   /// \return NULL if no promotable action is possible with the current
1521   /// sign extension.
1522   /// \p InsertedTruncs keeps track of all the truncate instructions inserted by
1523   /// the others CodeGenPrepare optimizations. This information is important
1524   /// because we do not want to promote these instructions as CodeGenPrepare
1525   /// will reinsert them later. Thus creating an infinite loop: create/remove.
1526   /// \p PromotedInsts maps the instructions to their type before promotion.
1527   static Action getAction(Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1528                           const TargetLowering &TLI,
1529                           const InstrToOrigTy &PromotedInsts);
1530 };
1531
1532 bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
1533                                         Type *ConsideredSExtType,
1534                                         const InstrToOrigTy &PromotedInsts) {
1535   // We can always get through sext.
1536   if (isa<SExtInst>(Inst))
1537     return true;
1538
1539   // We can get through binary operator, if it is legal. In other words, the
1540   // binary operator must have a nuw or nsw flag.
1541   const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
1542   if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
1543       (BinOp->hasNoUnsignedWrap() || BinOp->hasNoSignedWrap()))
1544     return true;
1545
1546   // Check if we can do the following simplification.
1547   // sext(trunc(sext)) --> sext
1548   if (!isa<TruncInst>(Inst))
1549     return false;
1550
1551   Value *OpndVal = Inst->getOperand(0);
1552   // Check if we can use this operand in the sext.
1553   // If the type is larger than the result type of the sign extension,
1554   // we cannot.
1555   if (OpndVal->getType()->getIntegerBitWidth() >
1556       ConsideredSExtType->getIntegerBitWidth())
1557     return false;
1558
1559   // If the operand of the truncate is not an instruction, we will not have
1560   // any information on the dropped bits.
1561   // (Actually we could for constant but it is not worth the extra logic).
1562   Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
1563   if (!Opnd)
1564     return false;
1565
1566   // Check if the source of the type is narrow enough.
1567   // I.e., check that trunc just drops sign extended bits.
1568   // #1 get the type of the operand.
1569   const Type *OpndType;
1570   InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
1571   if (It != PromotedInsts.end())
1572     OpndType = It->second;
1573   else if (isa<SExtInst>(Opnd))
1574     OpndType = cast<Instruction>(Opnd)->getOperand(0)->getType();
1575   else
1576     return false;
1577
1578   // #2 check that the truncate just drop sign extended bits.
1579   if (Inst->getType()->getIntegerBitWidth() >= OpndType->getIntegerBitWidth())
1580     return true;
1581
1582   return false;
1583 }
1584
1585 TypePromotionHelper::Action TypePromotionHelper::getAction(
1586     Instruction *SExt, const SetOfInstrs &InsertedTruncs,
1587     const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
1588   Instruction *SExtOpnd = dyn_cast<Instruction>(SExt->getOperand(0));
1589   Type *SExtTy = SExt->getType();
1590   // If the operand of the sign extension is not an instruction, we cannot
1591   // get through.
1592   // If it, check we can get through.
1593   if (!SExtOpnd || !canGetThrough(SExtOpnd, SExtTy, PromotedInsts))
1594     return NULL;
1595
1596   // Do not promote if the operand has been added by codegenprepare.
1597   // Otherwise, it means we are undoing an optimization that is likely to be
1598   // redone, thus causing potential infinite loop.
1599   if (isa<TruncInst>(SExtOpnd) && InsertedTruncs.count(SExtOpnd))
1600     return NULL;
1601
1602   // SExt or Trunc instructions.
1603   // Return the related handler.
1604   if (isa<SExtInst>(SExtOpnd) || isa<TruncInst>(SExtOpnd))
1605     return promoteOperandForTruncAndSExt;
1606
1607   // Regular instruction.
1608   // Abort early if we will have to insert non-free instructions.
1609   if (!SExtOpnd->hasOneUse() &&
1610       !TLI.isTruncateFree(SExtTy, SExtOpnd->getType()))
1611     return NULL;
1612   return promoteOperandForOther;
1613 }
1614
1615 Value *TypePromotionHelper::promoteOperandForTruncAndSExt(
1616     llvm::Instruction *SExt, TypePromotionTransaction &TPT,
1617     InstrToOrigTy &PromotedInsts, unsigned &CreatedInsts) {
1618   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1619   // get through it and this method should not be called.
1620   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1621   // Replace sext(trunc(opnd)) or sext(sext(opnd))
1622   // => sext(opnd).
1623   TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
1624   CreatedInsts = 0;
1625
1626   // Remove dead code.
1627   if (SExtOpnd->use_empty())
1628     TPT.eraseInstruction(SExtOpnd);
1629
1630   // Check if the sext is still needed.
1631   if (SExt->getType() != SExt->getOperand(0)->getType())
1632     return SExt;
1633
1634   // At this point we have: sext ty opnd to ty.
1635   // Reassign the uses of SExt to the opnd and remove SExt.
1636   Value *NextVal = SExt->getOperand(0);
1637   TPT.eraseInstruction(SExt, NextVal);
1638   return NextVal;
1639 }
1640
1641 Value *
1642 TypePromotionHelper::promoteOperandForOther(Instruction *SExt,
1643                                             TypePromotionTransaction &TPT,
1644                                             InstrToOrigTy &PromotedInsts,
1645                                             unsigned &CreatedInsts) {
1646   // By construction, the operand of SExt is an instruction. Otherwise we cannot
1647   // get through it and this method should not be called.
1648   Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
1649   CreatedInsts = 0;
1650   if (!SExtOpnd->hasOneUse()) {
1651     // SExtOpnd will be promoted.
1652     // All its uses, but SExt, will need to use a truncated value of the
1653     // promoted version.
1654     // Create the truncate now.
1655     Instruction *Trunc = TPT.createTrunc(SExt, SExtOpnd->getType());
1656     Trunc->removeFromParent();
1657     // Insert it just after the definition.
1658     Trunc->insertAfter(SExtOpnd);
1659
1660     TPT.replaceAllUsesWith(SExtOpnd, Trunc);
1661     // Restore the operand of SExt (which has been replace by the previous call
1662     // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
1663     TPT.setOperand(SExt, 0, SExtOpnd);
1664   }
1665
1666   // Get through the Instruction:
1667   // 1. Update its type.
1668   // 2. Replace the uses of SExt by Inst.
1669   // 3. Sign extend each operand that needs to be sign extended.
1670
1671   // Remember the original type of the instruction before promotion.
1672   // This is useful to know that the high bits are sign extended bits.
1673   PromotedInsts.insert(
1674       std::pair<Instruction *, Type *>(SExtOpnd, SExtOpnd->getType()));
1675   // Step #1.
1676   TPT.mutateType(SExtOpnd, SExt->getType());
1677   // Step #2.
1678   TPT.replaceAllUsesWith(SExt, SExtOpnd);
1679   // Step #3.
1680   Instruction *SExtForOpnd = SExt;
1681
1682   DEBUG(dbgs() << "Propagate SExt to operands\n");
1683   for (int OpIdx = 0, EndOpIdx = SExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
1684        ++OpIdx) {
1685     DEBUG(dbgs() << "Operand:\n" << *(SExtOpnd->getOperand(OpIdx)) << '\n');
1686     if (SExtOpnd->getOperand(OpIdx)->getType() == SExt->getType() ||
1687         !shouldSExtOperand(SExtOpnd, OpIdx)) {
1688       DEBUG(dbgs() << "No need to propagate\n");
1689       continue;
1690     }
1691     // Check if we can statically sign extend the operand.
1692     Value *Opnd = SExtOpnd->getOperand(OpIdx);
1693     if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
1694       DEBUG(dbgs() << "Statically sign extend\n");
1695       TPT.setOperand(
1696           SExtOpnd, OpIdx,
1697           ConstantInt::getSigned(SExt->getType(), Cst->getSExtValue()));
1698       continue;
1699     }
1700     // UndefValue are typed, so we have to statically sign extend them.
1701     if (isa<UndefValue>(Opnd)) {
1702       DEBUG(dbgs() << "Statically sign extend\n");
1703       TPT.setOperand(SExtOpnd, OpIdx, UndefValue::get(SExt->getType()));
1704       continue;
1705     }
1706
1707     // Otherwise we have to explicity sign extend the operand.
1708     // Check if SExt was reused to sign extend an operand.
1709     if (!SExtForOpnd) {
1710       // If yes, create a new one.
1711       DEBUG(dbgs() << "More operands to sext\n");
1712       SExtForOpnd = TPT.createSExt(SExt, Opnd, SExt->getType());
1713       ++CreatedInsts;
1714     }
1715
1716     TPT.setOperand(SExtForOpnd, 0, Opnd);
1717
1718     // Move the sign extension before the insertion point.
1719     TPT.moveBefore(SExtForOpnd, SExtOpnd);
1720     TPT.setOperand(SExtOpnd, OpIdx, SExtForOpnd);
1721     // If more sext are required, new instructions will have to be created.
1722     SExtForOpnd = NULL;
1723   }
1724   if (SExtForOpnd == SExt) {
1725     DEBUG(dbgs() << "Sign extension is useless now\n");
1726     TPT.eraseInstruction(SExt);
1727   }
1728   return SExtOpnd;
1729 }
1730
1731 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
1732 /// fold the operation into the addressing mode.  If so, update the addressing
1733 /// mode and return true, otherwise return false without modifying AddrMode.
1734 /// If \p MovedAway is not NULL, it contains the information of whether or
1735 /// not AddrInst has to be folded into the addressing mode on success.
1736 /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
1737 /// because it has been moved away.
1738 /// Thus AddrInst must not be added in the matched instructions.
1739 /// This state can happen when AddrInst is a sext, since it may be moved away.
1740 /// Therefore, AddrInst may not be valid when MovedAway is true and it must
1741 /// not be referenced anymore.
1742 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
1743                                                unsigned Depth,
1744                                                bool *MovedAway) {
1745   // Avoid exponential behavior on extremely deep expression trees.
1746   if (Depth >= 5) return false;
1747
1748   // By default, all matched instructions stay in place.
1749   if (MovedAway)
1750     *MovedAway = false;
1751
1752   switch (Opcode) {
1753   case Instruction::PtrToInt:
1754     // PtrToInt is always a noop, as we know that the int type is pointer sized.
1755     return MatchAddr(AddrInst->getOperand(0), Depth);
1756   case Instruction::IntToPtr:
1757     // This inttoptr is a no-op if the integer type is pointer sized.
1758     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
1759         TLI.getPointerTy(AddrInst->getType()->getPointerAddressSpace()))
1760       return MatchAddr(AddrInst->getOperand(0), Depth);
1761     return false;
1762   case Instruction::BitCast:
1763     // BitCast is always a noop, and we can handle it as long as it is
1764     // int->int or pointer->pointer (we don't want int<->fp or something).
1765     if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
1766          AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
1767         // Don't touch identity bitcasts.  These were probably put here by LSR,
1768         // and we don't want to mess around with them.  Assume it knows what it
1769         // is doing.
1770         AddrInst->getOperand(0)->getType() != AddrInst->getType())
1771       return MatchAddr(AddrInst->getOperand(0), Depth);
1772     return false;
1773   case Instruction::Add: {
1774     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
1775     ExtAddrMode BackupAddrMode = AddrMode;
1776     unsigned OldSize = AddrModeInsts.size();
1777     // Start a transaction at this point.
1778     // The LHS may match but not the RHS.
1779     // Therefore, we need a higher level restoration point to undo partially
1780     // matched operation.
1781     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1782         TPT.getRestorationPoint();
1783
1784     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
1785         MatchAddr(AddrInst->getOperand(0), Depth+1))
1786       return true;
1787
1788     // Restore the old addr mode info.
1789     AddrMode = BackupAddrMode;
1790     AddrModeInsts.resize(OldSize);
1791     TPT.rollback(LastKnownGood);
1792
1793     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
1794     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
1795         MatchAddr(AddrInst->getOperand(1), Depth+1))
1796       return true;
1797
1798     // Otherwise we definitely can't merge the ADD in.
1799     AddrMode = BackupAddrMode;
1800     AddrModeInsts.resize(OldSize);
1801     TPT.rollback(LastKnownGood);
1802     break;
1803   }
1804   //case Instruction::Or:
1805   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
1806   //break;
1807   case Instruction::Mul:
1808   case Instruction::Shl: {
1809     // Can only handle X*C and X << C.
1810     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
1811     if (!RHS) return false;
1812     int64_t Scale = RHS->getSExtValue();
1813     if (Opcode == Instruction::Shl)
1814       Scale = 1LL << Scale;
1815
1816     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
1817   }
1818   case Instruction::GetElementPtr: {
1819     // Scan the GEP.  We check it if it contains constant offsets and at most
1820     // one variable offset.
1821     int VariableOperand = -1;
1822     unsigned VariableScale = 0;
1823
1824     int64_t ConstantOffset = 0;
1825     const DataLayout *TD = TLI.getDataLayout();
1826     gep_type_iterator GTI = gep_type_begin(AddrInst);
1827     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
1828       if (StructType *STy = dyn_cast<StructType>(*GTI)) {
1829         const StructLayout *SL = TD->getStructLayout(STy);
1830         unsigned Idx =
1831           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
1832         ConstantOffset += SL->getElementOffset(Idx);
1833       } else {
1834         uint64_t TypeSize = TD->getTypeAllocSize(GTI.getIndexedType());
1835         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
1836           ConstantOffset += CI->getSExtValue()*TypeSize;
1837         } else if (TypeSize) {  // Scales of zero don't do anything.
1838           // We only allow one variable index at the moment.
1839           if (VariableOperand != -1)
1840             return false;
1841
1842           // Remember the variable index.
1843           VariableOperand = i;
1844           VariableScale = TypeSize;
1845         }
1846       }
1847     }
1848
1849     // A common case is for the GEP to only do a constant offset.  In this case,
1850     // just add it to the disp field and check validity.
1851     if (VariableOperand == -1) {
1852       AddrMode.BaseOffs += ConstantOffset;
1853       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
1854         // Check to see if we can fold the base pointer in too.
1855         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
1856           return true;
1857       }
1858       AddrMode.BaseOffs -= ConstantOffset;
1859       return false;
1860     }
1861
1862     // Save the valid addressing mode in case we can't match.
1863     ExtAddrMode BackupAddrMode = AddrMode;
1864     unsigned OldSize = AddrModeInsts.size();
1865
1866     // See if the scale and offset amount is valid for this target.
1867     AddrMode.BaseOffs += ConstantOffset;
1868
1869     // Match the base operand of the GEP.
1870     if (!MatchAddr(AddrInst->getOperand(0), Depth+1)) {
1871       // If it couldn't be matched, just stuff the value in a register.
1872       if (AddrMode.HasBaseReg) {
1873         AddrMode = BackupAddrMode;
1874         AddrModeInsts.resize(OldSize);
1875         return false;
1876       }
1877       AddrMode.HasBaseReg = true;
1878       AddrMode.BaseReg = AddrInst->getOperand(0);
1879     }
1880
1881     // Match the remaining variable portion of the GEP.
1882     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
1883                           Depth)) {
1884       // If it couldn't be matched, try stuffing the base into a register
1885       // instead of matching it, and retrying the match of the scale.
1886       AddrMode = BackupAddrMode;
1887       AddrModeInsts.resize(OldSize);
1888       if (AddrMode.HasBaseReg)
1889         return false;
1890       AddrMode.HasBaseReg = true;
1891       AddrMode.BaseReg = AddrInst->getOperand(0);
1892       AddrMode.BaseOffs += ConstantOffset;
1893       if (!MatchScaledValue(AddrInst->getOperand(VariableOperand),
1894                             VariableScale, Depth)) {
1895         // If even that didn't work, bail.
1896         AddrMode = BackupAddrMode;
1897         AddrModeInsts.resize(OldSize);
1898         return false;
1899       }
1900     }
1901
1902     return true;
1903   }
1904   case Instruction::SExt: {
1905     // Try to move this sext out of the way of the addressing mode.
1906     Instruction *SExt = cast<Instruction>(AddrInst);
1907     // Ask for a method for doing so.
1908     TypePromotionHelper::Action TPH = TypePromotionHelper::getAction(
1909         SExt, InsertedTruncs, TLI, PromotedInsts);
1910     if (!TPH)
1911       return false;
1912
1913     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1914         TPT.getRestorationPoint();
1915     unsigned CreatedInsts = 0;
1916     Value *PromotedOperand = TPH(SExt, TPT, PromotedInsts, CreatedInsts);
1917     // SExt has been moved away.
1918     // Thus either it will be rematched later in the recursive calls or it is
1919     // gone. Anyway, we must not fold it into the addressing mode at this point.
1920     // E.g.,
1921     // op = add opnd, 1
1922     // idx = sext op
1923     // addr = gep base, idx
1924     // is now:
1925     // promotedOpnd = sext opnd           <- no match here
1926     // op = promoted_add promotedOpnd, 1  <- match (later in recursive calls)
1927     // addr = gep base, op                <- match
1928     if (MovedAway)
1929       *MovedAway = true;
1930
1931     assert(PromotedOperand &&
1932            "TypePromotionHelper should have filtered out those cases");
1933
1934     ExtAddrMode BackupAddrMode = AddrMode;
1935     unsigned OldSize = AddrModeInsts.size();
1936
1937     if (!MatchAddr(PromotedOperand, Depth) ||
1938         // We fold less instructions than what we created.
1939         // Undo at this point.
1940         (OldSize + CreatedInsts > AddrModeInsts.size())) {
1941       AddrMode = BackupAddrMode;
1942       AddrModeInsts.resize(OldSize);
1943       DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
1944       TPT.rollback(LastKnownGood);
1945       return false;
1946     }
1947     return true;
1948   }
1949   }
1950   return false;
1951 }
1952
1953 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
1954 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
1955 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
1956 /// or intptr_t for the target.
1957 ///
1958 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
1959   // Start a transaction at this point that we will rollback if the matching
1960   // fails.
1961   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
1962       TPT.getRestorationPoint();
1963   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
1964     // Fold in immediates if legal for the target.
1965     AddrMode.BaseOffs += CI->getSExtValue();
1966     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1967       return true;
1968     AddrMode.BaseOffs -= CI->getSExtValue();
1969   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
1970     // If this is a global variable, try to fold it into the addressing mode.
1971     if (AddrMode.BaseGV == 0) {
1972       AddrMode.BaseGV = GV;
1973       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
1974         return true;
1975       AddrMode.BaseGV = 0;
1976     }
1977   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
1978     ExtAddrMode BackupAddrMode = AddrMode;
1979     unsigned OldSize = AddrModeInsts.size();
1980
1981     // Check to see if it is possible to fold this operation.
1982     bool MovedAway = false;
1983     if (MatchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
1984       // This instruction may have been move away. If so, there is nothing
1985       // to check here.
1986       if (MovedAway)
1987         return true;
1988       // Okay, it's possible to fold this.  Check to see if it is actually
1989       // *profitable* to do so.  We use a simple cost model to avoid increasing
1990       // register pressure too much.
1991       if (I->hasOneUse() ||
1992           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
1993         AddrModeInsts.push_back(I);
1994         return true;
1995       }
1996
1997       // It isn't profitable to do this, roll back.
1998       //cerr << "NOT FOLDING: " << *I;
1999       AddrMode = BackupAddrMode;
2000       AddrModeInsts.resize(OldSize);
2001       TPT.rollback(LastKnownGood);
2002     }
2003   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
2004     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
2005       return true;
2006     TPT.rollback(LastKnownGood);
2007   } else if (isa<ConstantPointerNull>(Addr)) {
2008     // Null pointer gets folded without affecting the addressing mode.
2009     return true;
2010   }
2011
2012   // Worse case, the target should support [reg] addressing modes. :)
2013   if (!AddrMode.HasBaseReg) {
2014     AddrMode.HasBaseReg = true;
2015     AddrMode.BaseReg = Addr;
2016     // Still check for legality in case the target supports [imm] but not [i+r].
2017     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2018       return true;
2019     AddrMode.HasBaseReg = false;
2020     AddrMode.BaseReg = 0;
2021   }
2022
2023   // If the base register is already taken, see if we can do [r+r].
2024   if (AddrMode.Scale == 0) {
2025     AddrMode.Scale = 1;
2026     AddrMode.ScaledReg = Addr;
2027     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
2028       return true;
2029     AddrMode.Scale = 0;
2030     AddrMode.ScaledReg = 0;
2031   }
2032   // Couldn't match.
2033   TPT.rollback(LastKnownGood);
2034   return false;
2035 }
2036
2037 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
2038 /// inline asm call are due to memory operands.  If so, return true, otherwise
2039 /// return false.
2040 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
2041                                     const TargetLowering &TLI) {
2042   TargetLowering::AsmOperandInfoVector TargetConstraints = TLI.ParseConstraints(ImmutableCallSite(CI));
2043   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2044     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2045
2046     // Compute the constraint code and ConstraintType to use.
2047     TLI.ComputeConstraintToUse(OpInfo, SDValue());
2048
2049     // If this asm operand is our Value*, and if it isn't an indirect memory
2050     // operand, we can't fold it!
2051     if (OpInfo.CallOperandVal == OpVal &&
2052         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
2053          !OpInfo.isIndirect))
2054       return false;
2055   }
2056
2057   return true;
2058 }
2059
2060 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
2061 /// memory use.  If we find an obviously non-foldable instruction, return true.
2062 /// Add the ultimately found memory instructions to MemoryUses.
2063 static bool FindAllMemoryUses(Instruction *I,
2064                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
2065                               SmallPtrSet<Instruction*, 16> &ConsideredInsts,
2066                               const TargetLowering &TLI) {
2067   // If we already considered this instruction, we're done.
2068   if (!ConsideredInsts.insert(I))
2069     return false;
2070
2071   // If this is an obviously unfoldable instruction, bail out.
2072   if (!MightBeFoldableInst(I))
2073     return true;
2074
2075   // Loop over all the uses, recursively processing them.
2076   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2077        UI != E; ++UI) {
2078     User *U = *UI;
2079
2080     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
2081       MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
2082       continue;
2083     }
2084
2085     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
2086       unsigned opNo = UI.getOperandNo();
2087       if (opNo == 0) return true; // Storing addr, not into addr.
2088       MemoryUses.push_back(std::make_pair(SI, opNo));
2089       continue;
2090     }
2091
2092     if (CallInst *CI = dyn_cast<CallInst>(U)) {
2093       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
2094       if (!IA) return true;
2095
2096       // If this is a memory operand, we're cool, otherwise bail out.
2097       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
2098         return true;
2099       continue;
2100     }
2101
2102     if (FindAllMemoryUses(cast<Instruction>(U), MemoryUses, ConsideredInsts,
2103                           TLI))
2104       return true;
2105   }
2106
2107   return false;
2108 }
2109
2110 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
2111 /// the use site that we're folding it into.  If so, there is no cost to
2112 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
2113 /// that we know are live at the instruction already.
2114 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
2115                                                    Value *KnownLive2) {
2116   // If Val is either of the known-live values, we know it is live!
2117   if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
2118     return true;
2119
2120   // All values other than instructions and arguments (e.g. constants) are live.
2121   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
2122
2123   // If Val is a constant sized alloca in the entry block, it is live, this is
2124   // true because it is just a reference to the stack/frame pointer, which is
2125   // live for the whole function.
2126   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
2127     if (AI->isStaticAlloca())
2128       return true;
2129
2130   // Check to see if this value is already used in the memory instruction's
2131   // block.  If so, it's already live into the block at the very least, so we
2132   // can reasonably fold it.
2133   return Val->isUsedInBasicBlock(MemoryInst->getParent());
2134 }
2135
2136 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
2137 /// mode of the machine to fold the specified instruction into a load or store
2138 /// that ultimately uses it.  However, the specified instruction has multiple
2139 /// uses.  Given this, it may actually increase register pressure to fold it
2140 /// into the load.  For example, consider this code:
2141 ///
2142 ///     X = ...
2143 ///     Y = X+1
2144 ///     use(Y)   -> nonload/store
2145 ///     Z = Y+1
2146 ///     load Z
2147 ///
2148 /// In this case, Y has multiple uses, and can be folded into the load of Z
2149 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
2150 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
2151 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
2152 /// number of computations either.
2153 ///
2154 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
2155 /// X was live across 'load Z' for other reasons, we actually *would* want to
2156 /// fold the addressing mode in the Z case.  This would make Y die earlier.
2157 bool AddressingModeMatcher::
2158 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
2159                                      ExtAddrMode &AMAfter) {
2160   if (IgnoreProfitability) return true;
2161
2162   // AMBefore is the addressing mode before this instruction was folded into it,
2163   // and AMAfter is the addressing mode after the instruction was folded.  Get
2164   // the set of registers referenced by AMAfter and subtract out those
2165   // referenced by AMBefore: this is the set of values which folding in this
2166   // address extends the lifetime of.
2167   //
2168   // Note that there are only two potential values being referenced here,
2169   // BaseReg and ScaleReg (global addresses are always available, as are any
2170   // folded immediates).
2171   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
2172
2173   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
2174   // lifetime wasn't extended by adding this instruction.
2175   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2176     BaseReg = 0;
2177   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
2178     ScaledReg = 0;
2179
2180   // If folding this instruction (and it's subexprs) didn't extend any live
2181   // ranges, we're ok with it.
2182   if (BaseReg == 0 && ScaledReg == 0)
2183     return true;
2184
2185   // If all uses of this instruction are ultimately load/store/inlineasm's,
2186   // check to see if their addressing modes will include this instruction.  If
2187   // so, we can fold it into all uses, so it doesn't matter if it has multiple
2188   // uses.
2189   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
2190   SmallPtrSet<Instruction*, 16> ConsideredInsts;
2191   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
2192     return false;  // Has a non-memory, non-foldable use!
2193
2194   // Now that we know that all uses of this instruction are part of a chain of
2195   // computation involving only operations that could theoretically be folded
2196   // into a memory use, loop over each of these uses and see if they could
2197   // *actually* fold the instruction.
2198   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
2199   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
2200     Instruction *User = MemoryUses[i].first;
2201     unsigned OpNo = MemoryUses[i].second;
2202
2203     // Get the access type of this use.  If the use isn't a pointer, we don't
2204     // know what it accesses.
2205     Value *Address = User->getOperand(OpNo);
2206     if (!Address->getType()->isPointerTy())
2207       return false;
2208     Type *AddressAccessTy = Address->getType()->getPointerElementType();
2209
2210     // Do a match against the root of this address, ignoring profitability. This
2211     // will tell us if the addressing mode for the memory operation will
2212     // *actually* cover the shared instruction.
2213     ExtAddrMode Result;
2214     TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2215         TPT.getRestorationPoint();
2216     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
2217                                   MemoryInst, Result, InsertedTruncs,
2218                                   PromotedInsts, TPT);
2219     Matcher.IgnoreProfitability = true;
2220     bool Success = Matcher.MatchAddr(Address, 0);
2221     (void)Success; assert(Success && "Couldn't select *anything*?");
2222
2223     // The match was to check the profitability, the changes made are not
2224     // part of the original matcher. Therefore, they should be dropped
2225     // otherwise the original matcher will not present the right state.
2226     TPT.rollback(LastKnownGood);
2227
2228     // If the match didn't cover I, then it won't be shared by it.
2229     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
2230                   I) == MatchedAddrModeInsts.end())
2231       return false;
2232
2233     MatchedAddrModeInsts.clear();
2234   }
2235
2236   return true;
2237 }
2238
2239 } // end anonymous namespace
2240
2241 /// IsNonLocalValue - Return true if the specified values are defined in a
2242 /// different basic block than BB.
2243 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
2244   if (Instruction *I = dyn_cast<Instruction>(V))
2245     return I->getParent() != BB;
2246   return false;
2247 }
2248
2249 /// OptimizeMemoryInst - Load and Store Instructions often have
2250 /// addressing modes that can do significant amounts of computation.  As such,
2251 /// instruction selection will try to get the load or store to do as much
2252 /// computation as possible for the program.  The problem is that isel can only
2253 /// see within a single block.  As such, we sink as much legal addressing mode
2254 /// stuff into the block as possible.
2255 ///
2256 /// This method is used to optimize both load/store and inline asms with memory
2257 /// operands.
2258 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
2259                                         Type *AccessTy) {
2260   Value *Repl = Addr;
2261
2262   // Try to collapse single-value PHI nodes.  This is necessary to undo
2263   // unprofitable PRE transformations.
2264   SmallVector<Value*, 8> worklist;
2265   SmallPtrSet<Value*, 16> Visited;
2266   worklist.push_back(Addr);
2267
2268   // Use a worklist to iteratively look through PHI nodes, and ensure that
2269   // the addressing mode obtained from the non-PHI roots of the graph
2270   // are equivalent.
2271   Value *Consensus = 0;
2272   unsigned NumUsesConsensus = 0;
2273   bool IsNumUsesConsensusValid = false;
2274   SmallVector<Instruction*, 16> AddrModeInsts;
2275   ExtAddrMode AddrMode;
2276   TypePromotionTransaction TPT;
2277   TypePromotionTransaction::ConstRestorationPt LastKnownGood =
2278       TPT.getRestorationPoint();
2279   while (!worklist.empty()) {
2280     Value *V = worklist.back();
2281     worklist.pop_back();
2282
2283     // Break use-def graph loops.
2284     if (!Visited.insert(V)) {
2285       Consensus = 0;
2286       break;
2287     }
2288
2289     // For a PHI node, push all of its incoming values.
2290     if (PHINode *P = dyn_cast<PHINode>(V)) {
2291       for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
2292         worklist.push_back(P->getIncomingValue(i));
2293       continue;
2294     }
2295
2296     // For non-PHIs, determine the addressing mode being computed.
2297     SmallVector<Instruction*, 16> NewAddrModeInsts;
2298     ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
2299         V, AccessTy, MemoryInst, NewAddrModeInsts, *TLI, InsertedTruncsSet,
2300         PromotedInsts, TPT);
2301
2302     // This check is broken into two cases with very similar code to avoid using
2303     // getNumUses() as much as possible. Some values have a lot of uses, so
2304     // calling getNumUses() unconditionally caused a significant compile-time
2305     // regression.
2306     if (!Consensus) {
2307       Consensus = V;
2308       AddrMode = NewAddrMode;
2309       AddrModeInsts = NewAddrModeInsts;
2310       continue;
2311     } else if (NewAddrMode == AddrMode) {
2312       if (!IsNumUsesConsensusValid) {
2313         NumUsesConsensus = Consensus->getNumUses();
2314         IsNumUsesConsensusValid = true;
2315       }
2316
2317       // Ensure that the obtained addressing mode is equivalent to that obtained
2318       // for all other roots of the PHI traversal.  Also, when choosing one
2319       // such root as representative, select the one with the most uses in order
2320       // to keep the cost modeling heuristics in AddressingModeMatcher
2321       // applicable.
2322       unsigned NumUses = V->getNumUses();
2323       if (NumUses > NumUsesConsensus) {
2324         Consensus = V;
2325         NumUsesConsensus = NumUses;
2326         AddrModeInsts = NewAddrModeInsts;
2327       }
2328       continue;
2329     }
2330
2331     Consensus = 0;
2332     break;
2333   }
2334
2335   // If the addressing mode couldn't be determined, or if multiple different
2336   // ones were determined, bail out now.
2337   if (!Consensus) {
2338     TPT.rollback(LastKnownGood);
2339     return false;
2340   }
2341   TPT.commit();
2342
2343   // Check to see if any of the instructions supersumed by this addr mode are
2344   // non-local to I's BB.
2345   bool AnyNonLocal = false;
2346   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
2347     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
2348       AnyNonLocal = true;
2349       break;
2350     }
2351   }
2352
2353   // If all the instructions matched are already in this BB, don't do anything.
2354   if (!AnyNonLocal) {
2355     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
2356     return false;
2357   }
2358
2359   // Insert this computation right after this user.  Since our caller is
2360   // scanning from the top of the BB to the bottom, reuse of the expr are
2361   // guaranteed to happen later.
2362   IRBuilder<> Builder(MemoryInst);
2363
2364   // Now that we determined the addressing expression we want to use and know
2365   // that we have to sink it into this block.  Check to see if we have already
2366   // done this for some other load/store instr in this block.  If so, reuse the
2367   // computation.
2368   Value *&SunkAddr = SunkAddrs[Addr];
2369   if (SunkAddr) {
2370     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
2371                  << *MemoryInst);
2372     if (SunkAddr->getType() != Addr->getType())
2373       SunkAddr = Builder.CreateBitCast(SunkAddr, Addr->getType());
2374   } else {
2375     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
2376                  << *MemoryInst);
2377     Type *IntPtrTy = TLI->getDataLayout()->getIntPtrType(Addr->getType());
2378     Value *Result = 0;
2379
2380     // Start with the base register. Do this first so that subsequent address
2381     // matching finds it last, which will prevent it from trying to match it
2382     // as the scaled value in case it happens to be a mul. That would be
2383     // problematic if we've sunk a different mul for the scale, because then
2384     // we'd end up sinking both muls.
2385     if (AddrMode.BaseReg) {
2386       Value *V = AddrMode.BaseReg;
2387       if (V->getType()->isPointerTy())
2388         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2389       if (V->getType() != IntPtrTy)
2390         V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
2391       Result = V;
2392     }
2393
2394     // Add the scale value.
2395     if (AddrMode.Scale) {
2396       Value *V = AddrMode.ScaledReg;
2397       if (V->getType() == IntPtrTy) {
2398         // done.
2399       } else if (V->getType()->isPointerTy()) {
2400         V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
2401       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
2402                  cast<IntegerType>(V->getType())->getBitWidth()) {
2403         V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
2404       } else {
2405         V = Builder.CreateSExt(V, IntPtrTy, "sunkaddr");
2406       }
2407       if (AddrMode.Scale != 1)
2408         V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
2409                               "sunkaddr");
2410       if (Result)
2411         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2412       else
2413         Result = V;
2414     }
2415
2416     // Add in the BaseGV if present.
2417     if (AddrMode.BaseGV) {
2418       Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
2419       if (Result)
2420         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2421       else
2422         Result = V;
2423     }
2424
2425     // Add in the Base Offset if present.
2426     if (AddrMode.BaseOffs) {
2427       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
2428       if (Result)
2429         Result = Builder.CreateAdd(Result, V, "sunkaddr");
2430       else
2431         Result = V;
2432     }
2433
2434     if (Result == 0)
2435       SunkAddr = Constant::getNullValue(Addr->getType());
2436     else
2437       SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
2438   }
2439
2440   MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
2441
2442   // If we have no uses, recursively delete the value and all dead instructions
2443   // using it.
2444   if (Repl->use_empty()) {
2445     // This can cause recursive deletion, which can invalidate our iterator.
2446     // Use a WeakVH to hold onto it in case this happens.
2447     WeakVH IterHandle(CurInstIterator);
2448     BasicBlock *BB = CurInstIterator->getParent();
2449
2450     RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
2451
2452     if (IterHandle != CurInstIterator) {
2453       // If the iterator instruction was recursively deleted, start over at the
2454       // start of the block.
2455       CurInstIterator = BB->begin();
2456       SunkAddrs.clear();
2457     }
2458   }
2459   ++NumMemoryInsts;
2460   return true;
2461 }
2462
2463 /// OptimizeInlineAsmInst - If there are any memory operands, use
2464 /// OptimizeMemoryInst to sink their address computing into the block when
2465 /// possible / profitable.
2466 bool CodeGenPrepare::OptimizeInlineAsmInst(CallInst *CS) {
2467   bool MadeChange = false;
2468
2469   TargetLowering::AsmOperandInfoVector
2470     TargetConstraints = TLI->ParseConstraints(CS);
2471   unsigned ArgNo = 0;
2472   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
2473     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
2474
2475     // Compute the constraint code and ConstraintType to use.
2476     TLI->ComputeConstraintToUse(OpInfo, SDValue());
2477
2478     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
2479         OpInfo.isIndirect) {
2480       Value *OpVal = CS->getArgOperand(ArgNo++);
2481       MadeChange |= OptimizeMemoryInst(CS, OpVal, OpVal->getType());
2482     } else if (OpInfo.Type == InlineAsm::isInput)
2483       ArgNo++;
2484   }
2485
2486   return MadeChange;
2487 }
2488
2489 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
2490 /// basic block as the load, unless conditions are unfavorable. This allows
2491 /// SelectionDAG to fold the extend into the load.
2492 ///
2493 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
2494   // Look for a load being extended.
2495   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
2496   if (!LI) return false;
2497
2498   // If they're already in the same block, there's nothing to do.
2499   if (LI->getParent() == I->getParent())
2500     return false;
2501
2502   // If the load has other users and the truncate is not free, this probably
2503   // isn't worthwhile.
2504   if (!LI->hasOneUse() &&
2505       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
2506               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
2507       !TLI->isTruncateFree(I->getType(), LI->getType()))
2508     return false;
2509
2510   // Check whether the target supports casts folded into loads.
2511   unsigned LType;
2512   if (isa<ZExtInst>(I))
2513     LType = ISD::ZEXTLOAD;
2514   else {
2515     assert(isa<SExtInst>(I) && "Unexpected ext type!");
2516     LType = ISD::SEXTLOAD;
2517   }
2518   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
2519     return false;
2520
2521   // Move the extend into the same block as the load, so that SelectionDAG
2522   // can fold it.
2523   I->removeFromParent();
2524   I->insertAfter(LI);
2525   ++NumExtsMoved;
2526   return true;
2527 }
2528
2529 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
2530   BasicBlock *DefBB = I->getParent();
2531
2532   // If the result of a {s|z}ext and its source are both live out, rewrite all
2533   // other uses of the source with result of extension.
2534   Value *Src = I->getOperand(0);
2535   if (Src->hasOneUse())
2536     return false;
2537
2538   // Only do this xform if truncating is free.
2539   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
2540     return false;
2541
2542   // Only safe to perform the optimization if the source is also defined in
2543   // this block.
2544   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
2545     return false;
2546
2547   bool DefIsLiveOut = false;
2548   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
2549        UI != E; ++UI) {
2550     Instruction *User = cast<Instruction>(*UI);
2551
2552     // Figure out which BB this ext is used in.
2553     BasicBlock *UserBB = User->getParent();
2554     if (UserBB == DefBB) continue;
2555     DefIsLiveOut = true;
2556     break;
2557   }
2558   if (!DefIsLiveOut)
2559     return false;
2560
2561   // Make sure none of the uses are PHI nodes.
2562   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
2563        UI != E; ++UI) {
2564     Instruction *User = cast<Instruction>(*UI);
2565     BasicBlock *UserBB = User->getParent();
2566     if (UserBB == DefBB) continue;
2567     // Be conservative. We don't want this xform to end up introducing
2568     // reloads just before load / store instructions.
2569     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
2570       return false;
2571   }
2572
2573   // InsertedTruncs - Only insert one trunc in each block once.
2574   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
2575
2576   bool MadeChange = false;
2577   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
2578        UI != E; ++UI) {
2579     Use &TheUse = UI.getUse();
2580     Instruction *User = cast<Instruction>(*UI);
2581
2582     // Figure out which BB this ext is used in.
2583     BasicBlock *UserBB = User->getParent();
2584     if (UserBB == DefBB) continue;
2585
2586     // Both src and def are live in this block. Rewrite the use.
2587     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
2588
2589     if (!InsertedTrunc) {
2590       BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
2591       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
2592       InsertedTruncsSet.insert(InsertedTrunc);
2593     }
2594
2595     // Replace a use of the {s|z}ext source with a use of the result.
2596     TheUse = InsertedTrunc;
2597     ++NumExtUses;
2598     MadeChange = true;
2599   }
2600
2601   return MadeChange;
2602 }
2603
2604 /// isFormingBranchFromSelectProfitable - Returns true if a SelectInst should be
2605 /// turned into an explicit branch.
2606 static bool isFormingBranchFromSelectProfitable(SelectInst *SI) {
2607   // FIXME: This should use the same heuristics as IfConversion to determine
2608   // whether a select is better represented as a branch.  This requires that
2609   // branch probability metadata is preserved for the select, which is not the
2610   // case currently.
2611
2612   CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
2613
2614   // If the branch is predicted right, an out of order CPU can avoid blocking on
2615   // the compare.  Emit cmovs on compares with a memory operand as branches to
2616   // avoid stalls on the load from memory.  If the compare has more than one use
2617   // there's probably another cmov or setcc around so it's not worth emitting a
2618   // branch.
2619   if (!Cmp)
2620     return false;
2621
2622   Value *CmpOp0 = Cmp->getOperand(0);
2623   Value *CmpOp1 = Cmp->getOperand(1);
2624
2625   // We check that the memory operand has one use to avoid uses of the loaded
2626   // value directly after the compare, making branches unprofitable.
2627   return Cmp->hasOneUse() &&
2628          ((isa<LoadInst>(CmpOp0) && CmpOp0->hasOneUse()) ||
2629           (isa<LoadInst>(CmpOp1) && CmpOp1->hasOneUse()));
2630 }
2631
2632
2633 /// If we have a SelectInst that will likely profit from branch prediction,
2634 /// turn it into a branch.
2635 bool CodeGenPrepare::OptimizeSelectInst(SelectInst *SI) {
2636   bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
2637
2638   // Can we convert the 'select' to CF ?
2639   if (DisableSelectToBranch || OptSize || !TLI || VectorCond)
2640     return false;
2641
2642   TargetLowering::SelectSupportKind SelectKind;
2643   if (VectorCond)
2644     SelectKind = TargetLowering::VectorMaskSelect;
2645   else if (SI->getType()->isVectorTy())
2646     SelectKind = TargetLowering::ScalarCondVectorVal;
2647   else
2648     SelectKind = TargetLowering::ScalarValSelect;
2649
2650   // Do we have efficient codegen support for this kind of 'selects' ?
2651   if (TLI->isSelectSupported(SelectKind)) {
2652     // We have efficient codegen support for the select instruction.
2653     // Check if it is profitable to keep this 'select'.
2654     if (!TLI->isPredictableSelectExpensive() ||
2655         !isFormingBranchFromSelectProfitable(SI))
2656       return false;
2657   }
2658
2659   ModifiedDT = true;
2660
2661   // First, we split the block containing the select into 2 blocks.
2662   BasicBlock *StartBlock = SI->getParent();
2663   BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(SI));
2664   BasicBlock *NextBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
2665
2666   // Create a new block serving as the landing pad for the branch.
2667   BasicBlock *SmallBlock = BasicBlock::Create(SI->getContext(), "select.mid",
2668                                              NextBlock->getParent(), NextBlock);
2669
2670   // Move the unconditional branch from the block with the select in it into our
2671   // landing pad block.
2672   StartBlock->getTerminator()->eraseFromParent();
2673   BranchInst::Create(NextBlock, SmallBlock);
2674
2675   // Insert the real conditional branch based on the original condition.
2676   BranchInst::Create(NextBlock, SmallBlock, SI->getCondition(), SI);
2677
2678   // The select itself is replaced with a PHI Node.
2679   PHINode *PN = PHINode::Create(SI->getType(), 2, "", NextBlock->begin());
2680   PN->takeName(SI);
2681   PN->addIncoming(SI->getTrueValue(), StartBlock);
2682   PN->addIncoming(SI->getFalseValue(), SmallBlock);
2683   SI->replaceAllUsesWith(PN);
2684   SI->eraseFromParent();
2685
2686   // Instruct OptimizeBlock to skip to the next block.
2687   CurInstIterator = StartBlock->end();
2688   ++NumSelectsExpanded;
2689   return true;
2690 }
2691
2692 bool CodeGenPrepare::OptimizeInst(Instruction *I) {
2693   if (PHINode *P = dyn_cast<PHINode>(I)) {
2694     // It is possible for very late stage optimizations (such as SimplifyCFG)
2695     // to introduce PHI nodes too late to be cleaned up.  If we detect such a
2696     // trivial PHI, go ahead and zap it here.
2697     if (Value *V = SimplifyInstruction(P, TLI ? TLI->getDataLayout() : 0,
2698                                        TLInfo, DT)) {
2699       P->replaceAllUsesWith(V);
2700       P->eraseFromParent();
2701       ++NumPHIsElim;
2702       return true;
2703     }
2704     return false;
2705   }
2706
2707   if (CastInst *CI = dyn_cast<CastInst>(I)) {
2708     // If the source of the cast is a constant, then this should have
2709     // already been constant folded.  The only reason NOT to constant fold
2710     // it is if something (e.g. LSR) was careful to place the constant
2711     // evaluation in a block other than then one that uses it (e.g. to hoist
2712     // the address of globals out of a loop).  If this is the case, we don't
2713     // want to forward-subst the cast.
2714     if (isa<Constant>(CI->getOperand(0)))
2715       return false;
2716
2717     if (TLI && OptimizeNoopCopyExpression(CI, *TLI))
2718       return true;
2719
2720     if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
2721       bool MadeChange = MoveExtToFormExtLoad(I);
2722       return MadeChange | OptimizeExtUses(I);
2723     }
2724     return false;
2725   }
2726
2727   if (CmpInst *CI = dyn_cast<CmpInst>(I))
2728     if (!TLI || !TLI->hasMultipleConditionRegisters())
2729       return OptimizeCmpExpression(CI);
2730
2731   if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
2732     if (TLI)
2733       return OptimizeMemoryInst(I, I->getOperand(0), LI->getType());
2734     return false;
2735   }
2736
2737   if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
2738     if (TLI)
2739       return OptimizeMemoryInst(I, SI->getOperand(1),
2740                                 SI->getOperand(0)->getType());
2741     return false;
2742   }
2743
2744   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
2745     if (GEPI->hasAllZeroIndices()) {
2746       /// The GEP operand must be a pointer, so must its result -> BitCast
2747       Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
2748                                         GEPI->getName(), GEPI);
2749       GEPI->replaceAllUsesWith(NC);
2750       GEPI->eraseFromParent();
2751       ++NumGEPsElim;
2752       OptimizeInst(NC);
2753       return true;
2754     }
2755     return false;
2756   }
2757
2758   if (CallInst *CI = dyn_cast<CallInst>(I))
2759     return OptimizeCallInst(CI);
2760
2761   if (SelectInst *SI = dyn_cast<SelectInst>(I))
2762     return OptimizeSelectInst(SI);
2763
2764   return false;
2765 }
2766
2767 // In this pass we look for GEP and cast instructions that are used
2768 // across basic blocks and rewrite them to improve basic-block-at-a-time
2769 // selection.
2770 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
2771   SunkAddrs.clear();
2772   bool MadeChange = false;
2773
2774   CurInstIterator = BB.begin();
2775   while (CurInstIterator != BB.end())
2776     MadeChange |= OptimizeInst(CurInstIterator++);
2777
2778   MadeChange |= DupRetToEnableTailCallOpts(&BB);
2779
2780   return MadeChange;
2781 }
2782
2783 // llvm.dbg.value is far away from the value then iSel may not be able
2784 // handle it properly. iSel will drop llvm.dbg.value if it can not
2785 // find a node corresponding to the value.
2786 bool CodeGenPrepare::PlaceDbgValues(Function &F) {
2787   bool MadeChange = false;
2788   for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
2789     Instruction *PrevNonDbgInst = NULL;
2790     for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE;) {
2791       Instruction *Insn = BI; ++BI;
2792       DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
2793       if (!DVI) {
2794         PrevNonDbgInst = Insn;
2795         continue;
2796       }
2797
2798       Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
2799       if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
2800         DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
2801         DVI->removeFromParent();
2802         if (isa<PHINode>(VI))
2803           DVI->insertBefore(VI->getParent()->getFirstInsertionPt());
2804         else
2805           DVI->insertAfter(VI);
2806         MadeChange = true;
2807         ++NumDbgValueMoved;
2808       }
2809     }
2810   }
2811   return MadeChange;
2812 }