Use the new MergeBasicBlockIntoOnlyPred function.
[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 #include "llvm/Support/PatternMatch.h"
37 using namespace llvm;
38 using namespace llvm::PatternMatch;
39
40 namespace {
41   class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
42     /// TLI - Keep a pointer of a TargetLowering to consult for determining
43     /// transformation profitability.
44     const TargetLowering *TLI;
45   public:
46     static char ID; // Pass identification, replacement for typeid
47     explicit CodeGenPrepare(const TargetLowering *tli = 0)
48       : FunctionPass(&ID), TLI(tli) {}
49     bool runOnFunction(Function &F);
50
51   private:
52     bool EliminateMostlyEmptyBlocks(Function &F);
53     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
54     void EliminateMostlyEmptyBlock(BasicBlock *BB);
55     bool OptimizeBlock(BasicBlock &BB);
56     bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
57                             DenseMap<Value*,Value*> &SunkAddrs);
58     bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
59                                DenseMap<Value*,Value*> &SunkAddrs);
60     bool OptimizeExtUses(Instruction *I);
61   };
62 }
63
64 char CodeGenPrepare::ID = 0;
65 static RegisterPass<CodeGenPrepare> X("codegenprepare",
66                                       "Optimize for code generation");
67
68 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
69   return new CodeGenPrepare(TLI);
70 }
71
72
73 bool CodeGenPrepare::runOnFunction(Function &F) {
74   bool EverMadeChange = false;
75
76   // First pass, eliminate blocks that contain only PHI nodes and an
77   // unconditional branch.
78   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
79
80   bool MadeChange = true;
81   while (MadeChange) {
82     MadeChange = false;
83     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
84       MadeChange |= OptimizeBlock(*BB);
85     EverMadeChange |= MadeChange;
86   }
87   return EverMadeChange;
88 }
89
90 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
91 /// and an unconditional branch.  Passes before isel (e.g. LSR/loopsimplify)
92 /// often split edges in ways that are non-optimal for isel.  Start by
93 /// eliminating these blocks so we can split them the way we want them.
94 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
95   bool MadeChange = false;
96   // Note that this intentionally skips the entry block.
97   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
98     BasicBlock *BB = I++;
99
100     // If this block doesn't end with an uncond branch, ignore it.
101     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
102     if (!BI || !BI->isUnconditional())
103       continue;
104
105     // If the instruction before the branch isn't a phi node, then other stuff
106     // is happening here.
107     BasicBlock::iterator BBI = BI;
108     if (BBI != BB->begin()) {
109       --BBI;
110       if (!isa<PHINode>(BBI)) continue;
111     }
112
113     // Do not break infinite loops.
114     BasicBlock *DestBB = BI->getSuccessor(0);
115     if (DestBB == BB)
116       continue;
117
118     if (!CanMergeBlocks(BB, DestBB))
119       continue;
120
121     EliminateMostlyEmptyBlock(BB);
122     MadeChange = true;
123   }
124   return MadeChange;
125 }
126
127 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
128 /// single uncond branch between them, and BB contains no other non-phi
129 /// instructions.
130 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
131                                     const BasicBlock *DestBB) const {
132   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
133   // the successor.  If there are more complex condition (e.g. preheaders),
134   // don't mess around with them.
135   BasicBlock::const_iterator BBI = BB->begin();
136   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
137     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
138          UI != E; ++UI) {
139       const Instruction *User = cast<Instruction>(*UI);
140       if (User->getParent() != DestBB || !isa<PHINode>(User))
141         return false;
142       // If User is inside DestBB block and it is a PHINode then check
143       // incoming value. If incoming value is not from BB then this is
144       // a complex condition (e.g. preheaders) we want to avoid here.
145       if (User->getParent() == DestBB) {
146         if (const PHINode *UPN = dyn_cast<PHINode>(User))
147           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
148             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
149             if (Insn && Insn->getParent() == BB &&
150                 Insn->getParent() != UPN->getIncomingBlock(I))
151               return false;
152           }
153       }
154     }
155   }
156
157   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
158   // and DestBB may have conflicting incoming values for the block.  If so, we
159   // can't merge the block.
160   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
161   if (!DestBBPN) return true;  // no conflict.
162
163   // Collect the preds of BB.
164   SmallPtrSet<const BasicBlock*, 16> BBPreds;
165   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
166     // It is faster to get preds from a PHI than with pred_iterator.
167     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
168       BBPreds.insert(BBPN->getIncomingBlock(i));
169   } else {
170     BBPreds.insert(pred_begin(BB), pred_end(BB));
171   }
172
173   // Walk the preds of DestBB.
174   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
175     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
176     if (BBPreds.count(Pred)) {   // Common predecessor?
177       BBI = DestBB->begin();
178       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
179         const Value *V1 = PN->getIncomingValueForBlock(Pred);
180         const Value *V2 = PN->getIncomingValueForBlock(BB);
181
182         // If V2 is a phi node in BB, look up what the mapped value will be.
183         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
184           if (V2PN->getParent() == BB)
185             V2 = V2PN->getIncomingValueForBlock(Pred);
186
187         // If there is a conflict, bail out.
188         if (V1 != V2) return false;
189       }
190     }
191   }
192
193   return true;
194 }
195
196
197 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
198 /// an unconditional branch in it.
199 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
200   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
201   BasicBlock *DestBB = BI->getSuccessor(0);
202
203   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
204
205   // If the destination block has a single pred, then this is a trivial edge,
206   // just collapse it.
207   if (DestBB->getSinglePredecessor()) {
208     MergeBasicBlockIntoOnlyPred(DestBB);
209     DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
210     return;
211   }
212
213   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
214   // to handle the new incoming edges it is about to have.
215   PHINode *PN;
216   for (BasicBlock::iterator BBI = DestBB->begin();
217        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
218     // Remove the incoming value for BB, and remember it.
219     Value *InVal = PN->removeIncomingValue(BB, false);
220
221     // Two options: either the InVal is a phi node defined in BB or it is some
222     // value that dominates BB.
223     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
224     if (InValPhi && InValPhi->getParent() == BB) {
225       // Add all of the input values of the input PHI as inputs of this phi.
226       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
227         PN->addIncoming(InValPhi->getIncomingValue(i),
228                         InValPhi->getIncomingBlock(i));
229     } else {
230       // Otherwise, add one instance of the dominating value for each edge that
231       // we will be adding.
232       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
233         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
234           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
235       } else {
236         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
237           PN->addIncoming(InVal, *PI);
238       }
239     }
240   }
241
242   // The PHIs are now updated, change everything that refers to BB to use
243   // DestBB and remove BB.
244   BB->replaceAllUsesWith(DestBB);
245   BB->eraseFromParent();
246
247   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
248 }
249
250
251 /// SplitEdgeNicely - Split the critical edge from TI to its specified
252 /// successor if it will improve codegen.  We only do this if the successor has
253 /// phi nodes (otherwise critical edges are ok).  If there is already another
254 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
255 /// instead of introducing a new block.
256 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum, Pass *P) {
257   BasicBlock *TIBB = TI->getParent();
258   BasicBlock *Dest = TI->getSuccessor(SuccNum);
259   assert(isa<PHINode>(Dest->begin()) &&
260          "This should only be called if Dest has a PHI!");
261
262   // As a hack, never split backedges of loops.  Even though the copy for any
263   // PHIs inserted on the backedge would be dead for exits from the loop, we
264   // assume that the cost of *splitting* the backedge would be too high.
265   if (Dest == TIBB)
266     return;
267
268   /// TIPHIValues - This array is lazily computed to determine the values of
269   /// PHIs in Dest that TI would provide.
270   SmallVector<Value*, 32> TIPHIValues;
271
272   // Check to see if Dest has any blocks that can be used as a split edge for
273   // this terminator.
274   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
275     BasicBlock *Pred = *PI;
276     // To be usable, the pred has to end with an uncond branch to the dest.
277     BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
278     if (!PredBr || !PredBr->isUnconditional() ||
279         // Must be empty other than the branch.
280         &Pred->front() != PredBr ||
281         // Cannot be the entry block; its label does not get emitted.
282         Pred == &(Dest->getParent()->getEntryBlock()))
283       continue;
284
285     // Finally, since we know that Dest has phi nodes in it, we have to make
286     // sure that jumping to Pred will have the same affect as going to Dest in
287     // terms of PHI values.
288     PHINode *PN;
289     unsigned PHINo = 0;
290     bool FoundMatch = true;
291     for (BasicBlock::iterator I = Dest->begin();
292          (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
293       if (PHINo == TIPHIValues.size())
294         TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
295
296       // If the PHI entry doesn't work, we can't use this pred.
297       if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
298         FoundMatch = false;
299         break;
300       }
301     }
302
303     // If we found a workable predecessor, change TI to branch to Succ.
304     if (FoundMatch) {
305       Dest->removePredecessor(TIBB);
306       TI->setSuccessor(SuccNum, Pred);
307       return;
308     }
309   }
310
311   SplitCriticalEdge(TI, SuccNum, P, true);
312 }
313
314 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
315 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
316 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
317 /// registers that must be created and coalesced.
318 ///
319 /// Return true if any changes are made.
320 ///
321 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
322   // If this is a noop copy,
323   MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
324   MVT DstVT = TLI.getValueType(CI->getType());
325
326   // This is an fp<->int conversion?
327   if (SrcVT.isInteger() != DstVT.isInteger())
328     return false;
329
330   // If this is an extension, it will be a zero or sign extension, which
331   // isn't a noop.
332   if (SrcVT.bitsLT(DstVT)) return false;
333
334   // If these values will be promoted, find out what they will be promoted
335   // to.  This helps us consider truncates on PPC as noop copies when they
336   // are.
337   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
338     SrcVT = TLI.getTypeToTransformTo(SrcVT);
339   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
340     DstVT = TLI.getTypeToTransformTo(DstVT);
341
342   // If, after promotion, these are the same types, this is a noop copy.
343   if (SrcVT != DstVT)
344     return false;
345
346   BasicBlock *DefBB = CI->getParent();
347
348   /// InsertedCasts - Only insert a cast in each block once.
349   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
350
351   bool MadeChange = false;
352   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
353        UI != E; ) {
354     Use &TheUse = UI.getUse();
355     Instruction *User = cast<Instruction>(*UI);
356
357     // Figure out which BB this cast is used in.  For PHI's this is the
358     // appropriate predecessor block.
359     BasicBlock *UserBB = User->getParent();
360     if (PHINode *PN = dyn_cast<PHINode>(User)) {
361       unsigned OpVal = UI.getOperandNo()/2;
362       UserBB = PN->getIncomingBlock(OpVal);
363     }
364
365     // Preincrement use iterator so we don't invalidate it.
366     ++UI;
367
368     // If this user is in the same block as the cast, don't change the cast.
369     if (UserBB == DefBB) continue;
370
371     // If we have already inserted a cast into this block, use it.
372     CastInst *&InsertedCast = InsertedCasts[UserBB];
373
374     if (!InsertedCast) {
375       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
376
377       InsertedCast =
378         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
379                          InsertPt);
380       MadeChange = true;
381     }
382
383     // Replace a use of the cast with a use of the new cast.
384     TheUse = InsertedCast;
385   }
386
387   // If we removed all uses, nuke the cast.
388   if (CI->use_empty()) {
389     CI->eraseFromParent();
390     MadeChange = true;
391   }
392
393   return MadeChange;
394 }
395
396 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
397 /// the number of virtual registers that must be created and coalesced.  This is
398 /// a clear win except on targets with multiple condition code registers
399 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
400 ///
401 /// Return true if any changes are made.
402 static bool OptimizeCmpExpression(CmpInst *CI) {
403   BasicBlock *DefBB = CI->getParent();
404
405   /// InsertedCmp - Only insert a cmp in each block once.
406   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
407
408   bool MadeChange = false;
409   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
410        UI != E; ) {
411     Use &TheUse = UI.getUse();
412     Instruction *User = cast<Instruction>(*UI);
413
414     // Preincrement use iterator so we don't invalidate it.
415     ++UI;
416
417     // Don't bother for PHI nodes.
418     if (isa<PHINode>(User))
419       continue;
420
421     // Figure out which BB this cmp is used in.
422     BasicBlock *UserBB = User->getParent();
423
424     // If this user is in the same block as the cmp, don't change the cmp.
425     if (UserBB == DefBB) continue;
426
427     // If we have already inserted a cmp into this block, use it.
428     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
429
430     if (!InsertedCmp) {
431       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
432
433       InsertedCmp =
434         CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
435                         CI->getOperand(1), "", InsertPt);
436       MadeChange = true;
437     }
438
439     // Replace a use of the cmp with a use of the new cmp.
440     TheUse = InsertedCmp;
441   }
442
443   // If we removed all uses, nuke the cmp.
444   if (CI->use_empty())
445     CI->eraseFromParent();
446
447   return MadeChange;
448 }
449
450 /// EraseDeadInstructions - Erase any dead instructions, recursively.
451 static void EraseDeadInstructions(Value *V) {
452   Instruction *I = dyn_cast<Instruction>(V);
453   if (!I || !I->use_empty()) return;
454
455   SmallPtrSet<Instruction*, 16> Insts;
456   Insts.insert(I);
457
458   while (!Insts.empty()) {
459     I = *Insts.begin();
460     Insts.erase(I);
461     if (isInstructionTriviallyDead(I)) {
462       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
463         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
464           Insts.insert(U);
465       I->eraseFromParent();
466     }
467   }
468 }
469
470 //===----------------------------------------------------------------------===//
471 // Addressing Mode Analysis and Optimization
472 //===----------------------------------------------------------------------===//
473
474 namespace {
475   /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
476   /// which holds actual Value*'s for register values.
477   struct ExtAddrMode : public TargetLowering::AddrMode {
478     Value *BaseReg;
479     Value *ScaledReg;
480     ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
481     void print(OStream &OS) const;
482     void dump() const {
483       print(cerr);
484       cerr << '\n';
485     }
486   };
487 } // end anonymous namespace
488
489 static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
490   AM.print(OS);
491   return OS;
492 }
493
494 void ExtAddrMode::print(OStream &OS) const {
495   bool NeedPlus = false;
496   OS << "[";
497   if (BaseGV)
498     OS << (NeedPlus ? " + " : "")
499        << "GV:%" << BaseGV->getName(), NeedPlus = true;
500
501   if (BaseOffs)
502     OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
503
504   if (BaseReg)
505     OS << (NeedPlus ? " + " : "")
506        << "Base:%" << BaseReg->getName(), NeedPlus = true;
507   if (Scale)
508     OS << (NeedPlus ? " + " : "")
509        << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
510
511   OS << ']';
512 }
513
514 namespace {
515 /// AddressingModeMatcher - This class exposes a single public method, which is
516 /// used to construct a "maximal munch" of the addressing mode for the target
517 /// specified by TLI for an access to "V" with an access type of AccessTy.  This
518 /// returns the addressing mode that is actually matched by value, but also
519 /// returns the list of instructions involved in that addressing computation in
520 /// AddrModeInsts.
521 class AddressingModeMatcher {
522   SmallVectorImpl<Instruction*> &AddrModeInsts;
523   const TargetLowering &TLI;
524
525   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
526   /// the memory instruction that we're computing this address for.
527   const Type *AccessTy;
528   Instruction *MemoryInst;
529   
530   /// AddrMode - This is the addressing mode that we're building up.  This is
531   /// part of the return value of this addressing mode matching stuff.
532   ExtAddrMode &AddrMode;
533   
534   /// IgnoreProfitability - This is set to true when we should not do
535   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
536   /// always returns true.
537   bool IgnoreProfitability;
538   
539   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
540                         const TargetLowering &T, const Type *AT,
541                         Instruction *MI, ExtAddrMode &AM)
542     : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
543     IgnoreProfitability = false;
544   }
545 public:
546   
547   /// Match - Find the maximal addressing mode that a load/store of V can fold,
548   /// give an access type of AccessTy.  This returns a list of involved
549   /// instructions in AddrModeInsts.
550   static ExtAddrMode Match(Value *V, const Type *AccessTy,
551                            Instruction *MemoryInst,
552                            SmallVectorImpl<Instruction*> &AddrModeInsts,
553                            const TargetLowering &TLI) {
554     ExtAddrMode Result;
555
556     bool Success = 
557       AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
558                             MemoryInst, Result).MatchAddr(V, 0);
559     Success = Success; assert(Success && "Couldn't select *anything*?");
560     return Result;
561   }
562 private:
563   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
564   bool MatchAddr(Value *V, unsigned Depth);
565   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
566   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
567                                             ExtAddrMode &AMBefore,
568                                             ExtAddrMode &AMAfter);
569   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
570 };
571 } // end anonymous namespace
572
573 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
574 /// Return true and update AddrMode if this addr mode is legal for the target,
575 /// false if not.
576 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
577                                              unsigned Depth) {
578   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
579   // mode.  Just process that directly.
580   if (Scale == 1)
581     return MatchAddr(ScaleReg, Depth);
582   
583   // If the scale is 0, it takes nothing to add this.
584   if (Scale == 0)
585     return true;
586   
587   // If we already have a scale of this value, we can add to it, otherwise, we
588   // need an available scale field.
589   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
590     return false;
591
592   ExtAddrMode TestAddrMode = AddrMode;
593
594   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
595   // [A+B + A*7] -> [B+A*8].
596   TestAddrMode.Scale += Scale;
597   TestAddrMode.ScaledReg = ScaleReg;
598
599   // If the new address isn't legal, bail out.
600   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
601     return false;
602
603   // It was legal, so commit it.
604   AddrMode = TestAddrMode;
605   
606   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
607   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
608   // X*Scale + C*Scale to addr mode.
609   ConstantInt *CI; Value *AddLHS;
610   if (match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
611     TestAddrMode.ScaledReg = AddLHS;
612     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
613       
614     // If this addressing mode is legal, commit it and remember that we folded
615     // this instruction.
616     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
617       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
618       AddrMode = TestAddrMode;
619       return true;
620     }
621   }
622
623   // Otherwise, not (x+c)*scale, just return what we have.
624   return true;
625 }
626
627 /// MightBeFoldableInst - This is a little filter, which returns true if an
628 /// addressing computation involving I might be folded into a load/store
629 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
630 /// the set of instructions that MatchOperationAddr can.
631 static bool MightBeFoldableInst(Instruction *I) {
632   switch (I->getOpcode()) {
633   case Instruction::BitCast:
634     // Don't touch identity bitcasts.
635     if (I->getType() == I->getOperand(0)->getType())
636       return false;
637     return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
638   case Instruction::PtrToInt:
639     // PtrToInt is always a noop, as we know that the int type is pointer sized.
640     return true;
641   case Instruction::IntToPtr:
642     // We know the input is intptr_t, so this is foldable.
643     return true;
644   case Instruction::Add:
645     return true;
646   case Instruction::Mul:
647   case Instruction::Shl:
648     // Can only handle X*C and X << C.
649     return isa<ConstantInt>(I->getOperand(1));
650   case Instruction::GetElementPtr:
651     return true;
652   default:
653     return false;
654   }
655 }
656
657
658 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
659 /// fold the operation into the addressing mode.  If so, update the addressing
660 /// mode and return true, otherwise return false without modifying AddrMode.
661 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
662                                                unsigned Depth) {
663   // Avoid exponential behavior on extremely deep expression trees.
664   if (Depth >= 5) return false;
665   
666   switch (Opcode) {
667   case Instruction::PtrToInt:
668     // PtrToInt is always a noop, as we know that the int type is pointer sized.
669     return MatchAddr(AddrInst->getOperand(0), Depth);
670   case Instruction::IntToPtr:
671     // This inttoptr is a no-op if the integer type is pointer sized.
672     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
673         TLI.getPointerTy())
674       return MatchAddr(AddrInst->getOperand(0), Depth);
675     return false;
676   case Instruction::BitCast:
677     // BitCast is always a noop, and we can handle it as long as it is
678     // int->int or pointer->pointer (we don't want int<->fp or something).
679     if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
680          isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
681         // Don't touch identity bitcasts.  These were probably put here by LSR,
682         // and we don't want to mess around with them.  Assume it knows what it
683         // is doing.
684         AddrInst->getOperand(0)->getType() != AddrInst->getType())
685       return MatchAddr(AddrInst->getOperand(0), Depth);
686     return false;
687   case Instruction::Add: {
688     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
689     ExtAddrMode BackupAddrMode = AddrMode;
690     unsigned OldSize = AddrModeInsts.size();
691     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
692         MatchAddr(AddrInst->getOperand(0), Depth+1))
693       return true;
694     
695     // Restore the old addr mode info.
696     AddrMode = BackupAddrMode;
697     AddrModeInsts.resize(OldSize);
698     
699     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
700     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
701         MatchAddr(AddrInst->getOperand(1), Depth+1))
702       return true;
703     
704     // Otherwise we definitely can't merge the ADD in.
705     AddrMode = BackupAddrMode;
706     AddrModeInsts.resize(OldSize);
707     break;
708   }
709   //case Instruction::Or:
710   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
711   //break;
712   case Instruction::Mul:
713   case Instruction::Shl: {
714     // Can only handle X*C and X << C.
715     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
716     if (!RHS) return false;
717     int64_t Scale = RHS->getSExtValue();
718     if (Opcode == Instruction::Shl)
719       Scale = 1 << Scale;
720     
721     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
722   }
723   case Instruction::GetElementPtr: {
724     // Scan the GEP.  We check it if it contains constant offsets and at most
725     // one variable offset.
726     int VariableOperand = -1;
727     unsigned VariableScale = 0;
728     
729     int64_t ConstantOffset = 0;
730     const TargetData *TD = TLI.getTargetData();
731     gep_type_iterator GTI = gep_type_begin(AddrInst);
732     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
733       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
734         const StructLayout *SL = TD->getStructLayout(STy);
735         unsigned Idx =
736           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
737         ConstantOffset += SL->getElementOffset(Idx);
738       } else {
739         uint64_t TypeSize = TD->getABITypeSize(GTI.getIndexedType());
740         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
741           ConstantOffset += CI->getSExtValue()*TypeSize;
742         } else if (TypeSize) {  // Scales of zero don't do anything.
743           // We only allow one variable index at the moment.
744           if (VariableOperand != -1)
745             return false;
746           
747           // Remember the variable index.
748           VariableOperand = i;
749           VariableScale = TypeSize;
750         }
751       }
752     }
753     
754     // A common case is for the GEP to only do a constant offset.  In this case,
755     // just add it to the disp field and check validity.
756     if (VariableOperand == -1) {
757       AddrMode.BaseOffs += ConstantOffset;
758       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
759         // Check to see if we can fold the base pointer in too.
760         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
761           return true;
762       }
763       AddrMode.BaseOffs -= ConstantOffset;
764       return false;
765     }
766
767     // Save the valid addressing mode in case we can't match.
768     ExtAddrMode BackupAddrMode = AddrMode;
769     
770     // Check that this has no base reg yet.  If so, we won't have a place to
771     // put the base of the GEP (assuming it is not a null ptr).
772     bool SetBaseReg = true;
773     if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
774       SetBaseReg = false;   // null pointer base doesn't need representation.
775     else if (AddrMode.HasBaseReg)
776       return false;  // Base register already specified, can't match GEP.
777     else {
778       // Otherwise, we'll use the GEP base as the BaseReg.
779       AddrMode.HasBaseReg = true;
780       AddrMode.BaseReg = AddrInst->getOperand(0);
781     }
782     
783     // See if the scale and offset amount is valid for this target.
784     AddrMode.BaseOffs += ConstantOffset;
785     
786     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
787                           Depth)) {
788       AddrMode = BackupAddrMode;
789       return false;
790     }
791     
792     // If we have a null as the base of the GEP, folding in the constant offset
793     // plus variable scale is all we can do.
794     if (!SetBaseReg) return true;
795       
796     // If this match succeeded, we know that we can form an address with the
797     // GepBase as the basereg.  Match the base pointer of the GEP more
798     // aggressively by zeroing out BaseReg and rematching.  If the base is
799     // (for example) another GEP, this allows merging in that other GEP into
800     // the addressing mode we're forming.
801     AddrMode.HasBaseReg = false;
802     AddrMode.BaseReg = 0;
803     bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
804     assert(Success && "MatchAddr should be able to fill in BaseReg!");
805     Success=Success;
806     return true;
807   }
808   }
809   return false;
810 }
811
812 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
813 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
814 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
815 /// or intptr_t for the target.
816 ///
817 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
818   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
819     // Fold in immediates if legal for the target.
820     AddrMode.BaseOffs += CI->getSExtValue();
821     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
822       return true;
823     AddrMode.BaseOffs -= CI->getSExtValue();
824   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
825     // If this is a global variable, try to fold it into the addressing mode.
826     if (AddrMode.BaseGV == 0) {
827       AddrMode.BaseGV = GV;
828       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
829         return true;
830       AddrMode.BaseGV = 0;
831     }
832   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
833     ExtAddrMode BackupAddrMode = AddrMode;
834     unsigned OldSize = AddrModeInsts.size();
835
836     // Check to see if it is possible to fold this operation.
837     if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
838       // Okay, it's possible to fold this.  Check to see if it is actually
839       // *profitable* to do so.  We use a simple cost model to avoid increasing
840       // register pressure too much.
841       if (I->hasOneUse() ||
842           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
843         AddrModeInsts.push_back(I);
844         return true;
845       }
846       
847       // It isn't profitable to do this, roll back.
848       //cerr << "NOT FOLDING: " << *I;
849       AddrMode = BackupAddrMode;
850       AddrModeInsts.resize(OldSize);
851     }
852   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
853     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
854       return true;
855   } else if (isa<ConstantPointerNull>(Addr)) {
856     // Null pointer gets folded without affecting the addressing mode.
857     return true;
858   }
859
860   // Worse case, the target should support [reg] addressing modes. :)
861   if (!AddrMode.HasBaseReg) {
862     AddrMode.HasBaseReg = true;
863     AddrMode.BaseReg = Addr;
864     // Still check for legality in case the target supports [imm] but not [i+r].
865     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
866       return true;
867     AddrMode.HasBaseReg = false;
868     AddrMode.BaseReg = 0;
869   }
870
871   // If the base register is already taken, see if we can do [r+r].
872   if (AddrMode.Scale == 0) {
873     AddrMode.Scale = 1;
874     AddrMode.ScaledReg = Addr;
875     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
876       return true;
877     AddrMode.Scale = 0;
878     AddrMode.ScaledReg = 0;
879   }
880   // Couldn't match.
881   return false;
882 }
883
884
885 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
886 /// inline asm call are due to memory operands.  If so, return true, otherwise
887 /// return false.
888 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
889                                     const TargetLowering &TLI) {
890   std::vector<InlineAsm::ConstraintInfo>
891   Constraints = IA->ParseConstraints();
892   
893   unsigned ArgNo = 1;   // ArgNo - The operand of the CallInst.
894   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
895     TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
896     
897     // Compute the value type for each operand.
898     switch (OpInfo.Type) {
899       case InlineAsm::isOutput:
900         if (OpInfo.isIndirect)
901           OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
902         break;
903       case InlineAsm::isInput:
904         OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
905         break;
906       case InlineAsm::isClobber:
907         // Nothing to do.
908         break;
909     }
910     
911     // Compute the constraint code and ConstraintType to use.
912     TLI.ComputeConstraintToUse(OpInfo, SDValue(),
913                              OpInfo.ConstraintType == TargetLowering::C_Memory);
914     
915     // If this asm operand is our Value*, and if it isn't an indirect memory
916     // operand, we can't fold it!
917     if (OpInfo.CallOperandVal == OpVal &&
918         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
919          !OpInfo.isIndirect))
920       return false;
921   }
922   
923   return true;
924 }
925
926
927 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
928 /// memory use.  If we find an obviously non-foldable instruction, return true.
929 /// Add the ultimately found memory instructions to MemoryUses.
930 static bool FindAllMemoryUses(Instruction *I,
931                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
932                               SmallPtrSet<Instruction*, 16> &ConsideredInsts,
933                               const TargetLowering &TLI) {
934   // If we already considered this instruction, we're done.
935   if (!ConsideredInsts.insert(I))
936     return false;
937   
938   // If this is an obviously unfoldable instruction, bail out.
939   if (!MightBeFoldableInst(I))
940     return true;
941
942   // Loop over all the uses, recursively processing them.
943   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
944        UI != E; ++UI) {
945     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
946       MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
947       continue;
948     }
949     
950     if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
951       if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
952       MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
953       continue;
954     }
955     
956     if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
957       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
958       if (IA == 0) return true;
959       
960       // If this is a memory operand, we're cool, otherwise bail out.
961       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
962         return true;
963       continue;
964     }
965     
966     if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
967                           TLI))
968       return true;
969   }
970
971   return false;
972 }
973
974
975 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
976 /// the use site that we're folding it into.  If so, there is no cost to
977 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
978 /// that we know are live at the instruction already.
979 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
980                                                    Value *KnownLive2) {
981   // If Val is either of the known-live values, we know it is live!
982   if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
983     return true;
984   
985   // All values other than instructions and arguments (e.g. constants) are live.
986   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
987   
988   // If Val is a constant sized alloca in the entry block, it is live, this is
989   // true because it is just a reference to the stack/frame pointer, which is
990   // live for the whole function.
991   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
992     if (AI->isStaticAlloca())
993       return true;
994   
995   // Check to see if this value is already used in the memory instruction's
996   // block.  If so, it's already live into the block at the very least, so we
997   // can reasonably fold it.
998   BasicBlock *MemBB = MemoryInst->getParent();
999   for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
1000        UI != E; ++UI)
1001     // We know that uses of arguments and instructions have to be instructions.
1002     if (cast<Instruction>(*UI)->getParent() == MemBB)
1003       return true;
1004   
1005   return false;
1006 }
1007
1008
1009
1010 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
1011 /// mode of the machine to fold the specified instruction into a load or store
1012 /// that ultimately uses it.  However, the specified instruction has multiple
1013 /// uses.  Given this, it may actually increase register pressure to fold it
1014 /// into the load.  For example, consider this code:
1015 ///
1016 ///     X = ...
1017 ///     Y = X+1
1018 ///     use(Y)   -> nonload/store
1019 ///     Z = Y+1
1020 ///     load Z
1021 ///
1022 /// In this case, Y has multiple uses, and can be folded into the load of Z
1023 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
1024 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
1025 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
1026 /// number of computations either.
1027 ///
1028 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
1029 /// X was live across 'load Z' for other reasons, we actually *would* want to
1030 /// fold the addressing mode in the Z case.  This would make Y die earlier.
1031 bool AddressingModeMatcher::
1032 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
1033                                      ExtAddrMode &AMAfter) {
1034   if (IgnoreProfitability) return true;
1035   
1036   // AMBefore is the addressing mode before this instruction was folded into it,
1037   // and AMAfter is the addressing mode after the instruction was folded.  Get
1038   // the set of registers referenced by AMAfter and subtract out those
1039   // referenced by AMBefore: this is the set of values which folding in this
1040   // address extends the lifetime of.
1041   //
1042   // Note that there are only two potential values being referenced here,
1043   // BaseReg and ScaleReg (global addresses are always available, as are any
1044   // folded immediates).
1045   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
1046   
1047   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
1048   // lifetime wasn't extended by adding this instruction.
1049   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1050     BaseReg = 0;
1051   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
1052     ScaledReg = 0;
1053
1054   // If folding this instruction (and it's subexprs) didn't extend any live
1055   // ranges, we're ok with it.
1056   if (BaseReg == 0 && ScaledReg == 0)
1057     return true;
1058
1059   // If all uses of this instruction are ultimately load/store/inlineasm's,
1060   // check to see if their addressing modes will include this instruction.  If
1061   // so, we can fold it into all uses, so it doesn't matter if it has multiple
1062   // uses.
1063   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
1064   SmallPtrSet<Instruction*, 16> ConsideredInsts;
1065   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
1066     return false;  // Has a non-memory, non-foldable use!
1067   
1068   // Now that we know that all uses of this instruction are part of a chain of
1069   // computation involving only operations that could theoretically be folded
1070   // into a memory use, loop over each of these uses and see if they could
1071   // *actually* fold the instruction.
1072   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
1073   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
1074     Instruction *User = MemoryUses[i].first;
1075     unsigned OpNo = MemoryUses[i].second;
1076     
1077     // Get the access type of this use.  If the use isn't a pointer, we don't
1078     // know what it accesses.
1079     Value *Address = User->getOperand(OpNo);
1080     if (!isa<PointerType>(Address->getType()))
1081       return false;
1082     const Type *AddressAccessTy =
1083       cast<PointerType>(Address->getType())->getElementType();
1084     
1085     // Do a match against the root of this address, ignoring profitability. This
1086     // will tell us if the addressing mode for the memory operation will
1087     // *actually* cover the shared instruction.
1088     ExtAddrMode Result;
1089     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
1090                                   MemoryInst, Result);
1091     Matcher.IgnoreProfitability = true;
1092     bool Success = Matcher.MatchAddr(Address, 0);
1093     Success = Success; assert(Success && "Couldn't select *anything*?");
1094
1095     // If the match didn't cover I, then it won't be shared by it.
1096     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
1097                   I) == MatchedAddrModeInsts.end())
1098       return false;
1099     
1100     MatchedAddrModeInsts.clear();
1101   }
1102   
1103   return true;
1104 }
1105
1106
1107 //===----------------------------------------------------------------------===//
1108 // Memory Optimization
1109 //===----------------------------------------------------------------------===//
1110
1111 /// IsNonLocalValue - Return true if the specified values are defined in a
1112 /// different basic block than BB.
1113 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
1114   if (Instruction *I = dyn_cast<Instruction>(V))
1115     return I->getParent() != BB;
1116   return false;
1117 }
1118
1119 /// OptimizeMemoryInst - Load and Store Instructions have often have
1120 /// addressing modes that can do significant amounts of computation.  As such,
1121 /// instruction selection will try to get the load or store to do as much
1122 /// computation as possible for the program.  The problem is that isel can only
1123 /// see within a single block.  As such, we sink as much legal addressing mode
1124 /// stuff into the block as possible.
1125 ///
1126 /// This method is used to optimize both load/store and inline asms with memory
1127 /// operands.
1128 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
1129                                         const Type *AccessTy,
1130                                         DenseMap<Value*,Value*> &SunkAddrs) {
1131   // Figure out what addressing mode will be built up for this operation.
1132   SmallVector<Instruction*, 16> AddrModeInsts;
1133   ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
1134                                                       AddrModeInsts, *TLI);
1135
1136   // Check to see if any of the instructions supersumed by this addr mode are
1137   // non-local to I's BB.
1138   bool AnyNonLocal = false;
1139   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
1140     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
1141       AnyNonLocal = true;
1142       break;
1143     }
1144   }
1145
1146   // If all the instructions matched are already in this BB, don't do anything.
1147   if (!AnyNonLocal) {
1148     DEBUG(cerr << "CGP: Found      local addrmode: " << AddrMode << "\n");
1149     return false;
1150   }
1151
1152   // Insert this computation right after this user.  Since our caller is
1153   // scanning from the top of the BB to the bottom, reuse of the expr are
1154   // guaranteed to happen later.
1155   BasicBlock::iterator InsertPt = MemoryInst;
1156
1157   // Now that we determined the addressing expression we want to use and know
1158   // that we have to sink it into this block.  Check to see if we have already
1159   // done this for some other load/store instr in this block.  If so, reuse the
1160   // computation.
1161   Value *&SunkAddr = SunkAddrs[Addr];
1162   if (SunkAddr) {
1163     DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
1164     if (SunkAddr->getType() != Addr->getType())
1165       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
1166   } else {
1167     DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
1168     const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
1169
1170     Value *Result = 0;
1171     // Start with the scale value.
1172     if (AddrMode.Scale) {
1173       Value *V = AddrMode.ScaledReg;
1174       if (V->getType() == IntPtrTy) {
1175         // done.
1176       } else if (isa<PointerType>(V->getType())) {
1177         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1178       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
1179                  cast<IntegerType>(V->getType())->getBitWidth()) {
1180         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
1181       } else {
1182         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
1183       }
1184       if (AddrMode.Scale != 1)
1185         V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
1186                                                           AddrMode.Scale),
1187                                       "sunkaddr", InsertPt);
1188       Result = V;
1189     }
1190
1191     // Add in the base register.
1192     if (AddrMode.BaseReg) {
1193       Value *V = AddrMode.BaseReg;
1194       if (V->getType() != IntPtrTy)
1195         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
1196       if (Result)
1197         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1198       else
1199         Result = V;
1200     }
1201
1202     // Add in the BaseGV if present.
1203     if (AddrMode.BaseGV) {
1204       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
1205                                   InsertPt);
1206       if (Result)
1207         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1208       else
1209         Result = V;
1210     }
1211
1212     // Add in the Base Offset if present.
1213     if (AddrMode.BaseOffs) {
1214       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
1215       if (Result)
1216         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
1217       else
1218         Result = V;
1219     }
1220
1221     if (Result == 0)
1222       SunkAddr = Constant::getNullValue(Addr->getType());
1223     else
1224       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
1225   }
1226
1227   MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
1228
1229   if (Addr->use_empty())
1230     EraseDeadInstructions(Addr);
1231   return true;
1232 }
1233
1234 /// OptimizeInlineAsmInst - If there are any memory operands, use
1235 /// OptimizeMemoryInst to sink their address computing into the block when
1236 /// possible / profitable.
1237 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
1238                                            DenseMap<Value*,Value*> &SunkAddrs) {
1239   bool MadeChange = false;
1240   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
1241
1242   // Do a prepass over the constraints, canonicalizing them, and building up the
1243   // ConstraintOperands list.
1244   std::vector<InlineAsm::ConstraintInfo>
1245     ConstraintInfos = IA->ParseConstraints();
1246
1247   /// ConstraintOperands - Information about all of the constraints.
1248   std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
1249   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
1250   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
1251     ConstraintOperands.
1252       push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
1253     TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
1254
1255     // Compute the value type for each operand.
1256     switch (OpInfo.Type) {
1257     case InlineAsm::isOutput:
1258       if (OpInfo.isIndirect)
1259         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1260       break;
1261     case InlineAsm::isInput:
1262       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
1263       break;
1264     case InlineAsm::isClobber:
1265       // Nothing to do.
1266       break;
1267     }
1268
1269     // Compute the constraint code and ConstraintType to use.
1270     TLI->ComputeConstraintToUse(OpInfo, SDValue(),
1271                              OpInfo.ConstraintType == TargetLowering::C_Memory);
1272
1273     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
1274         OpInfo.isIndirect) {
1275       Value *OpVal = OpInfo.CallOperandVal;
1276       MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
1277     }
1278   }
1279
1280   return MadeChange;
1281 }
1282
1283 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
1284   BasicBlock *DefBB = I->getParent();
1285
1286   // If both result of the {s|z}xt and its source are live out, rewrite all
1287   // other uses of the source with result of extension.
1288   Value *Src = I->getOperand(0);
1289   if (Src->hasOneUse())
1290     return false;
1291
1292   // Only do this xform if truncating is free.
1293   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
1294     return false;
1295
1296   // Only safe to perform the optimization if the source is also defined in
1297   // this block.
1298   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
1299     return false;
1300
1301   bool DefIsLiveOut = false;
1302   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1303        UI != E; ++UI) {
1304     Instruction *User = cast<Instruction>(*UI);
1305
1306     // Figure out which BB this ext is used in.
1307     BasicBlock *UserBB = User->getParent();
1308     if (UserBB == DefBB) continue;
1309     DefIsLiveOut = true;
1310     break;
1311   }
1312   if (!DefIsLiveOut)
1313     return false;
1314
1315   // Make sure non of the uses are PHI nodes.
1316   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1317        UI != E; ++UI) {
1318     Instruction *User = cast<Instruction>(*UI);
1319     BasicBlock *UserBB = User->getParent();
1320     if (UserBB == DefBB) continue;
1321     // Be conservative. We don't want this xform to end up introducing
1322     // reloads just before load / store instructions.
1323     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
1324       return false;
1325   }
1326
1327   // InsertedTruncs - Only insert one trunc in each block once.
1328   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
1329
1330   bool MadeChange = false;
1331   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
1332        UI != E; ++UI) {
1333     Use &TheUse = UI.getUse();
1334     Instruction *User = cast<Instruction>(*UI);
1335
1336     // Figure out which BB this ext is used in.
1337     BasicBlock *UserBB = User->getParent();
1338     if (UserBB == DefBB) continue;
1339
1340     // Both src and def are live in this block. Rewrite the use.
1341     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
1342
1343     if (!InsertedTrunc) {
1344       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
1345
1346       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
1347     }
1348
1349     // Replace a use of the {s|z}ext source with a use of the result.
1350     TheUse = InsertedTrunc;
1351
1352     MadeChange = true;
1353   }
1354
1355   return MadeChange;
1356 }
1357
1358 // In this pass we look for GEP and cast instructions that are used
1359 // across basic blocks and rewrite them to improve basic-block-at-a-time
1360 // selection.
1361 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
1362   bool MadeChange = false;
1363
1364   // Split all critical edges where the dest block has a PHI and where the phi
1365   // has shared immediate operands.
1366   TerminatorInst *BBTI = BB.getTerminator();
1367   if (BBTI->getNumSuccessors() > 1) {
1368     for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i)
1369       if (isa<PHINode>(BBTI->getSuccessor(i)->begin()) &&
1370           isCriticalEdge(BBTI, i, true))
1371         SplitEdgeNicely(BBTI, i, this);
1372   }
1373
1374
1375   // Keep track of non-local addresses that have been sunk into this block.
1376   // This allows us to avoid inserting duplicate code for blocks with multiple
1377   // load/stores of the same address.
1378   DenseMap<Value*, Value*> SunkAddrs;
1379
1380   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
1381     Instruction *I = BBI++;
1382
1383     if (CastInst *CI = dyn_cast<CastInst>(I)) {
1384       // If the source of the cast is a constant, then this should have
1385       // already been constant folded.  The only reason NOT to constant fold
1386       // it is if something (e.g. LSR) was careful to place the constant
1387       // evaluation in a block other than then one that uses it (e.g. to hoist
1388       // the address of globals out of a loop).  If this is the case, we don't
1389       // want to forward-subst the cast.
1390       if (isa<Constant>(CI->getOperand(0)))
1391         continue;
1392
1393       bool Change = false;
1394       if (TLI) {
1395         Change = OptimizeNoopCopyExpression(CI, *TLI);
1396         MadeChange |= Change;
1397       }
1398
1399       if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
1400         MadeChange |= OptimizeExtUses(I);
1401     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
1402       MadeChange |= OptimizeCmpExpression(CI);
1403     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
1404       if (TLI)
1405         MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
1406                                          SunkAddrs);
1407     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1408       if (TLI)
1409         MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1410                                          SI->getOperand(0)->getType(),
1411                                          SunkAddrs);
1412     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1413       if (GEPI->hasAllZeroIndices()) {
1414         /// The GEP operand must be a pointer, so must its result -> BitCast
1415         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1416                                           GEPI->getName(), GEPI);
1417         GEPI->replaceAllUsesWith(NC);
1418         GEPI->eraseFromParent();
1419         MadeChange = true;
1420         BBI = NC;
1421       }
1422     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1423       // If we found an inline asm expession, and if the target knows how to
1424       // lower it to normal LLVM code, do so now.
1425       if (TLI && isa<InlineAsm>(CI->getCalledValue()))
1426         if (const TargetAsmInfo *TAI =
1427             TLI->getTargetMachine().getTargetAsmInfo()) {
1428           if (TAI->ExpandInlineAsm(CI))
1429             BBI = BB.begin();
1430           else
1431             // Sink address computing for memory operands into the block.
1432             MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1433         }
1434     }
1435   }
1436
1437   return MadeChange;
1438 }