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