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