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