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