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