880a4e5eb890551e6144e146937f52a329c6afd5
[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/InlineAsm.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/IntrinsicInst.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/ProfileInfo.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Transforms/Utils/AddrModeMatcher.h"
29 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
30 #include "llvm/Transforms/Utils/Local.h"
31 #include "llvm/Transforms/Utils/BuildLibCalls.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/SmallSet.h"
34 #include "llvm/ADT/Statistic.h"
35 #include "llvm/Assembly/Writer.h"
36 #include "llvm/Support/CallSite.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/GetElementPtrTypeIterator.h"
40 #include "llvm/Support/PatternMatch.h"
41 #include "llvm/Support/raw_ostream.h"
42 #include "llvm/Support/IRBuilder.h"
43 using namespace llvm;
44 using namespace llvm::PatternMatch;
45
46 STATISTIC(NumElim,  "Number of blocks eliminated");
47
48 static cl::opt<bool>
49 CriticalEdgeSplit("cgp-critical-edge-splitting",
50                   cl::desc("Split critical edges during codegen prepare"),
51                   cl::init(false), cl::Hidden);
52
53 namespace {
54   class CodeGenPrepare : public FunctionPass {
55     /// TLI - Keep a pointer of a TargetLowering to consult for determining
56     /// transformation profitability.
57     const TargetLowering *TLI;
58     ProfileInfo *PFI;
59
60     /// BackEdges - Keep a set of all the loop back edges.
61     ///
62     SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
63   public:
64     static char ID; // Pass identification, replacement for typeid
65     explicit CodeGenPrepare(const TargetLowering *tli = 0)
66       : FunctionPass(ID), TLI(tli) {}
67     bool runOnFunction(Function &F);
68
69     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70       AU.addPreserved<ProfileInfo>();
71     }
72
73     virtual void releaseMemory() {
74       BackEdges.clear();
75     }
76
77   private:
78     bool EliminateMostlyEmptyBlocks(Function &F);
79     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
80     void EliminateMostlyEmptyBlock(BasicBlock *BB);
81     bool OptimizeBlock(BasicBlock &BB);
82     bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
83                             DenseMap<Value*,Value*> &SunkAddrs);
84     bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
85                                DenseMap<Value*,Value*> &SunkAddrs);
86     bool OptimizeCallInst(CallInst *CI);
87     bool MoveExtToFormExtLoad(Instruction *I);
88     bool OptimizeExtUses(Instruction *I);
89     void findLoopBackEdges(const Function &F);
90   };
91 }
92
93 char CodeGenPrepare::ID = 0;
94 INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
95                 "Optimize for code generation", false, false);
96
97 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
98   return new CodeGenPrepare(TLI);
99 }
100
101 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
102 ///
103 void CodeGenPrepare::findLoopBackEdges(const Function &F) {
104   SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
105   FindFunctionBackedges(F, Edges);
106   
107   BackEdges.insert(Edges.begin(), Edges.end());
108 }
109
110
111 bool CodeGenPrepare::runOnFunction(Function &F) {
112   bool EverMadeChange = false;
113
114   PFI = getAnalysisIfAvailable<ProfileInfo>();
115   // First pass, eliminate blocks that contain only PHI nodes and an
116   // unconditional branch.
117   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
118
119   // Now find loop back edges.
120   findLoopBackEdges(F);
121
122   bool MadeChange = true;
123   while (MadeChange) {
124     MadeChange = false;
125     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
126       MadeChange |= OptimizeBlock(*BB);
127     EverMadeChange |= MadeChange;
128   }
129   return EverMadeChange;
130 }
131
132 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
133 /// debug info directives, and an unconditional branch.  Passes before isel
134 /// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
135 /// isel.  Start by eliminating these blocks so we can split them the way we
136 /// want them.
137 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
138   bool MadeChange = false;
139   // Note that this intentionally skips the entry block.
140   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
141     BasicBlock *BB = I++;
142
143     // If this block doesn't end with an uncond branch, ignore it.
144     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
145     if (!BI || !BI->isUnconditional())
146       continue;
147
148     // If the instruction before the branch (skipping debug info) isn't a phi
149     // node, then other stuff is happening here.
150     BasicBlock::iterator BBI = BI;
151     if (BBI != BB->begin()) {
152       --BBI;
153       while (isa<DbgInfoIntrinsic>(BBI)) {
154         if (BBI == BB->begin())
155           break;
156         --BBI;
157       }
158       if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
159         continue;
160     }
161
162     // Do not break infinite loops.
163     BasicBlock *DestBB = BI->getSuccessor(0);
164     if (DestBB == BB)
165       continue;
166
167     if (!CanMergeBlocks(BB, DestBB))
168       continue;
169
170     EliminateMostlyEmptyBlock(BB);
171     MadeChange = true;
172   }
173   return MadeChange;
174 }
175
176 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
177 /// single uncond branch between them, and BB contains no other non-phi
178 /// instructions.
179 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
180                                     const BasicBlock *DestBB) const {
181   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
182   // the successor.  If there are more complex condition (e.g. preheaders),
183   // don't mess around with them.
184   BasicBlock::const_iterator BBI = BB->begin();
185   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
186     for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
187          UI != E; ++UI) {
188       const Instruction *User = cast<Instruction>(*UI);
189       if (User->getParent() != DestBB || !isa<PHINode>(User))
190         return false;
191       // If User is inside DestBB block and it is a PHINode then check
192       // incoming value. If incoming value is not from BB then this is
193       // a complex condition (e.g. preheaders) we want to avoid here.
194       if (User->getParent() == DestBB) {
195         if (const PHINode *UPN = dyn_cast<PHINode>(User))
196           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
197             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
198             if (Insn && Insn->getParent() == BB &&
199                 Insn->getParent() != UPN->getIncomingBlock(I))
200               return false;
201           }
202       }
203     }
204   }
205
206   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
207   // and DestBB may have conflicting incoming values for the block.  If so, we
208   // can't merge the block.
209   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
210   if (!DestBBPN) return true;  // no conflict.
211
212   // Collect the preds of BB.
213   SmallPtrSet<const BasicBlock*, 16> BBPreds;
214   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
215     // It is faster to get preds from a PHI than with pred_iterator.
216     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
217       BBPreds.insert(BBPN->getIncomingBlock(i));
218   } else {
219     BBPreds.insert(pred_begin(BB), pred_end(BB));
220   }
221
222   // Walk the preds of DestBB.
223   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
224     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
225     if (BBPreds.count(Pred)) {   // Common predecessor?
226       BBI = DestBB->begin();
227       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
228         const Value *V1 = PN->getIncomingValueForBlock(Pred);
229         const Value *V2 = PN->getIncomingValueForBlock(BB);
230
231         // If V2 is a phi node in BB, look up what the mapped value will be.
232         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
233           if (V2PN->getParent() == BB)
234             V2 = V2PN->getIncomingValueForBlock(Pred);
235
236         // If there is a conflict, bail out.
237         if (V1 != V2) return false;
238       }
239     }
240   }
241
242   return true;
243 }
244
245
246 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
247 /// an unconditional branch in it.
248 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
249   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
250   BasicBlock *DestBB = BI->getSuccessor(0);
251
252   DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
253
254   // If the destination block has a single pred, then this is a trivial edge,
255   // just collapse it.
256   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
257     if (SinglePred != DestBB) {
258       // Remember if SinglePred was the entry block of the function.  If so, we
259       // will need to move BB back to the entry position.
260       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
261       MergeBasicBlockIntoOnlyPred(DestBB, this);
262
263       if (isEntry && BB != &BB->getParent()->getEntryBlock())
264         BB->moveBefore(&BB->getParent()->getEntryBlock());
265       
266       DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
267       return;
268     }
269   }
270
271   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
272   // to handle the new incoming edges it is about to have.
273   PHINode *PN;
274   for (BasicBlock::iterator BBI = DestBB->begin();
275        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
276     // Remove the incoming value for BB, and remember it.
277     Value *InVal = PN->removeIncomingValue(BB, false);
278
279     // Two options: either the InVal is a phi node defined in BB or it is some
280     // value that dominates BB.
281     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
282     if (InValPhi && InValPhi->getParent() == BB) {
283       // Add all of the input values of the input PHI as inputs of this phi.
284       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
285         PN->addIncoming(InValPhi->getIncomingValue(i),
286                         InValPhi->getIncomingBlock(i));
287     } else {
288       // Otherwise, add one instance of the dominating value for each edge that
289       // we will be adding.
290       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
291         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
292           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
293       } else {
294         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
295           PN->addIncoming(InVal, *PI);
296       }
297     }
298   }
299
300   // The PHIs are now updated, change everything that refers to BB to use
301   // DestBB and remove BB.
302   BB->replaceAllUsesWith(DestBB);
303   if (PFI) {
304     PFI->replaceAllUses(BB, DestBB);
305     PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
306   }
307   BB->eraseFromParent();
308   ++NumElim;
309
310   DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
311 }
312
313 /// FindReusablePredBB - Check all of the predecessors of the block DestPHI
314 /// lives in to see if there is a block that we can reuse as a critical edge
315 /// from TIBB.
316 static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
317   BasicBlock *Dest = DestPHI->getParent();
318   
319   /// TIPHIValues - This array is lazily computed to determine the values of
320   /// PHIs in Dest that TI would provide.
321   SmallVector<Value*, 32> TIPHIValues;
322   
323   /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
324   unsigned TIBBEntryNo = 0;
325   
326   // Check to see if Dest has any blocks that can be used as a split edge for
327   // this terminator.
328   for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
329     BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
330     // To be usable, the pred has to end with an uncond branch to the dest.
331     BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
332     if (!PredBr || !PredBr->isUnconditional())
333       continue;
334     // Must be empty other than the branch and debug info.
335     BasicBlock::iterator I = Pred->begin();
336     while (isa<DbgInfoIntrinsic>(I))
337       I++;
338     if (&*I != PredBr)
339       continue;
340     // Cannot be the entry block; its label does not get emitted.
341     if (Pred == &Dest->getParent()->getEntryBlock())
342       continue;
343     
344     // Finally, since we know that Dest has phi nodes in it, we have to make
345     // sure that jumping to Pred will have the same effect as going to Dest in
346     // terms of PHI values.
347     PHINode *PN;
348     unsigned PHINo = 0;
349     unsigned PredEntryNo = pi;
350     
351     bool FoundMatch = true;
352     for (BasicBlock::iterator I = Dest->begin();
353          (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
354       if (PHINo == TIPHIValues.size()) {
355         if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
356           TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
357         TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
358       }
359       
360       // If the PHI entry doesn't work, we can't use this pred.
361       if (PN->getIncomingBlock(PredEntryNo) != Pred)
362         PredEntryNo = PN->getBasicBlockIndex(Pred);
363       
364       if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
365         FoundMatch = false;
366         break;
367       }
368     }
369     
370     // If we found a workable predecessor, change TI to branch to Succ.
371     if (FoundMatch)
372       return Pred;
373   }
374   return 0;  
375 }
376
377
378 /// SplitEdgeNicely - Split the critical edge from TI to its specified
379 /// successor if it will improve codegen.  We only do this if the successor has
380 /// phi nodes (otherwise critical edges are ok).  If there is already another
381 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
382 /// instead of introducing a new block.
383 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
384                      SmallSet<std::pair<const BasicBlock*,
385                                         const BasicBlock*>, 8> &BackEdges,
386                              Pass *P) {
387   BasicBlock *TIBB = TI->getParent();
388   BasicBlock *Dest = TI->getSuccessor(SuccNum);
389   assert(isa<PHINode>(Dest->begin()) &&
390          "This should only be called if Dest has a PHI!");
391   PHINode *DestPHI = cast<PHINode>(Dest->begin());
392
393   // Do not split edges to EH landing pads.
394   if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
395     if (Invoke->getSuccessor(1) == Dest)
396       return;
397
398   // As a hack, never split backedges of loops.  Even though the copy for any
399   // PHIs inserted on the backedge would be dead for exits from the loop, we
400   // assume that the cost of *splitting* the backedge would be too high.
401   if (BackEdges.count(std::make_pair(TIBB, Dest)))
402     return;
403
404   if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
405     ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
406     if (PFI)
407       PFI->splitEdge(TIBB, Dest, ReuseBB);
408     Dest->removePredecessor(TIBB);
409     TI->setSuccessor(SuccNum, ReuseBB);
410     return;
411   }
412
413   SplitCriticalEdge(TI, SuccNum, P, true);
414 }
415
416
417 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
418 /// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
419 /// sink it into user blocks to reduce the number of virtual
420 /// registers that must be created and coalesced.
421 ///
422 /// Return true if any changes are made.
423 ///
424 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
425   // If this is a noop copy,
426   EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
427   EVT DstVT = TLI.getValueType(CI->getType());
428
429   // This is an fp<->int conversion?
430   if (SrcVT.isInteger() != DstVT.isInteger())
431     return false;
432
433   // If this is an extension, it will be a zero or sign extension, which
434   // isn't a noop.
435   if (SrcVT.bitsLT(DstVT)) return false;
436
437   // If these values will be promoted, find out what they will be promoted
438   // to.  This helps us consider truncates on PPC as noop copies when they
439   // are.
440   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
441     SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
442   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
443     DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
444
445   // If, after promotion, these are the same types, this is a noop copy.
446   if (SrcVT != DstVT)
447     return false;
448
449   BasicBlock *DefBB = CI->getParent();
450
451   /// InsertedCasts - Only insert a cast in each block once.
452   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
453
454   bool MadeChange = false;
455   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
456        UI != E; ) {
457     Use &TheUse = UI.getUse();
458     Instruction *User = cast<Instruction>(*UI);
459
460     // Figure out which BB this cast is used in.  For PHI's this is the
461     // appropriate predecessor block.
462     BasicBlock *UserBB = User->getParent();
463     if (PHINode *PN = dyn_cast<PHINode>(User)) {
464       UserBB = PN->getIncomingBlock(UI);
465     }
466
467     // Preincrement use iterator so we don't invalidate it.
468     ++UI;
469
470     // If this user is in the same block as the cast, don't change the cast.
471     if (UserBB == DefBB) continue;
472
473     // If we have already inserted a cast into this block, use it.
474     CastInst *&InsertedCast = InsertedCasts[UserBB];
475
476     if (!InsertedCast) {
477       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
478
479       InsertedCast =
480         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
481                          InsertPt);
482       MadeChange = true;
483     }
484
485     // Replace a use of the cast with a use of the new cast.
486     TheUse = InsertedCast;
487   }
488
489   // If we removed all uses, nuke the cast.
490   if (CI->use_empty()) {
491     CI->eraseFromParent();
492     MadeChange = true;
493   }
494
495   return MadeChange;
496 }
497
498 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
499 /// the number of virtual registers that must be created and coalesced.  This is
500 /// a clear win except on targets with multiple condition code registers
501 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
502 ///
503 /// Return true if any changes are made.
504 static bool OptimizeCmpExpression(CmpInst *CI) {
505   BasicBlock *DefBB = CI->getParent();
506
507   /// InsertedCmp - Only insert a cmp in each block once.
508   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
509
510   bool MadeChange = false;
511   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
512        UI != E; ) {
513     Use &TheUse = UI.getUse();
514     Instruction *User = cast<Instruction>(*UI);
515
516     // Preincrement use iterator so we don't invalidate it.
517     ++UI;
518
519     // Don't bother for PHI nodes.
520     if (isa<PHINode>(User))
521       continue;
522
523     // Figure out which BB this cmp is used in.
524     BasicBlock *UserBB = User->getParent();
525
526     // If this user is in the same block as the cmp, don't change the cmp.
527     if (UserBB == DefBB) continue;
528
529     // If we have already inserted a cmp into this block, use it.
530     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
531
532     if (!InsertedCmp) {
533       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
534
535       InsertedCmp =
536         CmpInst::Create(CI->getOpcode(),
537                         CI->getPredicate(),  CI->getOperand(0),
538                         CI->getOperand(1), "", InsertPt);
539       MadeChange = true;
540     }
541
542     // Replace a use of the cmp with a use of the new cmp.
543     TheUse = InsertedCmp;
544   }
545
546   // If we removed all uses, nuke the cmp.
547   if (CI->use_empty())
548     CI->eraseFromParent();
549
550   return MadeChange;
551 }
552
553 namespace {
554 class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
555 protected:
556   void replaceCall(Value *With) {
557     CI->replaceAllUsesWith(With);
558     CI->eraseFromParent();
559   }
560   bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
561       if (ConstantInt *SizeCI =
562                              dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
563         return SizeCI->isAllOnesValue();
564     return false;
565   }
566 };
567 } // end anonymous namespace
568
569 bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
570   // Lower all uses of llvm.objectsize.*
571   IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
572   if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
573     bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
574     const Type *ReturnTy = CI->getType();
575     Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);    
576     CI->replaceAllUsesWith(RetVal);
577     CI->eraseFromParent();
578     return true;
579   }
580
581   // From here on out we're working with named functions.
582   if (CI->getCalledFunction() == 0) return false;
583   
584   // We'll need TargetData from here on out.
585   const TargetData *TD = TLI ? TLI->getTargetData() : 0;
586   if (!TD) return false;
587   
588   // Lower all default uses of _chk calls.  This is very similar
589   // to what InstCombineCalls does, but here we are only lowering calls
590   // that have the default "don't know" as the objectsize.  Anything else
591   // should be left alone.
592   CodeGenPrepareFortifiedLibCalls Simplifier;
593   return Simplifier.fold(CI, TD);
594 }
595 //===----------------------------------------------------------------------===//
596 // Memory Optimization
597 //===----------------------------------------------------------------------===//
598
599 /// IsNonLocalValue - Return true if the specified values are defined in a
600 /// different basic block than BB.
601 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
602   if (Instruction *I = dyn_cast<Instruction>(V))
603     return I->getParent() != BB;
604   return false;
605 }
606
607 /// OptimizeMemoryInst - Load and Store Instructions often have
608 /// addressing modes that can do significant amounts of computation.  As such,
609 /// instruction selection will try to get the load or store to do as much
610 /// computation as possible for the program.  The problem is that isel can only
611 /// see within a single block.  As such, we sink as much legal addressing mode
612 /// stuff into the block as possible.
613 ///
614 /// This method is used to optimize both load/store and inline asms with memory
615 /// operands.
616 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
617                                         const Type *AccessTy,
618                                         DenseMap<Value*,Value*> &SunkAddrs) {
619   // Figure out what addressing mode will be built up for this operation.
620   SmallVector<Instruction*, 16> AddrModeInsts;
621   ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
622                                                       AddrModeInsts, *TLI);
623
624   // Check to see if any of the instructions supersumed by this addr mode are
625   // non-local to I's BB.
626   bool AnyNonLocal = false;
627   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
628     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
629       AnyNonLocal = true;
630       break;
631     }
632   }
633
634   // If all the instructions matched are already in this BB, don't do anything.
635   if (!AnyNonLocal) {
636     DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
637     return false;
638   }
639
640   // Insert this computation right after this user.  Since our caller is
641   // scanning from the top of the BB to the bottom, reuse of the expr are
642   // guaranteed to happen later.
643   BasicBlock::iterator InsertPt = MemoryInst;
644
645   // Now that we determined the addressing expression we want to use and know
646   // that we have to sink it into this block.  Check to see if we have already
647   // done this for some other load/store instr in this block.  If so, reuse the
648   // computation.
649   Value *&SunkAddr = SunkAddrs[Addr];
650   if (SunkAddr) {
651     DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
652                  << *MemoryInst);
653     if (SunkAddr->getType() != Addr->getType())
654       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
655   } else {
656     DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
657                  << *MemoryInst);
658     const Type *IntPtrTy =
659           TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
660
661     Value *Result = 0;
662
663     // Start with the base register. Do this first so that subsequent address
664     // matching finds it last, which will prevent it from trying to match it
665     // as the scaled value in case it happens to be a mul. That would be
666     // problematic if we've sunk a different mul for the scale, because then
667     // we'd end up sinking both muls.
668     if (AddrMode.BaseReg) {
669       Value *V = AddrMode.BaseReg;
670       if (V->getType()->isPointerTy())
671         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
672       if (V->getType() != IntPtrTy)
673         V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
674                                         "sunkaddr", InsertPt);
675       Result = V;
676     }
677
678     // Add the scale value.
679     if (AddrMode.Scale) {
680       Value *V = AddrMode.ScaledReg;
681       if (V->getType() == IntPtrTy) {
682         // done.
683       } else if (V->getType()->isPointerTy()) {
684         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
685       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
686                  cast<IntegerType>(V->getType())->getBitWidth()) {
687         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
688       } else {
689         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
690       }
691       if (AddrMode.Scale != 1)
692         V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
693                                                                 AddrMode.Scale),
694                                       "sunkaddr", InsertPt);
695       if (Result)
696         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
697       else
698         Result = V;
699     }
700
701     // Add in the BaseGV if present.
702     if (AddrMode.BaseGV) {
703       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
704                                   InsertPt);
705       if (Result)
706         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
707       else
708         Result = V;
709     }
710
711     // Add in the Base Offset if present.
712     if (AddrMode.BaseOffs) {
713       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
714       if (Result)
715         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
716       else
717         Result = V;
718     }
719
720     if (Result == 0)
721       SunkAddr = Constant::getNullValue(Addr->getType());
722     else
723       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
724   }
725
726   MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
727
728   if (Addr->use_empty()) {
729     RecursivelyDeleteTriviallyDeadInstructions(Addr);
730     // This address is now available for reassignment, so erase the table entry;
731     // we don't want to match some completely different instruction.
732     SunkAddrs[Addr] = 0;
733   }
734   return true;
735 }
736
737 /// OptimizeInlineAsmInst - If there are any memory operands, use
738 /// OptimizeMemoryInst to sink their address computing into the block when
739 /// possible / profitable.
740 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
741                                            DenseMap<Value*,Value*> &SunkAddrs) {
742   bool MadeChange = false;
743
744   std::vector<TargetLowering::AsmOperandInfo> TargetConstraints = TLI->ParseConstraints(CS);
745   unsigned ArgNo = 0;
746   for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
747     TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
748     
749     // Compute the constraint code and ConstraintType to use.
750     TLI->ComputeConstraintToUse(OpInfo, SDValue());
751
752     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
753         OpInfo.isIndirect) {
754       Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
755       MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
756     } else if (OpInfo.Type == InlineAsm::isInput)
757       ArgNo++;
758   }
759
760   return MadeChange;
761 }
762
763 /// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
764 /// basic block as the load, unless conditions are unfavorable. This allows
765 /// SelectionDAG to fold the extend into the load.
766 ///
767 bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
768   // Look for a load being extended.
769   LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
770   if (!LI) return false;
771
772   // If they're already in the same block, there's nothing to do.
773   if (LI->getParent() == I->getParent())
774     return false;
775
776   // If the load has other users and the truncate is not free, this probably
777   // isn't worthwhile.
778   if (!LI->hasOneUse() &&
779       TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
780               !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
781       !TLI->isTruncateFree(I->getType(), LI->getType()))
782     return false;
783
784   // Check whether the target supports casts folded into loads.
785   unsigned LType;
786   if (isa<ZExtInst>(I))
787     LType = ISD::ZEXTLOAD;
788   else {
789     assert(isa<SExtInst>(I) && "Unexpected ext type!");
790     LType = ISD::SEXTLOAD;
791   }
792   if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
793     return false;
794
795   // Move the extend into the same block as the load, so that SelectionDAG
796   // can fold it.
797   I->removeFromParent();
798   I->insertAfter(LI);
799   return true;
800 }
801
802 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
803   BasicBlock *DefBB = I->getParent();
804
805   // If the result of a {s|z}ext and its source are both live out, rewrite all
806   // other uses of the source with result of extension.
807   Value *Src = I->getOperand(0);
808   if (Src->hasOneUse())
809     return false;
810
811   // Only do this xform if truncating is free.
812   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
813     return false;
814
815   // Only safe to perform the optimization if the source is also defined in
816   // this block.
817   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
818     return false;
819
820   bool DefIsLiveOut = false;
821   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
822        UI != E; ++UI) {
823     Instruction *User = cast<Instruction>(*UI);
824
825     // Figure out which BB this ext is used in.
826     BasicBlock *UserBB = User->getParent();
827     if (UserBB == DefBB) continue;
828     DefIsLiveOut = true;
829     break;
830   }
831   if (!DefIsLiveOut)
832     return false;
833
834   // Make sure non of the uses are PHI nodes.
835   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
836        UI != E; ++UI) {
837     Instruction *User = cast<Instruction>(*UI);
838     BasicBlock *UserBB = User->getParent();
839     if (UserBB == DefBB) continue;
840     // Be conservative. We don't want this xform to end up introducing
841     // reloads just before load / store instructions.
842     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
843       return false;
844   }
845
846   // InsertedTruncs - Only insert one trunc in each block once.
847   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
848
849   bool MadeChange = false;
850   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
851        UI != E; ++UI) {
852     Use &TheUse = UI.getUse();
853     Instruction *User = cast<Instruction>(*UI);
854
855     // Figure out which BB this ext is used in.
856     BasicBlock *UserBB = User->getParent();
857     if (UserBB == DefBB) continue;
858
859     // Both src and def are live in this block. Rewrite the use.
860     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
861
862     if (!InsertedTrunc) {
863       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
864
865       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
866     }
867
868     // Replace a use of the {s|z}ext source with a use of the result.
869     TheUse = InsertedTrunc;
870
871     MadeChange = true;
872   }
873
874   return MadeChange;
875 }
876
877 // In this pass we look for GEP and cast instructions that are used
878 // across basic blocks and rewrite them to improve basic-block-at-a-time
879 // selection.
880 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
881   bool MadeChange = false;
882
883   // Split all critical edges where the dest block has a PHI.
884   if (CriticalEdgeSplit) {
885     TerminatorInst *BBTI = BB.getTerminator();
886     if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
887       for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
888         BasicBlock *SuccBB = BBTI->getSuccessor(i);
889         if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
890           SplitEdgeNicely(BBTI, i, BackEdges, this);
891       }
892     }
893   }
894
895   // Keep track of non-local addresses that have been sunk into this block.
896   // This allows us to avoid inserting duplicate code for blocks with multiple
897   // load/stores of the same address.
898   DenseMap<Value*, Value*> SunkAddrs;
899
900   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
901     Instruction *I = BBI++;
902
903     if (CastInst *CI = dyn_cast<CastInst>(I)) {
904       // If the source of the cast is a constant, then this should have
905       // already been constant folded.  The only reason NOT to constant fold
906       // it is if something (e.g. LSR) was careful to place the constant
907       // evaluation in a block other than then one that uses it (e.g. to hoist
908       // the address of globals out of a loop).  If this is the case, we don't
909       // want to forward-subst the cast.
910       if (isa<Constant>(CI->getOperand(0)))
911         continue;
912
913       bool Change = false;
914       if (TLI) {
915         Change = OptimizeNoopCopyExpression(CI, *TLI);
916         MadeChange |= Change;
917       }
918
919       if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
920         MadeChange |= MoveExtToFormExtLoad(I);
921         MadeChange |= OptimizeExtUses(I);
922       }
923     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
924       MadeChange |= OptimizeCmpExpression(CI);
925     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
926       if (TLI)
927         MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
928                                          SunkAddrs);
929     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
930       if (TLI)
931         MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
932                                          SI->getOperand(0)->getType(),
933                                          SunkAddrs);
934     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
935       if (GEPI->hasAllZeroIndices()) {
936         /// The GEP operand must be a pointer, so must its result -> BitCast
937         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
938                                           GEPI->getName(), GEPI);
939         GEPI->replaceAllUsesWith(NC);
940         GEPI->eraseFromParent();
941         MadeChange = true;
942         BBI = NC;
943       }
944     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
945       // If we found an inline asm expession, and if the target knows how to
946       // lower it to normal LLVM code, do so now.
947       if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
948         if (TLI->ExpandInlineAsm(CI)) {
949           BBI = BB.begin();
950           // Avoid processing instructions out of order, which could cause
951           // reuse before a value is defined.
952           SunkAddrs.clear();
953         } else
954           // Sink address computing for memory operands into the block.
955           MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
956       } else {
957         // Other CallInst optimizations that don't need to muck with the
958         // enclosing iterator here.
959         MadeChange |= OptimizeCallInst(CI);
960       }
961     }
962   }
963
964   return MadeChange;
965 }