2dfd4d7a3d3ccc0a00f5653bffb8fd87a6266a90
[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/Pass.h"
24 #include "llvm/Target/TargetAsmInfo.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
29 #include "llvm/Transforms/Utils/Local.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/SmallSet.h"
32 #include "llvm/Support/CallSite.h"
33 #include "llvm/Support/Compiler.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/GetElementPtrTypeIterator.h"
36 using namespace llvm;
37
38 namespace {  
39   class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
40     /// TLI - Keep a pointer of a TargetLowering to consult for determining
41     /// transformation profitability.
42     const TargetLowering *TLI;
43   public:
44     static char ID; // Pass identification, replacement for typeid
45     explicit CodeGenPrepare(const TargetLowering *tli = 0)
46       : FunctionPass((intptr_t)&ID), TLI(tli) {}
47     bool runOnFunction(Function &F);
48     
49   private:
50     bool EliminateMostlyEmptyBlocks(Function &F);
51     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
52     void EliminateMostlyEmptyBlock(BasicBlock *BB);
53     bool OptimizeBlock(BasicBlock &BB);
54     bool OptimizeLoadStoreInst(Instruction *I, Value *Addr,
55                                const Type *AccessTy,
56                                DenseMap<Value*,Value*> &SunkAddrs);
57     bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
58                                DenseMap<Value*,Value*> &SunkAddrs);
59     bool OptimizeExtUses(Instruction *I);
60   };
61 }
62
63 char CodeGenPrepare::ID = 0;
64 static RegisterPass<CodeGenPrepare> X("codegenprepare",
65                                       "Optimize for code generation");
66
67 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
68   return new CodeGenPrepare(TLI);
69 }
70
71
72 bool CodeGenPrepare::runOnFunction(Function &F) {
73   bool EverMadeChange = false;
74   
75   // First pass, eliminate blocks that contain only PHI nodes and an
76   // unconditional branch.
77   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
78   
79   bool MadeChange = true;
80   while (MadeChange) {
81     MadeChange = false;
82     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
83       MadeChange |= OptimizeBlock(*BB);
84     EverMadeChange |= MadeChange;
85   }
86   return EverMadeChange;
87 }
88
89 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
90 /// and an unconditional branch.  Passes before isel (e.g. LSR/loopsimplify) 
91 /// often split edges in ways that are non-optimal for isel.  Start by
92 /// eliminating these blocks so we can split them the way we want them.
93 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
94   bool MadeChange = false;
95   // Note that this intentionally skips the entry block.
96   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
97     BasicBlock *BB = I++;
98
99     // If this block doesn't end with an uncond branch, ignore it.
100     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
101     if (!BI || !BI->isUnconditional())
102       continue;
103     
104     // If the instruction before the branch isn't a phi node, then other stuff
105     // is happening here.
106     BasicBlock::iterator BBI = BI;
107     if (BBI != BB->begin()) {
108       --BBI;
109       if (!isa<PHINode>(BBI)) continue;
110     }
111     
112     // Do not break infinite loops.
113     BasicBlock *DestBB = BI->getSuccessor(0);
114     if (DestBB == BB)
115       continue;
116     
117     if (!CanMergeBlocks(BB, DestBB))
118       continue;
119     
120     EliminateMostlyEmptyBlock(BB);
121     MadeChange = true;
122   }
123   return MadeChange;
124 }
125
126 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
127 /// single uncond branch between them, and BB contains no other non-phi
128 /// instructions.
129 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
130                                     const BasicBlock *DestBB) const {
131   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
132   // the successor.  If there are more complex condition (e.g. preheaders),
133   // don't mess around with them.
134   BasicBlock::const_iterator BBI = BB->begin();
135   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
136     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
137          UI != E; ++UI) {
138       const Instruction *User = cast<Instruction>(*UI);
139       if (User->getParent() != DestBB || !isa<PHINode>(User))
140         return false;
141       // If User is inside DestBB block and it is a PHINode then check 
142       // incoming value. If incoming value is not from BB then this is 
143       // a complex condition (e.g. preheaders) we want to avoid here.
144       if (User->getParent() == DestBB) {
145         if (const PHINode *UPN = dyn_cast<PHINode>(User))
146           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
147             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
148             if (Insn && Insn->getParent() == BB &&
149                 Insn->getParent() != UPN->getIncomingBlock(I))
150               return false;
151           }
152       }
153     }
154   }
155   
156   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
157   // and DestBB may have conflicting incoming values for the block.  If so, we
158   // can't merge the block.
159   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
160   if (!DestBBPN) return true;  // no conflict.
161   
162   // Collect the preds of BB.
163   SmallPtrSet<const BasicBlock*, 16> BBPreds;
164   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
165     // It is faster to get preds from a PHI than with pred_iterator.
166     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
167       BBPreds.insert(BBPN->getIncomingBlock(i));
168   } else {
169     BBPreds.insert(pred_begin(BB), pred_end(BB));
170   }
171   
172   // Walk the preds of DestBB.
173   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
174     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
175     if (BBPreds.count(Pred)) {   // Common predecessor?
176       BBI = DestBB->begin();
177       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
178         const Value *V1 = PN->getIncomingValueForBlock(Pred);
179         const Value *V2 = PN->getIncomingValueForBlock(BB);
180         
181         // If V2 is a phi node in BB, look up what the mapped value will be.
182         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
183           if (V2PN->getParent() == BB)
184             V2 = V2PN->getIncomingValueForBlock(Pred);
185         
186         // If there is a conflict, bail out.
187         if (V1 != V2) return false;
188       }
189     }
190   }
191
192   return true;
193 }
194
195
196 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
197 /// an unconditional branch in it.
198 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
199   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
200   BasicBlock *DestBB = BI->getSuccessor(0);
201   
202   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
203   
204   // If the destination block has a single pred, then this is a trivial edge,
205   // just collapse it.
206   if (DestBB->getSinglePredecessor()) {
207     // If DestBB has single-entry PHI nodes, fold them.
208     while (PHINode *PN = dyn_cast<PHINode>(DestBB->begin())) {
209       PN->replaceAllUsesWith(PN->getIncomingValue(0));
210       PN->eraseFromParent();
211     }
212     
213     // Splice all the PHI nodes from BB over to DestBB.
214     DestBB->getInstList().splice(DestBB->begin(), BB->getInstList(),
215                                  BB->begin(), BI);
216     
217     // Anything that branched to BB now branches to DestBB.
218     BB->replaceAllUsesWith(DestBB);
219     
220     // Nuke BB.
221     BB->eraseFromParent();
222     
223     DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
224     return;
225   }
226   
227   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
228   // to handle the new incoming edges it is about to have.
229   PHINode *PN;
230   for (BasicBlock::iterator BBI = DestBB->begin();
231        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
232     // Remove the incoming value for BB, and remember it.
233     Value *InVal = PN->removeIncomingValue(BB, false);
234     
235     // Two options: either the InVal is a phi node defined in BB or it is some
236     // value that dominates BB.
237     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
238     if (InValPhi && InValPhi->getParent() == BB) {
239       // Add all of the input values of the input PHI as inputs of this phi.
240       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
241         PN->addIncoming(InValPhi->getIncomingValue(i),
242                         InValPhi->getIncomingBlock(i));
243     } else {
244       // Otherwise, add one instance of the dominating value for each edge that
245       // we will be adding.
246       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
247         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
248           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
249       } else {
250         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
251           PN->addIncoming(InVal, *PI);
252       }
253     }
254   }
255   
256   // The PHIs are now updated, change everything that refers to BB to use
257   // DestBB and remove BB.
258   BB->replaceAllUsesWith(DestBB);
259   BB->eraseFromParent();
260   
261   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
262 }
263
264
265 /// SplitEdgeNicely - Split the critical edge from TI to its specified
266 /// successor if it will improve codegen.  We only do this if the successor has
267 /// phi nodes (otherwise critical edges are ok).  If there is already another
268 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
269 /// instead of introducing a new block.
270 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
271   BasicBlock *TIBB = TI->getParent();
272   BasicBlock *Dest = TI->getSuccessor(SuccNum);
273   assert(isa<PHINode>(Dest->begin()) &&
274          "This should only be called if Dest has a PHI!");
275   
276   // As a hack, never split backedges of loops.  Even though the copy for any
277   // PHIs inserted on the backedge would be dead for exits from the loop, we
278   // assume that the cost of *splitting* the backedge would be too high.
279   if (Dest == TIBB)
280     return;
281   
282   /// TIPHIValues - This array is lazily computed to determine the values of
283   /// PHIs in Dest that TI would provide.
284   SmallVector<Value*, 32> TIPHIValues;
285   
286   // Check to see if Dest has any blocks that can be used as a split edge for
287   // this terminator.
288   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
289     BasicBlock *Pred = *PI;
290     // To be usable, the pred has to end with an uncond branch to the dest.
291     BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
292     if (!PredBr || !PredBr->isUnconditional() ||
293         // Must be empty other than the branch.
294         &Pred->front() != PredBr ||
295         // Cannot be the entry block; its label does not get emitted.
296         Pred == &(Dest->getParent()->getEntryBlock()))
297       continue;
298     
299     // Finally, since we know that Dest has phi nodes in it, we have to make
300     // sure that jumping to Pred will have the same affect as going to Dest in
301     // terms of PHI values.
302     PHINode *PN;
303     unsigned PHINo = 0;
304     bool FoundMatch = true;
305     for (BasicBlock::iterator I = Dest->begin();
306          (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
307       if (PHINo == TIPHIValues.size())
308         TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
309       
310       // If the PHI entry doesn't work, we can't use this pred.
311       if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
312         FoundMatch = false;
313         break;
314       }
315     }
316     
317     // If we found a workable predecessor, change TI to branch to Succ.
318     if (FoundMatch) {
319       Dest->removePredecessor(TIBB);
320       TI->setSuccessor(SuccNum, Pred);
321       return;
322     }
323   }
324   
325   SplitCriticalEdge(TI, SuccNum, P, true);  
326 }
327
328 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
329 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
330 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
331 /// registers that must be created and coalesced.
332 ///
333 /// Return true if any changes are made.
334 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
335   // If this is a noop copy, 
336   MVT::ValueType SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
337   MVT::ValueType DstVT = TLI.getValueType(CI->getType());
338   
339   // This is an fp<->int conversion?
340   if (MVT::isInteger(SrcVT) != MVT::isInteger(DstVT))
341     return false;
342   
343   // If this is an extension, it will be a zero or sign extension, which
344   // isn't a noop.
345   if (SrcVT < DstVT) return false;
346   
347   // If these values will be promoted, find out what they will be promoted
348   // to.  This helps us consider truncates on PPC as noop copies when they
349   // are.
350   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
351     SrcVT = TLI.getTypeToTransformTo(SrcVT);
352   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
353     DstVT = TLI.getTypeToTransformTo(DstVT);
354   
355   // If, after promotion, these are the same types, this is a noop copy.
356   if (SrcVT != DstVT)
357     return false;
358   
359   BasicBlock *DefBB = CI->getParent();
360   
361   /// InsertedCasts - Only insert a cast in each block once.
362   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
363   
364   bool MadeChange = false;
365   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end(); 
366        UI != E; ) {
367     Use &TheUse = UI.getUse();
368     Instruction *User = cast<Instruction>(*UI);
369     
370     // Figure out which BB this cast is used in.  For PHI's this is the
371     // appropriate predecessor block.
372     BasicBlock *UserBB = User->getParent();
373     if (PHINode *PN = dyn_cast<PHINode>(User)) {
374       unsigned OpVal = UI.getOperandNo()/2;
375       UserBB = PN->getIncomingBlock(OpVal);
376     }
377     
378     // Preincrement use iterator so we don't invalidate it.
379     ++UI;
380     
381     // If this user is in the same block as the cast, don't change the cast.
382     if (UserBB == DefBB) continue;
383     
384     // If we have already inserted a cast into this block, use it.
385     CastInst *&InsertedCast = InsertedCasts[UserBB];
386
387     if (!InsertedCast) {
388       BasicBlock::iterator InsertPt = UserBB->begin();
389       while (isa<PHINode>(InsertPt)) ++InsertPt;
390       
391       InsertedCast = 
392         CastInst::create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "", 
393                          InsertPt);
394       MadeChange = true;
395     }
396     
397     // Replace a use of the cast with a use of the new cast.
398     TheUse = InsertedCast;
399   }
400   
401   // If we removed all uses, nuke the cast.
402   if (CI->use_empty()) {
403     CI->eraseFromParent();
404     MadeChange = true;
405   }
406   
407   return MadeChange;
408 }
409
410 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce 
411 /// the number of virtual registers that must be created and coalesced.  This is
412 /// a clear win except on targets with multiple condition code registers
413 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
414 ///
415 /// Return true if any changes are made.
416 static bool OptimizeCmpExpression(CmpInst *CI){
417
418   BasicBlock *DefBB = CI->getParent();
419   
420   /// InsertedCmp - Only insert a cmp in each block once.
421   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
422   
423   bool MadeChange = false;
424   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end(); 
425        UI != E; ) {
426     Use &TheUse = UI.getUse();
427     Instruction *User = cast<Instruction>(*UI);
428     
429     // Preincrement use iterator so we don't invalidate it.
430     ++UI;
431     
432     // Don't bother for PHI nodes.
433     if (isa<PHINode>(User))
434       continue;
435
436     // Figure out which BB this cmp is used in.
437     BasicBlock *UserBB = User->getParent();
438     
439     // If this user is in the same block as the cmp, don't change the cmp.
440     if (UserBB == DefBB) continue;
441     
442     // If we have already inserted a cmp into this block, use it.
443     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
444
445     if (!InsertedCmp) {
446       BasicBlock::iterator InsertPt = UserBB->begin();
447       while (isa<PHINode>(InsertPt)) ++InsertPt;
448       
449       InsertedCmp = 
450         CmpInst::create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0), 
451                         CI->getOperand(1), "", InsertPt);
452       MadeChange = true;
453     }
454     
455     // Replace a use of the cmp with a use of the new cmp.
456     TheUse = InsertedCmp;
457   }
458   
459   // If we removed all uses, nuke the cmp.
460   if (CI->use_empty())
461     CI->eraseFromParent();
462   
463   return MadeChange;
464 }
465
466 /// EraseDeadInstructions - Erase any dead instructions
467 static void EraseDeadInstructions(Value *V) {
468   Instruction *I = dyn_cast<Instruction>(V);
469   if (!I || !I->use_empty()) return;
470   
471   SmallPtrSet<Instruction*, 16> Insts;
472   Insts.insert(I);
473   
474   while (!Insts.empty()) {
475     I = *Insts.begin();
476     Insts.erase(I);
477     if (isInstructionTriviallyDead(I)) {
478       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
479         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
480           Insts.insert(U);
481       I->eraseFromParent();
482     }
483   }
484 }
485
486 namespace {
487
488 /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode which
489 /// holds actual Value*'s for register values.
490 struct ExtAddrMode : public TargetLowering::AddrMode {
491   Value *BaseReg;
492   Value *ScaledReg;
493   ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
494   void dump() const;
495 };
496
497 static std::ostream &operator<<(std::ostream &OS, const ExtAddrMode &AM) {
498   bool NeedPlus = false;
499   OS << "[";
500   if (AM.BaseGV)
501     OS << (NeedPlus ? " + " : "")
502        << "GV:%" << AM.BaseGV->getName(), NeedPlus = true;
503   
504   if (AM.BaseOffs)
505     OS << (NeedPlus ? " + " : "") << AM.BaseOffs, NeedPlus = true;
506   
507   if (AM.BaseReg)
508     OS << (NeedPlus ? " + " : "")
509        << "Base:%" << AM.BaseReg->getName(), NeedPlus = true;
510   if (AM.Scale)
511     OS << (NeedPlus ? " + " : "")
512        << AM.Scale << "*%" << AM.ScaledReg->getName(), NeedPlus = true;
513   
514   return OS << "]";
515 }
516
517 void ExtAddrMode::dump() const {
518   cerr << *this << "\n";
519 }
520
521 }
522
523 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
524                                    const Type *AccessTy, ExtAddrMode &AddrMode,
525                                    SmallVector<Instruction*, 16> &AddrModeInsts,
526                                    const TargetLowering &TLI, unsigned Depth);
527   
528 /// FindMaximalLegalAddressingMode - If we can, try to merge the computation of
529 /// Addr into the specified addressing mode.  If Addr can't be added to AddrMode
530 /// this returns false.  This assumes that Addr is either a pointer type or
531 /// intptr_t for the target.
532 static bool FindMaximalLegalAddressingMode(Value *Addr, const Type *AccessTy,
533                                            ExtAddrMode &AddrMode,
534                                    SmallVector<Instruction*, 16> &AddrModeInsts,
535                                            const TargetLowering &TLI,
536                                            unsigned Depth) {
537   
538   // If this is a global variable, fold it into the addressing mode if possible.
539   if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
540     if (AddrMode.BaseGV == 0) {
541       AddrMode.BaseGV = GV;
542       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
543         return true;
544       AddrMode.BaseGV = 0;
545     }
546   } else if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
547     AddrMode.BaseOffs += CI->getSExtValue();
548     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
549       return true;
550     AddrMode.BaseOffs -= CI->getSExtValue();
551   } else if (isa<ConstantPointerNull>(Addr)) {
552     return true;
553   }
554   
555   // Look through constant exprs and instructions.
556   unsigned Opcode = ~0U;
557   User *AddrInst = 0;
558   if (Instruction *I = dyn_cast<Instruction>(Addr)) {
559     Opcode = I->getOpcode();
560     AddrInst = I;
561   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
562     Opcode = CE->getOpcode();
563     AddrInst = CE;
564   }
565
566   // Limit recursion to avoid exponential behavior.
567   if (Depth == 5) { AddrInst = 0; Opcode = ~0U; }
568
569   // If this is really an instruction, add it to our list of related
570   // instructions.
571   if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst))
572     AddrModeInsts.push_back(I);
573
574   switch (Opcode) {
575   case Instruction::PtrToInt:
576     // PtrToInt is always a noop, as we know that the int type is pointer sized.
577     if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
578                                        AddrMode, AddrModeInsts, TLI, Depth))
579       return true;
580     break;
581   case Instruction::IntToPtr:
582     // This inttoptr is a no-op if the integer type is pointer sized.
583     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
584         TLI.getPointerTy()) {
585       if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
586                                          AddrMode, AddrModeInsts, TLI, Depth))
587         return true;
588     }
589     break;
590   case Instruction::Add: {
591     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
592     ExtAddrMode BackupAddrMode = AddrMode;
593     unsigned OldSize = AddrModeInsts.size();
594     if (FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
595                                        AddrMode, AddrModeInsts, TLI, Depth+1) &&
596         FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
597                                        AddrMode, AddrModeInsts, TLI, Depth+1))
598       return true;
599
600     // Restore the old addr mode info.
601     AddrMode = BackupAddrMode;
602     AddrModeInsts.resize(OldSize);
603     
604     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
605     if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
606                                        AddrMode, AddrModeInsts, TLI, Depth+1) &&
607         FindMaximalLegalAddressingMode(AddrInst->getOperand(1), AccessTy,
608                                        AddrMode, AddrModeInsts, TLI, Depth+1))
609       return true;
610     
611     // Otherwise we definitely can't merge the ADD in.
612     AddrMode = BackupAddrMode;
613     AddrModeInsts.resize(OldSize);
614     break;    
615   }
616   case Instruction::Or: {
617     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
618     if (!RHS) break;
619     // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
620     break;
621   }
622   case Instruction::Mul:
623   case Instruction::Shl: {
624     // Can only handle X*C and X << C, and can only handle this when the scale
625     // field is available.
626     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
627     if (!RHS) break;
628     int64_t Scale = RHS->getSExtValue();
629     if (Opcode == Instruction::Shl)
630       Scale = 1 << Scale;
631     
632     if (TryMatchingScaledValue(AddrInst->getOperand(0), Scale, AccessTy,
633                                AddrMode, AddrModeInsts, TLI, Depth))
634       return true;
635     break;
636   }
637   case Instruction::GetElementPtr: {
638     // Scan the GEP.  We check it if it contains constant offsets and at most
639     // one variable offset.
640     int VariableOperand = -1;
641     unsigned VariableScale = 0;
642     
643     int64_t ConstantOffset = 0;
644     const TargetData *TD = TLI.getTargetData();
645     gep_type_iterator GTI = gep_type_begin(AddrInst);
646     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
647       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
648         const StructLayout *SL = TD->getStructLayout(STy);
649         unsigned Idx =
650           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
651         ConstantOffset += SL->getElementOffset(Idx);
652       } else {
653         uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
654         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
655           ConstantOffset += CI->getSExtValue()*TypeSize;
656         } else if (TypeSize) {  // Scales of zero don't do anything.
657           // We only allow one variable index at the moment.
658           if (VariableOperand != -1) {
659             VariableOperand = -2;
660             break;
661           }
662           
663           // Remember the variable index.
664           VariableOperand = i;
665           VariableScale = TypeSize;
666         }
667       }
668     }
669
670     // If the GEP had multiple variable indices, punt.
671     if (VariableOperand == -2)
672       break;
673
674     // A common case is for the GEP to only do a constant offset.  In this case,
675     // just add it to the disp field and check validity.
676     if (VariableOperand == -1) {
677       AddrMode.BaseOffs += ConstantOffset;
678       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
679         // Check to see if we can fold the base pointer in too.
680         if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
681                                            AddrMode, AddrModeInsts, TLI,
682                                            Depth+1))
683           return true;
684       }
685       AddrMode.BaseOffs -= ConstantOffset;
686     } else {
687       // Check that this has no base reg yet.  If so, we won't have a place to
688       // put the base of the GEP (assuming it is not a null ptr).
689       bool SetBaseReg = false;
690       if (AddrMode.HasBaseReg) {
691         if (!isa<ConstantPointerNull>(AddrInst->getOperand(0)))
692           break;
693       } else {
694         AddrMode.HasBaseReg = true;
695         AddrMode.BaseReg = AddrInst->getOperand(0);
696         SetBaseReg = true;
697       }
698       
699       // See if the scale amount is valid for this target.
700       AddrMode.BaseOffs += ConstantOffset;
701       if (TryMatchingScaledValue(AddrInst->getOperand(VariableOperand),
702                                  VariableScale, AccessTy, AddrMode, 
703                                  AddrModeInsts, TLI, Depth)) {
704         if (!SetBaseReg) return true;
705
706         // If this match succeeded, we know that we can form an address with the
707         // GepBase as the basereg.  See if we can match *more*.
708         AddrMode.HasBaseReg = false;
709         AddrMode.BaseReg = 0;
710         if (FindMaximalLegalAddressingMode(AddrInst->getOperand(0), AccessTy,
711                                            AddrMode, AddrModeInsts, TLI,
712                                            Depth+1))
713           return true;
714         // Strange, shouldn't happen.  Restore the base reg and succeed the easy
715         // way.        
716         AddrMode.HasBaseReg = true;
717         AddrMode.BaseReg = AddrInst->getOperand(0);
718         return true;
719       }
720       
721       AddrMode.BaseOffs -= ConstantOffset;
722       if (SetBaseReg) {
723         AddrMode.HasBaseReg = false;
724         AddrMode.BaseReg = 0;
725       }
726     }
727     break;    
728   }
729   }
730   
731   if (Instruction *I = dyn_cast_or_null<Instruction>(AddrInst)) {
732     assert(AddrModeInsts.back() == I && "Stack imbalance"); I = I;
733     AddrModeInsts.pop_back();
734   }
735   
736   // Worse case, the target should support [reg] addressing modes. :)
737   if (!AddrMode.HasBaseReg) {
738     AddrMode.HasBaseReg = true;
739     // Still check for legality in case the target supports [imm] but not [i+r].
740     if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
741       AddrMode.BaseReg = Addr;
742       return true;
743     }
744     AddrMode.HasBaseReg = false;
745   }
746   
747   // If the base register is already taken, see if we can do [r+r].
748   if (AddrMode.Scale == 0) {
749     AddrMode.Scale = 1;
750     if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
751       AddrMode.ScaledReg = Addr;
752       return true;
753     }
754     AddrMode.Scale = 0;
755   }
756   // Couldn't match.
757   return false;
758 }
759
760 /// TryMatchingScaledValue - Try adding ScaleReg*Scale to the specified
761 /// addressing mode.  Return true if this addr mode is legal for the target,
762 /// false if not.
763 static bool TryMatchingScaledValue(Value *ScaleReg, int64_t Scale,
764                                    const Type *AccessTy, ExtAddrMode &AddrMode,
765                                    SmallVector<Instruction*, 16> &AddrModeInsts,
766                                    const TargetLowering &TLI, unsigned Depth) {
767   // If we already have a scale of this value, we can add to it, otherwise, we
768   // need an available scale field.
769   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
770     return false;
771   
772   ExtAddrMode InputAddrMode = AddrMode;
773   
774   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
775   // [A+B + A*7] -> [B+A*8].
776   AddrMode.Scale += Scale;
777   AddrMode.ScaledReg = ScaleReg;
778   
779   if (TLI.isLegalAddressingMode(AddrMode, AccessTy)) {
780     // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
781     // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
782     // X*Scale + C*Scale to addr mode.
783     BinaryOperator *BinOp = dyn_cast<BinaryOperator>(ScaleReg);
784     if (BinOp && BinOp->getOpcode() == Instruction::Add &&
785         isa<ConstantInt>(BinOp->getOperand(1)) && InputAddrMode.ScaledReg ==0) {
786       
787       InputAddrMode.Scale = Scale;
788       InputAddrMode.ScaledReg = BinOp->getOperand(0);
789       InputAddrMode.BaseOffs += 
790         cast<ConstantInt>(BinOp->getOperand(1))->getSExtValue()*Scale;
791       if (TLI.isLegalAddressingMode(InputAddrMode, AccessTy)) {
792         AddrModeInsts.push_back(BinOp);
793         AddrMode = InputAddrMode;
794         return true;
795       }
796     }
797
798     // Otherwise, not (x+c)*scale, just return what we have.
799     return true;
800   }
801   
802   // Otherwise, back this attempt out.
803   AddrMode.Scale -= Scale;
804   if (AddrMode.Scale == 0) AddrMode.ScaledReg = 0;
805   
806   return false;
807 }
808
809
810 /// IsNonLocalValue - Return true if the specified values are defined in a
811 /// different basic block than BB.
812 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
813   if (Instruction *I = dyn_cast<Instruction>(V))
814     return I->getParent() != BB;
815   return false;
816 }
817
818 /// OptimizeLoadStoreInst - Load and Store Instructions have often have
819 /// addressing modes that can do significant amounts of computation.  As such,
820 /// instruction selection will try to get the load or store to do as much
821 /// computation as possible for the program.  The problem is that isel can only
822 /// see within a single block.  As such, we sink as much legal addressing mode
823 /// stuff into the block as possible.
824 bool CodeGenPrepare::OptimizeLoadStoreInst(Instruction *LdStInst, Value *Addr,
825                                            const Type *AccessTy,
826                                            DenseMap<Value*,Value*> &SunkAddrs) {
827   // Figure out what addressing mode will be built up for this operation.
828   SmallVector<Instruction*, 16> AddrModeInsts;
829   ExtAddrMode AddrMode;
830   bool Success = FindMaximalLegalAddressingMode(Addr, AccessTy, AddrMode,
831                                                 AddrModeInsts, *TLI, 0);
832   Success = Success; assert(Success && "Couldn't select *anything*?");
833   
834   // Check to see if any of the instructions supersumed by this addr mode are
835   // non-local to I's BB.
836   bool AnyNonLocal = false;
837   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
838     if (IsNonLocalValue(AddrModeInsts[i], LdStInst->getParent())) {
839       AnyNonLocal = true;
840       break;
841     }
842   }
843   
844   // If all the instructions matched are already in this BB, don't do anything.
845   if (!AnyNonLocal) {
846     DEBUG(cerr << "CGP: Found      local addrmode: " << AddrMode << "\n");
847     return false;
848   }
849   
850   // Insert this computation right after this user.  Since our caller is
851   // scanning from the top of the BB to the bottom, reuse of the expr are
852   // guaranteed to happen later.
853   BasicBlock::iterator InsertPt = LdStInst;
854   
855   // Now that we determined the addressing expression we want to use and know
856   // that we have to sink it into this block.  Check to see if we have already
857   // done this for some other load/store instr in this block.  If so, reuse the
858   // computation.
859   Value *&SunkAddr = SunkAddrs[Addr];
860   if (SunkAddr) {
861     DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
862     if (SunkAddr->getType() != Addr->getType())
863       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
864   } else {
865     DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
866     const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
867     
868     Value *Result = 0;
869     // Start with the scale value.
870     if (AddrMode.Scale) {
871       Value *V = AddrMode.ScaledReg;
872       if (V->getType() == IntPtrTy) {
873         // done.
874       } else if (isa<PointerType>(V->getType())) {
875         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
876       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
877                  cast<IntegerType>(V->getType())->getBitWidth()) {
878         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
879       } else {
880         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
881       }
882       if (AddrMode.Scale != 1)
883         V = BinaryOperator::createMul(V, ConstantInt::get(IntPtrTy,
884                                                           AddrMode.Scale),
885                                       "sunkaddr", InsertPt);
886       Result = V;
887     }
888
889     // Add in the base register.
890     if (AddrMode.BaseReg) {
891       Value *V = AddrMode.BaseReg;
892       if (V->getType() != IntPtrTy)
893         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
894       if (Result)
895         Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
896       else
897         Result = V;
898     }
899     
900     // Add in the BaseGV if present.
901     if (AddrMode.BaseGV) {
902       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
903                                   InsertPt);
904       if (Result)
905         Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
906       else
907         Result = V;
908     }
909     
910     // Add in the Base Offset if present.
911     if (AddrMode.BaseOffs) {
912       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
913       if (Result)
914         Result = BinaryOperator::createAdd(Result, V, "sunkaddr", InsertPt);
915       else
916         Result = V;
917     }
918
919     if (Result == 0)
920       SunkAddr = Constant::getNullValue(Addr->getType());
921     else
922       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
923   }
924   
925   LdStInst->replaceUsesOfWith(Addr, SunkAddr);
926   
927   if (Addr->use_empty())
928     EraseDeadInstructions(Addr);
929   return true;
930 }
931
932 /// OptimizeInlineAsmInst - If there are any memory operands, use
933 /// OptimizeLoadStoreInt to sink their address computing into the block when
934 /// possible / profitable.
935 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
936                                            DenseMap<Value*,Value*> &SunkAddrs) {
937   bool MadeChange = false;
938   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
939
940   // Do a prepass over the constraints, canonicalizing them, and building up the
941   // ConstraintOperands list.
942   std::vector<InlineAsm::ConstraintInfo>
943     ConstraintInfos = IA->ParseConstraints();
944
945   /// ConstraintOperands - Information about all of the constraints.
946   std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
947   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
948   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
949     ConstraintOperands.
950       push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
951     TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
952
953     // Compute the value type for each operand.
954     switch (OpInfo.Type) {
955     case InlineAsm::isOutput:
956       if (OpInfo.isIndirect)
957         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
958       break;
959     case InlineAsm::isInput:
960       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
961       break;
962     case InlineAsm::isClobber:
963       // Nothing to do.
964       break;
965     }
966
967     // Compute the constraint code and ConstraintType to use.
968     TLI->ComputeConstraintToUse(OpInfo, SDOperand());
969
970     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
971         OpInfo.isIndirect) {
972       Value *OpVal = OpInfo.CallOperandVal;
973       MadeChange |= OptimizeLoadStoreInst(I, OpVal, OpVal->getType(),
974                                           SunkAddrs);
975     }
976   }
977
978   return MadeChange;
979 }
980
981 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
982   BasicBlock *DefBB = I->getParent();
983
984   // If both result of the {s|z}xt and its source are live out, rewrite all
985   // other uses of the source with result of extension.
986   Value *Src = I->getOperand(0);
987   if (Src->hasOneUse())
988     return false;
989
990   // Only do this xform if truncating is free.
991   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
992     return false;
993
994   // Only safe to perform the optimization if the source is also defined in
995   // this block.
996   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
997     return false;
998
999   bool DefIsLiveOut = false;
1000   for (Value::use_iterator UI = I->use_begin(), E = I->use_end(); 
1001        UI != E; ++UI) {
1002     Instruction *User = cast<Instruction>(*UI);
1003
1004     // Figure out which BB this ext is used in.
1005     BasicBlock *UserBB = User->getParent();
1006     if (UserBB == DefBB) continue;
1007     DefIsLiveOut = true;
1008     break;
1009   }
1010   if (!DefIsLiveOut)
1011     return false;
1012
1013   // Make sure non of the uses are PHI nodes.
1014   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end(); 
1015        UI != E; ++UI) {
1016     Instruction *User = cast<Instruction>(*UI);
1017     BasicBlock *UserBB = User->getParent();
1018     if (UserBB == DefBB) continue;
1019     // Be conservative. We don't want this xform to end up introducing
1020     // reloads just before load / store instructions.
1021     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1022       return false;
1023   }
1024
1025   // InsertedTruncs - Only insert one trunc in each block once.
1026   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1027
1028   bool MadeChange = false;
1029   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end(); 
1030        UI != E; ++UI) {
1031     Use &TheUse = UI.getUse();
1032     Instruction *User = cast<Instruction>(*UI);
1033
1034     // Figure out which BB this ext is used in.
1035     BasicBlock *UserBB = User->getParent();
1036     if (UserBB == DefBB) continue;
1037
1038     // Both src and def are live in this block. Rewrite the use.
1039     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1040
1041     if (!InsertedTrunc) {
1042       BasicBlock::iterator InsertPt = UserBB->begin();
1043       while (isa<PHINode>(InsertPt)) ++InsertPt;
1044       
1045       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1046     }
1047
1048     // Replace a use of the {s|z}ext source with a use of the result.
1049     TheUse = InsertedTrunc;
1050
1051     MadeChange = true;
1052   }
1053
1054   return MadeChange;
1055 }
1056
1057 // In this pass we look for GEP and cast instructions that are used
1058 // across basic blocks and rewrite them to improve basic-block-at-a-time
1059 // selection.
1060 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1061   bool MadeChange = false;
1062   
1063   // Split all critical edges where the dest block has a PHI and where the phi
1064   // has shared immediate operands.
1065   TerminatorInst *BBTI = BB.getTerminator();
1066   if (BBTI->getNumSuccessors() > 1) {
1067     for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1068       if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1069           isCriticalEdge(BBTI, i, true))
1070         SplitEdgeNicely(BBTI, i, this);
1071   }
1072   
1073   
1074   // Keep track of non-local addresses that have been sunk into this block.
1075   // This allows us to avoid inserting duplicate code for blocks with multiple
1076   // load/stores of the same address.
1077   DenseMap<Value*, Value*> SunkAddrs;
1078   
1079   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1080     Instruction *I = BBI++;
1081     
1082     if (CastInst *CI = dyn_cast<CastInst>(I)) {
1083       // If the source of the cast is a constant, then this should have
1084       // already been constant folded.  The only reason NOT to constant fold
1085       // it is if something (e.g. LSR) was careful to place the constant
1086       // evaluation in a block other than then one that uses it (e.g. to hoist
1087       // the address of globals out of a loop).  If this is the case, we don't
1088       // want to forward-subst the cast.
1089       if (isa<Constant>(CI->getOperand(0)))
1090         continue;
1091       
1092       bool Change = false;
1093       if (TLI) {
1094         Change = OptimizeNoopCopyExpression(CI, *TLI);
1095         MadeChange |= Change;
1096       }
1097
1098       if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1099         MadeChange |= OptimizeExtUses(I);
1100     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1101       MadeChange |= OptimizeCmpExpression(CI);
1102     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1103       if (TLI)
1104         MadeChange |= OptimizeLoadStoreInst(I, I->getOperand(0), LI->getType(),
1105                                             SunkAddrs);
1106     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1107       if (TLI)
1108         MadeChange |= OptimizeLoadStoreInst(I, SI->getOperand(1),
1109                                             SI->getOperand(0)->getType(),
1110                                             SunkAddrs);
1111     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1112       if (GEPI->hasAllZeroIndices()) {
1113         /// The GEP operand must be a pointer, so must its result -> BitCast
1114         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(), 
1115                                           GEPI->getName(), GEPI);
1116         GEPI->replaceAllUsesWith(NC);
1117         GEPI->eraseFromParent();
1118         MadeChange = true;
1119         BBI = NC;
1120       }
1121     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1122       // If we found an inline asm expession, and if the target knows how to
1123       // lower it to normal LLVM code, do so now.
1124       if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1125         if (const TargetAsmInfo *TAI = 
1126             TLI->getTargetMachine().getTargetAsmInfo()) {
1127           if (TAI->ExpandInlineAsm(CI))
1128             BBI = BB.begin();
1129           else
1130             // Sink address computing for memory operands into the block.
1131             MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1132         }
1133     }
1134   }
1135     
1136   return MadeChange;
1137 }
1138