CodeGenPrepare.cpp revision 95bb00414eba82cc1c058b558cd28bc28134c561
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/IntrinsicInst.h"
24#include "llvm/Pass.h"
25#include "llvm/Analysis/InstructionSimplify.h"
26#include "llvm/Analysis/ProfileInfo.h"
27#include "llvm/Target/TargetData.h"
28#include "llvm/Target/TargetLowering.h"
29#include "llvm/Transforms/Utils/AddrModeMatcher.h"
30#include "llvm/Transforms/Utils/BasicBlockUtils.h"
31#include "llvm/Transforms/Utils/Local.h"
32#include "llvm/Transforms/Utils/BuildLibCalls.h"
33#include "llvm/ADT/DenseMap.h"
34#include "llvm/ADT/SmallSet.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/Assembly/Writer.h"
37#include "llvm/Support/CallSite.h"
38#include "llvm/Support/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/GetElementPtrTypeIterator.h"
41#include "llvm/Support/PatternMatch.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/Support/IRBuilder.h"
44using namespace llvm;
45using namespace llvm::PatternMatch;
46
47STATISTIC(NumElim,  "Number of blocks eliminated");
48
49static cl::opt<bool>
50CriticalEdgeSplit("cgp-critical-edge-splitting",
51                  cl::desc("Split critical edges during codegen prepare"),
52                  cl::init(false), cl::Hidden);
53
54namespace {
55  class CodeGenPrepare : public FunctionPass {
56    /// TLI - Keep a pointer of a TargetLowering to consult for determining
57    /// transformation profitability.
58    const TargetLowering *TLI;
59    ProfileInfo *PFI;
60
61    /// BackEdges - Keep a set of all the loop back edges.
62    ///
63    SmallSet<std::pair<const BasicBlock*, const BasicBlock*>, 8> BackEdges;
64  public:
65    static char ID; // Pass identification, replacement for typeid
66    explicit CodeGenPrepare(const TargetLowering *tli = 0)
67      : FunctionPass(ID), TLI(tli) {
68        initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
69      }
70    bool runOnFunction(Function &F);
71
72    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
73      AU.addPreserved<ProfileInfo>();
74    }
75
76    virtual void releaseMemory() {
77      BackEdges.clear();
78    }
79
80  private:
81    bool EliminateMostlyEmptyBlocks(Function &F);
82    bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
83    void EliminateMostlyEmptyBlock(BasicBlock *BB);
84    bool OptimizeBlock(BasicBlock &BB);
85    bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
86                            DenseMap<Value*,Value*> &SunkAddrs);
87    bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
88                               DenseMap<Value*,Value*> &SunkAddrs);
89    bool OptimizeCallInst(CallInst *CI);
90    bool MoveExtToFormExtLoad(Instruction *I);
91    bool OptimizeExtUses(Instruction *I);
92    void findLoopBackEdges(const Function &F);
93  };
94}
95
96char CodeGenPrepare::ID = 0;
97INITIALIZE_PASS(CodeGenPrepare, "codegenprepare",
98                "Optimize for code generation", false, false)
99
100FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
101  return new CodeGenPrepare(TLI);
102}
103
104/// findLoopBackEdges - Do a DFS walk to find loop back edges.
105///
106void CodeGenPrepare::findLoopBackEdges(const Function &F) {
107  SmallVector<std::pair<const BasicBlock*,const BasicBlock*>, 32> Edges;
108  FindFunctionBackedges(F, Edges);
109
110  BackEdges.insert(Edges.begin(), Edges.end());
111}
112
113
114bool CodeGenPrepare::runOnFunction(Function &F) {
115  bool EverMadeChange = false;
116
117  PFI = getAnalysisIfAvailable<ProfileInfo>();
118  // First pass, eliminate blocks that contain only PHI nodes and an
119  // unconditional branch.
120  EverMadeChange |= EliminateMostlyEmptyBlocks(F);
121
122  // Now find loop back edges, but only if they are being used to decide which
123  // critical edges to split.
124  if (CriticalEdgeSplit)
125    findLoopBackEdges(F);
126
127  bool MadeChange = true;
128  while (MadeChange) {
129    MadeChange = false;
130    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
131      MadeChange |= OptimizeBlock(*BB);
132    EverMadeChange |= MadeChange;
133  }
134  return EverMadeChange;
135}
136
137/// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes,
138/// debug info directives, and an unconditional branch.  Passes before isel
139/// (e.g. LSR/loopsimplify) often split edges in ways that are non-optimal for
140/// isel.  Start by eliminating these blocks so we can split them the way we
141/// want them.
142bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
143  bool MadeChange = false;
144  // Note that this intentionally skips the entry block.
145  for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
146    BasicBlock *BB = I++;
147
148    // If this block doesn't end with an uncond branch, ignore it.
149    BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
150    if (!BI || !BI->isUnconditional())
151      continue;
152
153    // If the instruction before the branch (skipping debug info) isn't a phi
154    // node, then other stuff is happening here.
155    BasicBlock::iterator BBI = BI;
156    if (BBI != BB->begin()) {
157      --BBI;
158      while (isa<DbgInfoIntrinsic>(BBI)) {
159        if (BBI == BB->begin())
160          break;
161        --BBI;
162      }
163      if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
164        continue;
165    }
166
167    // Do not break infinite loops.
168    BasicBlock *DestBB = BI->getSuccessor(0);
169    if (DestBB == BB)
170      continue;
171
172    if (!CanMergeBlocks(BB, DestBB))
173      continue;
174
175    EliminateMostlyEmptyBlock(BB);
176    MadeChange = true;
177  }
178  return MadeChange;
179}
180
181/// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
182/// single uncond branch between them, and BB contains no other non-phi
183/// instructions.
184bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
185                                    const BasicBlock *DestBB) const {
186  // We only want to eliminate blocks whose phi nodes are used by phi nodes in
187  // the successor.  If there are more complex condition (e.g. preheaders),
188  // don't mess around with them.
189  BasicBlock::const_iterator BBI = BB->begin();
190  while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
191    for (Value::const_use_iterator UI = PN->use_begin(), E = PN->use_end();
192         UI != E; ++UI) {
193      const Instruction *User = cast<Instruction>(*UI);
194      if (User->getParent() != DestBB || !isa<PHINode>(User))
195        return false;
196      // If User is inside DestBB block and it is a PHINode then check
197      // incoming value. If incoming value is not from BB then this is
198      // a complex condition (e.g. preheaders) we want to avoid here.
199      if (User->getParent() == DestBB) {
200        if (const PHINode *UPN = dyn_cast<PHINode>(User))
201          for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
202            Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
203            if (Insn && Insn->getParent() == BB &&
204                Insn->getParent() != UPN->getIncomingBlock(I))
205              return false;
206          }
207      }
208    }
209  }
210
211  // If BB and DestBB contain any common predecessors, then the phi nodes in BB
212  // and DestBB may have conflicting incoming values for the block.  If so, we
213  // can't merge the block.
214  const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
215  if (!DestBBPN) return true;  // no conflict.
216
217  // Collect the preds of BB.
218  SmallPtrSet<const BasicBlock*, 16> BBPreds;
219  if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
220    // It is faster to get preds from a PHI than with pred_iterator.
221    for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
222      BBPreds.insert(BBPN->getIncomingBlock(i));
223  } else {
224    BBPreds.insert(pred_begin(BB), pred_end(BB));
225  }
226
227  // Walk the preds of DestBB.
228  for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
229    BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
230    if (BBPreds.count(Pred)) {   // Common predecessor?
231      BBI = DestBB->begin();
232      while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
233        const Value *V1 = PN->getIncomingValueForBlock(Pred);
234        const Value *V2 = PN->getIncomingValueForBlock(BB);
235
236        // If V2 is a phi node in BB, look up what the mapped value will be.
237        if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
238          if (V2PN->getParent() == BB)
239            V2 = V2PN->getIncomingValueForBlock(Pred);
240
241        // If there is a conflict, bail out.
242        if (V1 != V2) return false;
243      }
244    }
245  }
246
247  return true;
248}
249
250
251/// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
252/// an unconditional branch in it.
253void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
254  BranchInst *BI = cast<BranchInst>(BB->getTerminator());
255  BasicBlock *DestBB = BI->getSuccessor(0);
256
257  DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
258
259  // If the destination block has a single pred, then this is a trivial edge,
260  // just collapse it.
261  if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
262    if (SinglePred != DestBB) {
263      // Remember if SinglePred was the entry block of the function.  If so, we
264      // will need to move BB back to the entry position.
265      bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
266      MergeBasicBlockIntoOnlyPred(DestBB, this);
267
268      if (isEntry && BB != &BB->getParent()->getEntryBlock())
269        BB->moveBefore(&BB->getParent()->getEntryBlock());
270
271      DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
272      return;
273    }
274  }
275
276  // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
277  // to handle the new incoming edges it is about to have.
278  PHINode *PN;
279  for (BasicBlock::iterator BBI = DestBB->begin();
280       (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
281    // Remove the incoming value for BB, and remember it.
282    Value *InVal = PN->removeIncomingValue(BB, false);
283
284    // Two options: either the InVal is a phi node defined in BB or it is some
285    // value that dominates BB.
286    PHINode *InValPhi = dyn_cast<PHINode>(InVal);
287    if (InValPhi && InValPhi->getParent() == BB) {
288      // Add all of the input values of the input PHI as inputs of this phi.
289      for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
290        PN->addIncoming(InValPhi->getIncomingValue(i),
291                        InValPhi->getIncomingBlock(i));
292    } else {
293      // Otherwise, add one instance of the dominating value for each edge that
294      // we will be adding.
295      if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
296        for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
297          PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
298      } else {
299        for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
300          PN->addIncoming(InVal, *PI);
301      }
302    }
303  }
304
305  // The PHIs are now updated, change everything that refers to BB to use
306  // DestBB and remove BB.
307  BB->replaceAllUsesWith(DestBB);
308  if (PFI) {
309    PFI->replaceAllUses(BB, DestBB);
310    PFI->removeEdge(ProfileInfo::getEdge(BB, DestBB));
311  }
312  BB->eraseFromParent();
313  ++NumElim;
314
315  DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
316}
317
318/// FindReusablePredBB - Check all of the predecessors of the block DestPHI
319/// lives in to see if there is a block that we can reuse as a critical edge
320/// from TIBB.
321static BasicBlock *FindReusablePredBB(PHINode *DestPHI, BasicBlock *TIBB) {
322  BasicBlock *Dest = DestPHI->getParent();
323
324  /// TIPHIValues - This array is lazily computed to determine the values of
325  /// PHIs in Dest that TI would provide.
326  SmallVector<Value*, 32> TIPHIValues;
327
328  /// TIBBEntryNo - This is a cache to speed up pred queries for TIBB.
329  unsigned TIBBEntryNo = 0;
330
331  // Check to see if Dest has any blocks that can be used as a split edge for
332  // this terminator.
333  for (unsigned pi = 0, e = DestPHI->getNumIncomingValues(); pi != e; ++pi) {
334    BasicBlock *Pred = DestPHI->getIncomingBlock(pi);
335    // To be usable, the pred has to end with an uncond branch to the dest.
336    BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
337    if (!PredBr || !PredBr->isUnconditional())
338      continue;
339    // Must be empty other than the branch and debug info.
340    BasicBlock::iterator I = Pred->begin();
341    while (isa<DbgInfoIntrinsic>(I))
342      I++;
343    if (&*I != PredBr)
344      continue;
345    // Cannot be the entry block; its label does not get emitted.
346    if (Pred == &Dest->getParent()->getEntryBlock())
347      continue;
348
349    // Finally, since we know that Dest has phi nodes in it, we have to make
350    // sure that jumping to Pred will have the same effect as going to Dest in
351    // terms of PHI values.
352    PHINode *PN;
353    unsigned PHINo = 0;
354    unsigned PredEntryNo = pi;
355
356    bool FoundMatch = true;
357    for (BasicBlock::iterator I = Dest->begin();
358         (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
359      if (PHINo == TIPHIValues.size()) {
360        if (PN->getIncomingBlock(TIBBEntryNo) != TIBB)
361          TIBBEntryNo = PN->getBasicBlockIndex(TIBB);
362        TIPHIValues.push_back(PN->getIncomingValue(TIBBEntryNo));
363      }
364
365      // If the PHI entry doesn't work, we can't use this pred.
366      if (PN->getIncomingBlock(PredEntryNo) != Pred)
367        PredEntryNo = PN->getBasicBlockIndex(Pred);
368
369      if (TIPHIValues[PHINo] != PN->getIncomingValue(PredEntryNo)) {
370        FoundMatch = false;
371        break;
372      }
373    }
374
375    // If we found a workable predecessor, change TI to branch to Succ.
376    if (FoundMatch)
377      return Pred;
378  }
379  return 0;
380}
381
382
383/// SplitEdgeNicely - Split the critical edge from TI to its specified
384/// successor if it will improve codegen.  We only do this if the successor has
385/// phi nodes (otherwise critical edges are ok).  If there is already another
386/// predecessor of the succ that is empty (and thus has no phi nodes), use it
387/// instead of introducing a new block.
388static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
389                     SmallSet<std::pair<const BasicBlock*,
390                                        const BasicBlock*>, 8> &BackEdges,
391                             Pass *P) {
392  BasicBlock *TIBB = TI->getParent();
393  BasicBlock *Dest = TI->getSuccessor(SuccNum);
394  assert(isa<PHINode>(Dest->begin()) &&
395         "This should only be called if Dest has a PHI!");
396  PHINode *DestPHI = cast<PHINode>(Dest->begin());
397
398  // Do not split edges to EH landing pads.
399  if (InvokeInst *Invoke = dyn_cast<InvokeInst>(TI))
400    if (Invoke->getSuccessor(1) == Dest)
401      return;
402
403  // As a hack, never split backedges of loops.  Even though the copy for any
404  // PHIs inserted on the backedge would be dead for exits from the loop, we
405  // assume that the cost of *splitting* the backedge would be too high.
406  if (BackEdges.count(std::make_pair(TIBB, Dest)))
407    return;
408
409  if (BasicBlock *ReuseBB = FindReusablePredBB(DestPHI, TIBB)) {
410    ProfileInfo *PFI = P->getAnalysisIfAvailable<ProfileInfo>();
411    if (PFI)
412      PFI->splitEdge(TIBB, Dest, ReuseBB);
413    Dest->removePredecessor(TIBB);
414    TI->setSuccessor(SuccNum, ReuseBB);
415    return;
416  }
417
418  SplitCriticalEdge(TI, SuccNum, P, true);
419}
420
421
422/// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
423/// copy (e.g. it's casting from one pointer type to another, i32->i8 on PPC),
424/// sink it into user blocks to reduce the number of virtual
425/// registers that must be created and coalesced.
426///
427/// Return true if any changes are made.
428///
429static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
430  // If this is a noop copy,
431  EVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
432  EVT DstVT = TLI.getValueType(CI->getType());
433
434  // This is an fp<->int conversion?
435  if (SrcVT.isInteger() != DstVT.isInteger())
436    return false;
437
438  // If this is an extension, it will be a zero or sign extension, which
439  // isn't a noop.
440  if (SrcVT.bitsLT(DstVT)) return false;
441
442  // If these values will be promoted, find out what they will be promoted
443  // to.  This helps us consider truncates on PPC as noop copies when they
444  // are.
445  if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
446    SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
447  if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
448    DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
449
450  // If, after promotion, these are the same types, this is a noop copy.
451  if (SrcVT != DstVT)
452    return false;
453
454  BasicBlock *DefBB = CI->getParent();
455
456  /// InsertedCasts - Only insert a cast in each block once.
457  DenseMap<BasicBlock*, CastInst*> InsertedCasts;
458
459  bool MadeChange = false;
460  for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
461       UI != E; ) {
462    Use &TheUse = UI.getUse();
463    Instruction *User = cast<Instruction>(*UI);
464
465    // Figure out which BB this cast is used in.  For PHI's this is the
466    // appropriate predecessor block.
467    BasicBlock *UserBB = User->getParent();
468    if (PHINode *PN = dyn_cast<PHINode>(User)) {
469      UserBB = PN->getIncomingBlock(UI);
470    }
471
472    // Preincrement use iterator so we don't invalidate it.
473    ++UI;
474
475    // If this user is in the same block as the cast, don't change the cast.
476    if (UserBB == DefBB) continue;
477
478    // If we have already inserted a cast into this block, use it.
479    CastInst *&InsertedCast = InsertedCasts[UserBB];
480
481    if (!InsertedCast) {
482      BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
483
484      InsertedCast =
485        CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
486                         InsertPt);
487      MadeChange = true;
488    }
489
490    // Replace a use of the cast with a use of the new cast.
491    TheUse = InsertedCast;
492  }
493
494  // If we removed all uses, nuke the cast.
495  if (CI->use_empty()) {
496    CI->eraseFromParent();
497    MadeChange = true;
498  }
499
500  return MadeChange;
501}
502
503/// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
504/// the number of virtual registers that must be created and coalesced.  This is
505/// a clear win except on targets with multiple condition code registers
506///  (PowerPC), where it might lose; some adjustment may be wanted there.
507///
508/// Return true if any changes are made.
509static bool OptimizeCmpExpression(CmpInst *CI) {
510  BasicBlock *DefBB = CI->getParent();
511
512  /// InsertedCmp - Only insert a cmp in each block once.
513  DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
514
515  bool MadeChange = false;
516  for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
517       UI != E; ) {
518    Use &TheUse = UI.getUse();
519    Instruction *User = cast<Instruction>(*UI);
520
521    // Preincrement use iterator so we don't invalidate it.
522    ++UI;
523
524    // Don't bother for PHI nodes.
525    if (isa<PHINode>(User))
526      continue;
527
528    // Figure out which BB this cmp is used in.
529    BasicBlock *UserBB = User->getParent();
530
531    // If this user is in the same block as the cmp, don't change the cmp.
532    if (UserBB == DefBB) continue;
533
534    // If we have already inserted a cmp into this block, use it.
535    CmpInst *&InsertedCmp = InsertedCmps[UserBB];
536
537    if (!InsertedCmp) {
538      BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
539
540      InsertedCmp =
541        CmpInst::Create(CI->getOpcode(),
542                        CI->getPredicate(),  CI->getOperand(0),
543                        CI->getOperand(1), "", InsertPt);
544      MadeChange = true;
545    }
546
547    // Replace a use of the cmp with a use of the new cmp.
548    TheUse = InsertedCmp;
549  }
550
551  // If we removed all uses, nuke the cmp.
552  if (CI->use_empty())
553    CI->eraseFromParent();
554
555  return MadeChange;
556}
557
558namespace {
559class CodeGenPrepareFortifiedLibCalls : public SimplifyFortifiedLibCalls {
560protected:
561  void replaceCall(Value *With) {
562    CI->replaceAllUsesWith(With);
563    CI->eraseFromParent();
564  }
565  bool isFoldable(unsigned SizeCIOp, unsigned, bool) const {
566      if (ConstantInt *SizeCI =
567                             dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp)))
568        return SizeCI->isAllOnesValue();
569    return false;
570  }
571};
572} // end anonymous namespace
573
574bool CodeGenPrepare::OptimizeCallInst(CallInst *CI) {
575  // Lower all uses of llvm.objectsize.*
576  IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
577  if (II && II->getIntrinsicID() == Intrinsic::objectsize) {
578    bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
579    const Type *ReturnTy = CI->getType();
580    Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
581    CI->replaceAllUsesWith(RetVal);
582    CI->eraseFromParent();
583    return true;
584  }
585
586  // From here on out we're working with named functions.
587  if (CI->getCalledFunction() == 0) return false;
588
589  // We'll need TargetData from here on out.
590  const TargetData *TD = TLI ? TLI->getTargetData() : 0;
591  if (!TD) return false;
592
593  // Lower all default uses of _chk calls.  This is very similar
594  // to what InstCombineCalls does, but here we are only lowering calls
595  // that have the default "don't know" as the objectsize.  Anything else
596  // should be left alone.
597  CodeGenPrepareFortifiedLibCalls Simplifier;
598  return Simplifier.fold(CI, TD);
599}
600//===----------------------------------------------------------------------===//
601// Memory Optimization
602//===----------------------------------------------------------------------===//
603
604/// IsNonLocalValue - Return true if the specified values are defined in a
605/// different basic block than BB.
606static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
607  if (Instruction *I = dyn_cast<Instruction>(V))
608    return I->getParent() != BB;
609  return false;
610}
611
612/// OptimizeMemoryInst - Load and Store Instructions often have
613/// addressing modes that can do significant amounts of computation.  As such,
614/// instruction selection will try to get the load or store to do as much
615/// computation as possible for the program.  The problem is that isel can only
616/// see within a single block.  As such, we sink as much legal addressing mode
617/// stuff into the block as possible.
618///
619/// This method is used to optimize both load/store and inline asms with memory
620/// operands.
621bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
622                                        const Type *AccessTy,
623                                        DenseMap<Value*,Value*> &SunkAddrs) {
624  Value *Repl = Addr;
625
626  // Try to collapse single-value PHI nodes.  This is necessary to undo
627  // unprofitable PRE transformations.
628  SmallVector<Value*, 8> worklist;
629  SmallPtrSet<Value*, 16> Visited;
630  worklist.push_back(Addr);
631
632  // Use a worklist to iteratively look through PHI nodes, and ensure that
633  // the addressing mode obtained from the non-PHI roots of the graph
634  // are equivalent.
635  Value *Consensus = 0;
636  unsigned NumUses = 0;
637  SmallVector<Instruction*, 16> AddrModeInsts;
638  ExtAddrMode AddrMode;
639  while (!worklist.empty()) {
640    Value *V = worklist.back();
641    worklist.pop_back();
642
643    // Break use-def graph loops.
644    if (Visited.count(V)) {
645      Consensus = 0;
646      break;
647    }
648
649    Visited.insert(V);
650
651    // For a PHI node, push all of its incoming values.
652    if (PHINode *P = dyn_cast<PHINode>(V)) {
653      for (unsigned i = 0, e = P->getNumIncomingValues(); i != e; ++i)
654        worklist.push_back(P->getIncomingValue(i));
655      continue;
656    }
657
658    // For non-PHIs, determine the addressing mode being computed.
659    SmallVector<Instruction*, 16> NewAddrModeInsts;
660    ExtAddrMode NewAddrMode =
661      AddressingModeMatcher::Match(V, AccessTy,MemoryInst,
662                                   NewAddrModeInsts, *TLI);
663
664    // Ensure that the obtained addressing mode is equivalent to that obtained
665    // for all other roots of the PHI traversal.  Also, when choosing one
666    // such root as representative, select the one with the most uses in order
667    // to keep the cost modeling heuristics in AddressingModeMatcher applicable.
668    if (!Consensus || NewAddrMode == AddrMode) {
669      if (V->getNumUses() > NumUses) {
670        Consensus = V;
671        NumUses = V->getNumUses();
672        AddrMode = NewAddrMode;
673        AddrModeInsts = NewAddrModeInsts;
674      }
675      continue;
676    }
677
678    Consensus = 0;
679    break;
680  }
681
682  // If the addressing mode couldn't be determined, or if multiple different
683  // ones were determined, bail out now.
684  if (!Consensus) return false;
685
686  // Check to see if any of the instructions supersumed by this addr mode are
687  // non-local to I's BB.
688  bool AnyNonLocal = false;
689  for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
690    if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
691      AnyNonLocal = true;
692      break;
693    }
694  }
695
696  // If all the instructions matched are already in this BB, don't do anything.
697  if (!AnyNonLocal) {
698    DEBUG(dbgs() << "CGP: Found      local addrmode: " << AddrMode << "\n");
699    return false;
700  }
701
702  // Insert this computation right after this user.  Since our caller is
703  // scanning from the top of the BB to the bottom, reuse of the expr are
704  // guaranteed to happen later.
705  BasicBlock::iterator InsertPt = MemoryInst;
706
707  // Now that we determined the addressing expression we want to use and know
708  // that we have to sink it into this block.  Check to see if we have already
709  // done this for some other load/store instr in this block.  If so, reuse the
710  // computation.
711  Value *&SunkAddr = SunkAddrs[Addr];
712  if (SunkAddr) {
713    DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
714                 << *MemoryInst);
715    if (SunkAddr->getType() != Addr->getType())
716      SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
717  } else {
718    DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
719                 << *MemoryInst);
720    const Type *IntPtrTy =
721          TLI->getTargetData()->getIntPtrType(AccessTy->getContext());
722
723    Value *Result = 0;
724
725    // Start with the base register. Do this first so that subsequent address
726    // matching finds it last, which will prevent it from trying to match it
727    // as the scaled value in case it happens to be a mul. That would be
728    // problematic if we've sunk a different mul for the scale, because then
729    // we'd end up sinking both muls.
730    if (AddrMode.BaseReg) {
731      Value *V = AddrMode.BaseReg;
732      if (V->getType()->isPointerTy())
733        V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
734      if (V->getType() != IntPtrTy)
735        V = CastInst::CreateIntegerCast(V, IntPtrTy, /*isSigned=*/true,
736                                        "sunkaddr", InsertPt);
737      Result = V;
738    }
739
740    // Add the scale value.
741    if (AddrMode.Scale) {
742      Value *V = AddrMode.ScaledReg;
743      if (V->getType() == IntPtrTy) {
744        // done.
745      } else if (V->getType()->isPointerTy()) {
746        V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
747      } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
748                 cast<IntegerType>(V->getType())->getBitWidth()) {
749        V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
750      } else {
751        V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
752      }
753      if (AddrMode.Scale != 1)
754        V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
755                                                                AddrMode.Scale),
756                                      "sunkaddr", InsertPt);
757      if (Result)
758        Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
759      else
760        Result = V;
761    }
762
763    // Add in the BaseGV if present.
764    if (AddrMode.BaseGV) {
765      Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
766                                  InsertPt);
767      if (Result)
768        Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
769      else
770        Result = V;
771    }
772
773    // Add in the Base Offset if present.
774    if (AddrMode.BaseOffs) {
775      Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
776      if (Result)
777        Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
778      else
779        Result = V;
780    }
781
782    if (Result == 0)
783      SunkAddr = Constant::getNullValue(Addr->getType());
784    else
785      SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
786  }
787
788  MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
789
790  if (Repl->use_empty()) {
791    RecursivelyDeleteTriviallyDeadInstructions(Repl);
792    // This address is now available for reassignment, so erase the table entry;
793    // we don't want to match some completely different instruction.
794    SunkAddrs[Addr] = 0;
795  }
796  return true;
797}
798
799/// OptimizeInlineAsmInst - If there are any memory operands, use
800/// OptimizeMemoryInst to sink their address computing into the block when
801/// possible / profitable.
802bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
803                                           DenseMap<Value*,Value*> &SunkAddrs) {
804  bool MadeChange = false;
805
806  TargetLowering::AsmOperandInfoVector TargetConstraints = TLI->ParseConstraints(CS);
807  unsigned ArgNo = 0;
808  for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
809    TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
810
811    // Compute the constraint code and ConstraintType to use.
812    TLI->ComputeConstraintToUse(OpInfo, SDValue());
813
814    if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
815        OpInfo.isIndirect) {
816      Value *OpVal = const_cast<Value *>(CS.getArgument(ArgNo++));
817      MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
818    } else if (OpInfo.Type == InlineAsm::isInput)
819      ArgNo++;
820  }
821
822  return MadeChange;
823}
824
825/// MoveExtToFormExtLoad - Move a zext or sext fed by a load into the same
826/// basic block as the load, unless conditions are unfavorable. This allows
827/// SelectionDAG to fold the extend into the load.
828///
829bool CodeGenPrepare::MoveExtToFormExtLoad(Instruction *I) {
830  // Look for a load being extended.
831  LoadInst *LI = dyn_cast<LoadInst>(I->getOperand(0));
832  if (!LI) return false;
833
834  // If they're already in the same block, there's nothing to do.
835  if (LI->getParent() == I->getParent())
836    return false;
837
838  // If the load has other users and the truncate is not free, this probably
839  // isn't worthwhile.
840  if (!LI->hasOneUse() &&
841      TLI && (TLI->isTypeLegal(TLI->getValueType(LI->getType())) ||
842              !TLI->isTypeLegal(TLI->getValueType(I->getType()))) &&
843      !TLI->isTruncateFree(I->getType(), LI->getType()))
844    return false;
845
846  // Check whether the target supports casts folded into loads.
847  unsigned LType;
848  if (isa<ZExtInst>(I))
849    LType = ISD::ZEXTLOAD;
850  else {
851    assert(isa<SExtInst>(I) && "Unexpected ext type!");
852    LType = ISD::SEXTLOAD;
853  }
854  if (TLI && !TLI->isLoadExtLegal(LType, TLI->getValueType(LI->getType())))
855    return false;
856
857  // Move the extend into the same block as the load, so that SelectionDAG
858  // can fold it.
859  I->removeFromParent();
860  I->insertAfter(LI);
861  return true;
862}
863
864bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
865  BasicBlock *DefBB = I->getParent();
866
867  // If the result of a {s|z}ext and its source are both live out, rewrite all
868  // other uses of the source with result of extension.
869  Value *Src = I->getOperand(0);
870  if (Src->hasOneUse())
871    return false;
872
873  // Only do this xform if truncating is free.
874  if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
875    return false;
876
877  // Only safe to perform the optimization if the source is also defined in
878  // this block.
879  if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
880    return false;
881
882  bool DefIsLiveOut = false;
883  for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
884       UI != E; ++UI) {
885    Instruction *User = cast<Instruction>(*UI);
886
887    // Figure out which BB this ext is used in.
888    BasicBlock *UserBB = User->getParent();
889    if (UserBB == DefBB) continue;
890    DefIsLiveOut = true;
891    break;
892  }
893  if (!DefIsLiveOut)
894    return false;
895
896  // Make sure non of the uses are PHI nodes.
897  for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
898       UI != E; ++UI) {
899    Instruction *User = cast<Instruction>(*UI);
900    BasicBlock *UserBB = User->getParent();
901    if (UserBB == DefBB) continue;
902    // Be conservative. We don't want this xform to end up introducing
903    // reloads just before load / store instructions.
904    if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
905      return false;
906  }
907
908  // InsertedTruncs - Only insert one trunc in each block once.
909  DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
910
911  bool MadeChange = false;
912  for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
913       UI != E; ++UI) {
914    Use &TheUse = UI.getUse();
915    Instruction *User = cast<Instruction>(*UI);
916
917    // Figure out which BB this ext is used in.
918    BasicBlock *UserBB = User->getParent();
919    if (UserBB == DefBB) continue;
920
921    // Both src and def are live in this block. Rewrite the use.
922    Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
923
924    if (!InsertedTrunc) {
925      BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
926
927      InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
928    }
929
930    // Replace a use of the {s|z}ext source with a use of the result.
931    TheUse = InsertedTrunc;
932
933    MadeChange = true;
934  }
935
936  return MadeChange;
937}
938
939// In this pass we look for GEP and cast instructions that are used
940// across basic blocks and rewrite them to improve basic-block-at-a-time
941// selection.
942bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
943  bool MadeChange = false;
944
945  // Split all critical edges where the dest block has a PHI.
946  if (CriticalEdgeSplit) {
947    TerminatorInst *BBTI = BB.getTerminator();
948    if (BBTI->getNumSuccessors() > 1 && !isa<IndirectBrInst>(BBTI)) {
949      for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
950        BasicBlock *SuccBB = BBTI->getSuccessor(i);
951        if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
952          SplitEdgeNicely(BBTI, i, BackEdges, this);
953      }
954    }
955  }
956
957  // Keep track of non-local addresses that have been sunk into this block.
958  // This allows us to avoid inserting duplicate code for blocks with multiple
959  // load/stores of the same address.
960  DenseMap<Value*, Value*> SunkAddrs;
961
962  for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
963    Instruction *I = BBI++;
964
965    if (PHINode *P = dyn_cast<PHINode>(I)) {
966      // It is possible for very late stage optimizations (such as SimplifyCFG)
967      // to introduce PHI nodes too late to be cleaned up.  If we detect such a
968      // trivial PHI, go ahead and zap it here.
969      if (Value *V = SimplifyInstruction(P)) {
970        P->replaceAllUsesWith(V);
971        P->eraseFromParent();
972      }
973    } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
974      // If the source of the cast is a constant, then this should have
975      // already been constant folded.  The only reason NOT to constant fold
976      // it is if something (e.g. LSR) was careful to place the constant
977      // evaluation in a block other than then one that uses it (e.g. to hoist
978      // the address of globals out of a loop).  If this is the case, we don't
979      // want to forward-subst the cast.
980      if (isa<Constant>(CI->getOperand(0)))
981        continue;
982
983      bool Change = false;
984      if (TLI) {
985        Change = OptimizeNoopCopyExpression(CI, *TLI);
986        MadeChange |= Change;
987      }
988
989      if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I))) {
990        MadeChange |= MoveExtToFormExtLoad(I);
991        MadeChange |= OptimizeExtUses(I);
992      }
993    } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
994      MadeChange |= OptimizeCmpExpression(CI);
995    } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
996      if (TLI)
997        MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
998                                         SunkAddrs);
999    } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
1000      if (TLI)
1001        MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
1002                                         SI->getOperand(0)->getType(),
1003                                         SunkAddrs);
1004    } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
1005      if (GEPI->hasAllZeroIndices()) {
1006        /// The GEP operand must be a pointer, so must its result -> BitCast
1007        Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
1008                                          GEPI->getName(), GEPI);
1009        GEPI->replaceAllUsesWith(NC);
1010        GEPI->eraseFromParent();
1011        MadeChange = true;
1012        BBI = NC;
1013      }
1014    } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
1015      // If we found an inline asm expession, and if the target knows how to
1016      // lower it to normal LLVM code, do so now.
1017      if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
1018        if (TLI->ExpandInlineAsm(CI)) {
1019          BBI = BB.begin();
1020          // Avoid processing instructions out of order, which could cause
1021          // reuse before a value is defined.
1022          SunkAddrs.clear();
1023        } else
1024          // Sink address computing for memory operands into the block.
1025          MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
1026      } else {
1027        // Other CallInst optimizations that don't need to muck with the
1028        // enclosing iterator here.
1029        MadeChange |= OptimizeCallInst(CI);
1030      }
1031    }
1032  }
1033
1034  return MadeChange;
1035}
1036