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