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