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