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