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