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