LLVM API Documentation

CodeGenPrepare.cpp

Go to the documentation of this file.
00001 //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass munges the code in the input function to better prepare it for
00011 // SelectionDAG-based code generation. This works around limitations in it's
00012 // basic-block-at-a-time approach. It should eventually be removed.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #define DEBUG_TYPE "codegenprepare"
00017 #include "llvm/Transforms/Scalar.h"
00018 #include "llvm/Constants.h"
00019 #include "llvm/DerivedTypes.h"
00020 #include "llvm/Function.h"
00021 #include "llvm/InlineAsm.h"
00022 #include "llvm/Instructions.h"
00023 #include "llvm/Pass.h"
00024 #include "llvm/Target/TargetAsmInfo.h"
00025 #include "llvm/Target/TargetData.h"
00026 #include "llvm/Target/TargetLowering.h"
00027 #include "llvm/Target/TargetMachine.h"
00028 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00029 #include "llvm/Transforms/Utils/Local.h"
00030 #include "llvm/ADT/DenseMap.h"
00031 #include "llvm/ADT/SmallSet.h"
00032 #include "llvm/Support/CallSite.h"
00033 #include "llvm/Support/CommandLine.h"
00034 #include "llvm/Support/Compiler.h"
00035 #include "llvm/Support/Debug.h"
00036 #include "llvm/Support/GetElementPtrTypeIterator.h"
00037 #include "llvm/Support/PatternMatch.h"
00038 using namespace llvm;
00039 using namespace llvm::PatternMatch;
00040 
00041 static cl::opt<bool> FactorCommonPreds("split-critical-paths-tweak",
00042                                        cl::init(false), cl::Hidden);
00043 
00044 namespace {
00045   class VISIBILITY_HIDDEN CodeGenPrepare : public FunctionPass {
00046     /// TLI - Keep a pointer of a TargetLowering to consult for determining
00047     /// transformation profitability.
00048     const TargetLowering *TLI;
00049 
00050     /// BackEdges - Keep a set of all the loop back edges.
00051     ///
00052     SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> BackEdges;
00053   public:
00054     static char ID; // Pass identification, replacement for typeid
00055     explicit CodeGenPrepare(const TargetLowering *tli = 0)
00056       : FunctionPass(&ID), TLI(tli) {}
00057     bool runOnFunction(Function &F);
00058 
00059   private:
00060     bool EliminateMostlyEmptyBlocks(Function &F);
00061     bool CanMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
00062     void EliminateMostlyEmptyBlock(BasicBlock *BB);
00063     bool OptimizeBlock(BasicBlock &BB);
00064     bool OptimizeMemoryInst(Instruction *I, Value *Addr, const Type *AccessTy,
00065                             DenseMap<Value*,Value*> &SunkAddrs);
00066     bool OptimizeInlineAsmInst(Instruction *I, CallSite CS,
00067                                DenseMap<Value*,Value*> &SunkAddrs);
00068     bool OptimizeExtUses(Instruction *I);
00069     void findLoopBackEdges(Function &F);
00070   };
00071 }
00072 
00073 char CodeGenPrepare::ID = 0;
00074 static RegisterPass<CodeGenPrepare> X("codegenprepare",
00075                                       "Optimize for code generation");
00076 
00077 FunctionPass *llvm::createCodeGenPreparePass(const TargetLowering *TLI) {
00078   return new CodeGenPrepare(TLI);
00079 }
00080 
00081 /// findLoopBackEdges - Do a DFS walk to find loop back edges.
00082 ///
00083 void CodeGenPrepare::findLoopBackEdges(Function &F) {
00084   SmallPtrSet<BasicBlock*, 8> Visited;
00085   SmallVector<std::pair<BasicBlock*, succ_iterator>, 8> VisitStack;
00086   SmallPtrSet<BasicBlock*, 8> InStack;
00087 
00088   BasicBlock *BB = &F.getEntryBlock();
00089   if (succ_begin(BB) == succ_end(BB))
00090     return;
00091   Visited.insert(BB);
00092   VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
00093   InStack.insert(BB);
00094   do {
00095     std::pair<BasicBlock*, succ_iterator> &Top = VisitStack.back();
00096     BasicBlock *ParentBB = Top.first;
00097     succ_iterator &I = Top.second;
00098 
00099     bool FoundNew = false;
00100     while (I != succ_end(ParentBB)) {
00101       BB = *I++;
00102       if (Visited.insert(BB)) {
00103         FoundNew = true;
00104         break;
00105       }
00106       // Successor is in VisitStack, it's a back edge.
00107       if (InStack.count(BB))
00108         BackEdges.insert(std::make_pair(ParentBB, BB));
00109     }
00110 
00111     if (FoundNew) {
00112       // Go down one level if there is a unvisited successor.
00113       InStack.insert(BB);
00114       VisitStack.push_back(std::make_pair(BB, succ_begin(BB)));
00115     } else {
00116       // Go up one level.
00117       std::pair<BasicBlock*, succ_iterator> &Pop = VisitStack.back();
00118       InStack.erase(Pop.first);
00119       VisitStack.pop_back();
00120     }
00121   } while (!VisitStack.empty());
00122 }
00123 
00124 
00125 bool CodeGenPrepare::runOnFunction(Function &F) {
00126   bool EverMadeChange = false;
00127 
00128   // First pass, eliminate blocks that contain only PHI nodes and an
00129   // unconditional branch.
00130   EverMadeChange |= EliminateMostlyEmptyBlocks(F);
00131 
00132   // Now find loop back edges.
00133   findLoopBackEdges(F);
00134 
00135   bool MadeChange = true;
00136   while (MadeChange) {
00137     MadeChange = false;
00138     for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
00139       MadeChange |= OptimizeBlock(*BB);
00140     EverMadeChange |= MadeChange;
00141   }
00142   return EverMadeChange;
00143 }
00144 
00145 /// EliminateMostlyEmptyBlocks - eliminate blocks that contain only PHI nodes
00146 /// and an unconditional branch.  Passes before isel (e.g. LSR/loopsimplify)
00147 /// often split edges in ways that are non-optimal for isel.  Start by
00148 /// eliminating these blocks so we can split them the way we want them.
00149 bool CodeGenPrepare::EliminateMostlyEmptyBlocks(Function &F) {
00150   bool MadeChange = false;
00151   // Note that this intentionally skips the entry block.
00152   for (Function::iterator I = ++F.begin(), E = F.end(); I != E; ) {
00153     BasicBlock *BB = I++;
00154 
00155     // If this block doesn't end with an uncond branch, ignore it.
00156     BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
00157     if (!BI || !BI->isUnconditional())
00158       continue;
00159 
00160     // If the instruction before the branch isn't a phi node, then other stuff
00161     // is happening here.
00162     BasicBlock::iterator BBI = BI;
00163     if (BBI != BB->begin()) {
00164       --BBI;
00165       if (!isa<PHINode>(BBI)) continue;
00166     }
00167 
00168     // Do not break infinite loops.
00169     BasicBlock *DestBB = BI->getSuccessor(0);
00170     if (DestBB == BB)
00171       continue;
00172 
00173     if (!CanMergeBlocks(BB, DestBB))
00174       continue;
00175 
00176     EliminateMostlyEmptyBlock(BB);
00177     MadeChange = true;
00178   }
00179   return MadeChange;
00180 }
00181 
00182 /// CanMergeBlocks - Return true if we can merge BB into DestBB if there is a
00183 /// single uncond branch between them, and BB contains no other non-phi
00184 /// instructions.
00185 bool CodeGenPrepare::CanMergeBlocks(const BasicBlock *BB,
00186                                     const BasicBlock *DestBB) const {
00187   // We only want to eliminate blocks whose phi nodes are used by phi nodes in
00188   // the successor.  If there are more complex condition (e.g. preheaders),
00189   // don't mess around with them.
00190   BasicBlock::const_iterator BBI = BB->begin();
00191   while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
00192     for (Value::use_const_iterator UI = PN->use_begin(), E = PN->use_end();
00193          UI != E; ++UI) {
00194       const Instruction *User = cast<Instruction>(*UI);
00195       if (User->getParent() != DestBB || !isa<PHINode>(User))
00196         return false;
00197       // If User is inside DestBB block and it is a PHINode then check
00198       // incoming value. If incoming value is not from BB then this is
00199       // a complex condition (e.g. preheaders) we want to avoid here.
00200       if (User->getParent() == DestBB) {
00201         if (const PHINode *UPN = dyn_cast<PHINode>(User))
00202           for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
00203             Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
00204             if (Insn && Insn->getParent() == BB &&
00205                 Insn->getParent() != UPN->getIncomingBlock(I))
00206               return false;
00207           }
00208       }
00209     }
00210   }
00211 
00212   // If BB and DestBB contain any common predecessors, then the phi nodes in BB
00213   // and DestBB may have conflicting incoming values for the block.  If so, we
00214   // can't merge the block.
00215   const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
00216   if (!DestBBPN) return true;  // no conflict.
00217 
00218   // Collect the preds of BB.
00219   SmallPtrSet<const BasicBlock*, 16> BBPreds;
00220   if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
00221     // It is faster to get preds from a PHI than with pred_iterator.
00222     for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
00223       BBPreds.insert(BBPN->getIncomingBlock(i));
00224   } else {
00225     BBPreds.insert(pred_begin(BB), pred_end(BB));
00226   }
00227 
00228   // Walk the preds of DestBB.
00229   for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
00230     BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
00231     if (BBPreds.count(Pred)) {   // Common predecessor?
00232       BBI = DestBB->begin();
00233       while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
00234         const Value *V1 = PN->getIncomingValueForBlock(Pred);
00235         const Value *V2 = PN->getIncomingValueForBlock(BB);
00236 
00237         // If V2 is a phi node in BB, look up what the mapped value will be.
00238         if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
00239           if (V2PN->getParent() == BB)
00240             V2 = V2PN->getIncomingValueForBlock(Pred);
00241 
00242         // If there is a conflict, bail out.
00243         if (V1 != V2) return false;
00244       }
00245     }
00246   }
00247 
00248   return true;
00249 }
00250 
00251 
00252 /// EliminateMostlyEmptyBlock - Eliminate a basic block that have only phi's and
00253 /// an unconditional branch in it.
00254 void CodeGenPrepare::EliminateMostlyEmptyBlock(BasicBlock *BB) {
00255   BranchInst *BI = cast<BranchInst>(BB->getTerminator());
00256   BasicBlock *DestBB = BI->getSuccessor(0);
00257 
00258   DOUT << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB;
00259 
00260   // If the destination block has a single pred, then this is a trivial edge,
00261   // just collapse it.
00262   if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
00263     if (SinglePred != DestBB) {
00264       // Remember if SinglePred was the entry block of the function.  If so, we
00265       // will need to move BB back to the entry position.
00266       bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
00267       MergeBasicBlockIntoOnlyPred(DestBB);
00268 
00269       if (isEntry && BB != &BB->getParent()->getEntryBlock())
00270         BB->moveBefore(&BB->getParent()->getEntryBlock());
00271       
00272       DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
00273       return;
00274     }
00275   }
00276 
00277   // Otherwise, we have multiple predecessors of BB.  Update the PHIs in DestBB
00278   // to handle the new incoming edges it is about to have.
00279   PHINode *PN;
00280   for (BasicBlock::iterator BBI = DestBB->begin();
00281        (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
00282     // Remove the incoming value for BB, and remember it.
00283     Value *InVal = PN->removeIncomingValue(BB, false);
00284 
00285     // Two options: either the InVal is a phi node defined in BB or it is some
00286     // value that dominates BB.
00287     PHINode *InValPhi = dyn_cast<PHINode>(InVal);
00288     if (InValPhi && InValPhi->getParent() == BB) {
00289       // Add all of the input values of the input PHI as inputs of this phi.
00290       for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
00291         PN->addIncoming(InValPhi->getIncomingValue(i),
00292                         InValPhi->getIncomingBlock(i));
00293     } else {
00294       // Otherwise, add one instance of the dominating value for each edge that
00295       // we will be adding.
00296       if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
00297         for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
00298           PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
00299       } else {
00300         for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
00301           PN->addIncoming(InVal, *PI);
00302       }
00303     }
00304   }
00305 
00306   // The PHIs are now updated, change everything that refers to BB to use
00307   // DestBB and remove BB.
00308   BB->replaceAllUsesWith(DestBB);
00309   BB->eraseFromParent();
00310 
00311   DOUT << "AFTER:\n" << *DestBB << "\n\n\n";
00312 }
00313 
00314 
00315 /// SplitEdgeNicely - Split the critical edge from TI to its specified
00316 /// successor if it will improve codegen.  We only do this if the successor has
00317 /// phi nodes (otherwise critical edges are ok).  If there is already another
00318 /// predecessor of the succ that is empty (and thus has no phi nodes), use it
00319 /// instead of introducing a new block.
00320 static void SplitEdgeNicely(TerminatorInst *TI, unsigned SuccNum,
00321                      SmallSet<std::pair<BasicBlock*,BasicBlock*>, 8> &BackEdges,
00322                              Pass *P) {
00323   BasicBlock *TIBB = TI->getParent();
00324   BasicBlock *Dest = TI->getSuccessor(SuccNum);
00325   assert(isa<PHINode>(Dest->begin()) &&
00326          "This should only be called if Dest has a PHI!");
00327 
00328   // As a hack, never split backedges of loops.  Even though the copy for any
00329   // PHIs inserted on the backedge would be dead for exits from the loop, we
00330   // assume that the cost of *splitting* the backedge would be too high.
00331   if (BackEdges.count(std::make_pair(TIBB, Dest)))
00332     return;
00333 
00334   if (!FactorCommonPreds) {
00335     /// TIPHIValues - This array is lazily computed to determine the values of
00336     /// PHIs in Dest that TI would provide.
00337     SmallVector<Value*, 32> TIPHIValues;
00338 
00339     // Check to see if Dest has any blocks that can be used as a split edge for
00340     // this terminator.
00341     for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
00342       BasicBlock *Pred = *PI;
00343       // To be usable, the pred has to end with an uncond branch to the dest.
00344       BranchInst *PredBr = dyn_cast<BranchInst>(Pred->getTerminator());
00345       if (!PredBr || !PredBr->isUnconditional() ||
00346           // Must be empty other than the branch.
00347           &Pred->front() != PredBr ||
00348           // Cannot be the entry block; its label does not get emitted.
00349           Pred == &(Dest->getParent()->getEntryBlock()))
00350         continue;
00351 
00352       // Finally, since we know that Dest has phi nodes in it, we have to make
00353       // sure that jumping to Pred will have the same affect as going to Dest in
00354       // terms of PHI values.
00355       PHINode *PN;
00356       unsigned PHINo = 0;
00357       bool FoundMatch = true;
00358       for (BasicBlock::iterator I = Dest->begin();
00359            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo) {
00360         if (PHINo == TIPHIValues.size())
00361           TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
00362 
00363         // If the PHI entry doesn't work, we can't use this pred.
00364         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
00365           FoundMatch = false;
00366           break;
00367         }
00368       }
00369 
00370       // If we found a workable predecessor, change TI to branch to Succ.
00371       if (FoundMatch) {
00372         Dest->removePredecessor(TIBB);
00373         TI->setSuccessor(SuccNum, Pred);
00374         return;
00375       }
00376     }
00377 
00378     SplitCriticalEdge(TI, SuccNum, P, true);
00379     return;
00380   }
00381 
00382   PHINode *PN;
00383   SmallVector<Value*, 8> TIPHIValues;
00384   for (BasicBlock::iterator I = Dest->begin();
00385        (PN = dyn_cast<PHINode>(I)); ++I)
00386     TIPHIValues.push_back(PN->getIncomingValueForBlock(TIBB));
00387 
00388   SmallVector<BasicBlock*, 8> IdenticalPreds;
00389   for (pred_iterator PI = pred_begin(Dest), E = pred_end(Dest); PI != E; ++PI) {
00390     BasicBlock *Pred = *PI;
00391     if (BackEdges.count(std::make_pair(Pred, Dest)))
00392       continue;
00393     if (PI == TIBB)
00394       IdenticalPreds.push_back(Pred);
00395     else {
00396       bool Identical = true;
00397       unsigned PHINo = 0;
00398       for (BasicBlock::iterator I = Dest->begin();
00399            (PN = dyn_cast<PHINode>(I)); ++I, ++PHINo)
00400         if (TIPHIValues[PHINo] != PN->getIncomingValueForBlock(Pred)) {
00401           Identical = false;
00402           break;
00403         }
00404       if (Identical)
00405         IdenticalPreds.push_back(Pred);
00406     }
00407   }
00408 
00409   assert(!IdenticalPreds.empty());
00410   SplitBlockPredecessors(Dest, &IdenticalPreds[0], IdenticalPreds.size(),
00411                          ".critedge", P);
00412 }
00413 
00414 
00415 /// OptimizeNoopCopyExpression - If the specified cast instruction is a noop
00416 /// copy (e.g. it's casting from one pointer type to another, int->uint, or
00417 /// int->sbyte on PPC), sink it into user blocks to reduce the number of virtual
00418 /// registers that must be created and coalesced.
00419 ///
00420 /// Return true if any changes are made.
00421 ///
00422 static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI){
00423   // If this is a noop copy,
00424   MVT SrcVT = TLI.getValueType(CI->getOperand(0)->getType());
00425   MVT DstVT = TLI.getValueType(CI->getType());
00426 
00427   // This is an fp<->int conversion?
00428   if (SrcVT.isInteger() != DstVT.isInteger())
00429     return false;
00430 
00431   // If this is an extension, it will be a zero or sign extension, which
00432   // isn't a noop.
00433   if (SrcVT.bitsLT(DstVT)) return false;
00434 
00435   // If these values will be promoted, find out what they will be promoted
00436   // to.  This helps us consider truncates on PPC as noop copies when they
00437   // are.
00438   if (TLI.getTypeAction(SrcVT) == TargetLowering::Promote)
00439     SrcVT = TLI.getTypeToTransformTo(SrcVT);
00440   if (TLI.getTypeAction(DstVT) == TargetLowering::Promote)
00441     DstVT = TLI.getTypeToTransformTo(DstVT);
00442 
00443   // If, after promotion, these are the same types, this is a noop copy.
00444   if (SrcVT != DstVT)
00445     return false;
00446 
00447   BasicBlock *DefBB = CI->getParent();
00448 
00449   /// InsertedCasts - Only insert a cast in each block once.
00450   DenseMap<BasicBlock*, CastInst*> InsertedCasts;
00451 
00452   bool MadeChange = false;
00453   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
00454        UI != E; ) {
00455     Use &TheUse = UI.getUse();
00456     Instruction *User = cast<Instruction>(*UI);
00457 
00458     // Figure out which BB this cast is used in.  For PHI's this is the
00459     // appropriate predecessor block.
00460     BasicBlock *UserBB = User->getParent();
00461     if (PHINode *PN = dyn_cast<PHINode>(User)) {
00462       UserBB = PN->getIncomingBlock(UI);
00463     }
00464 
00465     // Preincrement use iterator so we don't invalidate it.
00466     ++UI;
00467 
00468     // If this user is in the same block as the cast, don't change the cast.
00469     if (UserBB == DefBB) continue;
00470 
00471     // If we have already inserted a cast into this block, use it.
00472     CastInst *&InsertedCast = InsertedCasts[UserBB];
00473 
00474     if (!InsertedCast) {
00475       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
00476 
00477       InsertedCast =
00478         CastInst::Create(CI->getOpcode(), CI->getOperand(0), CI->getType(), "",
00479                          InsertPt);
00480       MadeChange = true;
00481     }
00482 
00483     // Replace a use of the cast with a use of the new cast.
00484     TheUse = InsertedCast;
00485   }
00486 
00487   // If we removed all uses, nuke the cast.
00488   if (CI->use_empty()) {
00489     CI->eraseFromParent();
00490     MadeChange = true;
00491   }
00492 
00493   return MadeChange;
00494 }
00495 
00496 /// OptimizeCmpExpression - sink the given CmpInst into user blocks to reduce
00497 /// the number of virtual registers that must be created and coalesced.  This is
00498 /// a clear win except on targets with multiple condition code registers
00499 ///  (PowerPC), where it might lose; some adjustment may be wanted there.
00500 ///
00501 /// Return true if any changes are made.
00502 static bool OptimizeCmpExpression(CmpInst *CI) {
00503   BasicBlock *DefBB = CI->getParent();
00504 
00505   /// InsertedCmp - Only insert a cmp in each block once.
00506   DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
00507 
00508   bool MadeChange = false;
00509   for (Value::use_iterator UI = CI->use_begin(), E = CI->use_end();
00510        UI != E; ) {
00511     Use &TheUse = UI.getUse();
00512     Instruction *User = cast<Instruction>(*UI);
00513 
00514     // Preincrement use iterator so we don't invalidate it.
00515     ++UI;
00516 
00517     // Don't bother for PHI nodes.
00518     if (isa<PHINode>(User))
00519       continue;
00520 
00521     // Figure out which BB this cmp is used in.
00522     BasicBlock *UserBB = User->getParent();
00523 
00524     // If this user is in the same block as the cmp, don't change the cmp.
00525     if (UserBB == DefBB) continue;
00526 
00527     // If we have already inserted a cmp into this block, use it.
00528     CmpInst *&InsertedCmp = InsertedCmps[UserBB];
00529 
00530     if (!InsertedCmp) {
00531       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
00532 
00533       InsertedCmp =
00534         CmpInst::Create(CI->getOpcode(), CI->getPredicate(), CI->getOperand(0),
00535                         CI->getOperand(1), "", InsertPt);
00536       MadeChange = true;
00537     }
00538 
00539     // Replace a use of the cmp with a use of the new cmp.
00540     TheUse = InsertedCmp;
00541   }
00542 
00543   // If we removed all uses, nuke the cmp.
00544   if (CI->use_empty())
00545     CI->eraseFromParent();
00546 
00547   return MadeChange;
00548 }
00549 
00550 //===----------------------------------------------------------------------===//
00551 // Addressing Mode Analysis and Optimization
00552 //===----------------------------------------------------------------------===//
00553 
00554 namespace {
00555   /// ExtAddrMode - This is an extended version of TargetLowering::AddrMode
00556   /// which holds actual Value*'s for register values.
00557   struct ExtAddrMode : public TargetLowering::AddrMode {
00558     Value *BaseReg;
00559     Value *ScaledReg;
00560     ExtAddrMode() : BaseReg(0), ScaledReg(0) {}
00561     void print(OStream &OS) const;
00562     void dump() const {
00563       print(cerr);
00564       cerr << '\n';
00565     }
00566   };
00567 } // end anonymous namespace
00568 
00569 static inline OStream &operator<<(OStream &OS, const ExtAddrMode &AM) {
00570   AM.print(OS);
00571   return OS;
00572 }
00573 
00574 void ExtAddrMode::print(OStream &OS) const {
00575   bool NeedPlus = false;
00576   OS << "[";
00577   if (BaseGV)
00578     OS << (NeedPlus ? " + " : "")
00579        << "GV:%" << BaseGV->getName(), NeedPlus = true;
00580 
00581   if (BaseOffs)
00582     OS << (NeedPlus ? " + " : "") << BaseOffs, NeedPlus = true;
00583 
00584   if (BaseReg)
00585     OS << (NeedPlus ? " + " : "")
00586        << "Base:%" << BaseReg->getName(), NeedPlus = true;
00587   if (Scale)
00588     OS << (NeedPlus ? " + " : "")
00589        << Scale << "*%" << ScaledReg->getName(), NeedPlus = true;
00590 
00591   OS << ']';
00592 }
00593 
00594 namespace {
00595 /// AddressingModeMatcher - This class exposes a single public method, which is
00596 /// used to construct a "maximal munch" of the addressing mode for the target
00597 /// specified by TLI for an access to "V" with an access type of AccessTy.  This
00598 /// returns the addressing mode that is actually matched by value, but also
00599 /// returns the list of instructions involved in that addressing computation in
00600 /// AddrModeInsts.
00601 class AddressingModeMatcher {
00602   SmallVectorImpl<Instruction*> &AddrModeInsts;
00603   const TargetLowering &TLI;
00604 
00605   /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
00606   /// the memory instruction that we're computing this address for.
00607   const Type *AccessTy;
00608   Instruction *MemoryInst;
00609   
00610   /// AddrMode - This is the addressing mode that we're building up.  This is
00611   /// part of the return value of this addressing mode matching stuff.
00612   ExtAddrMode &AddrMode;
00613   
00614   /// IgnoreProfitability - This is set to true when we should not do
00615   /// profitability checks.  When true, IsProfitableToFoldIntoAddressingMode
00616   /// always returns true.
00617   bool IgnoreProfitability;
00618   
00619   AddressingModeMatcher(SmallVectorImpl<Instruction*> &AMI,
00620                         const TargetLowering &T, const Type *AT,
00621                         Instruction *MI, ExtAddrMode &AM)
00622     : AddrModeInsts(AMI), TLI(T), AccessTy(AT), MemoryInst(MI), AddrMode(AM) {
00623     IgnoreProfitability = false;
00624   }
00625 public:
00626   
00627   /// Match - Find the maximal addressing mode that a load/store of V can fold,
00628   /// give an access type of AccessTy.  This returns a list of involved
00629   /// instructions in AddrModeInsts.
00630   static ExtAddrMode Match(Value *V, const Type *AccessTy,
00631                            Instruction *MemoryInst,
00632                            SmallVectorImpl<Instruction*> &AddrModeInsts,
00633                            const TargetLowering &TLI) {
00634     ExtAddrMode Result;
00635 
00636     bool Success = 
00637       AddressingModeMatcher(AddrModeInsts, TLI, AccessTy,
00638                             MemoryInst, Result).MatchAddr(V, 0);
00639     Success = Success; assert(Success && "Couldn't select *anything*?");
00640     return Result;
00641   }
00642 private:
00643   bool MatchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
00644   bool MatchAddr(Value *V, unsigned Depth);
00645   bool MatchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth);
00646   bool IsProfitableToFoldIntoAddressingMode(Instruction *I,
00647                                             ExtAddrMode &AMBefore,
00648                                             ExtAddrMode &AMAfter);
00649   bool ValueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
00650 };
00651 } // end anonymous namespace
00652 
00653 /// MatchScaledValue - Try adding ScaleReg*Scale to the current addressing mode.
00654 /// Return true and update AddrMode if this addr mode is legal for the target,
00655 /// false if not.
00656 bool AddressingModeMatcher::MatchScaledValue(Value *ScaleReg, int64_t Scale,
00657                                              unsigned Depth) {
00658   // If Scale is 1, then this is the same as adding ScaleReg to the addressing
00659   // mode.  Just process that directly.
00660   if (Scale == 1)
00661     return MatchAddr(ScaleReg, Depth);
00662   
00663   // If the scale is 0, it takes nothing to add this.
00664   if (Scale == 0)
00665     return true;
00666   
00667   // If we already have a scale of this value, we can add to it, otherwise, we
00668   // need an available scale field.
00669   if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
00670     return false;
00671 
00672   ExtAddrMode TestAddrMode = AddrMode;
00673 
00674   // Add scale to turn X*4+X*3 -> X*7.  This could also do things like
00675   // [A+B + A*7] -> [B+A*8].
00676   TestAddrMode.Scale += Scale;
00677   TestAddrMode.ScaledReg = ScaleReg;
00678 
00679   // If the new address isn't legal, bail out.
00680   if (!TLI.isLegalAddressingMode(TestAddrMode, AccessTy))
00681     return false;
00682 
00683   // It was legal, so commit it.
00684   AddrMode = TestAddrMode;
00685   
00686   // Okay, we decided that we can add ScaleReg+Scale to AddrMode.  Check now
00687   // to see if ScaleReg is actually X+C.  If so, we can turn this into adding
00688   // X*Scale + C*Scale to addr mode.
00689   ConstantInt *CI; Value *AddLHS;
00690   if (isa<Instruction>(ScaleReg) &&  // not a constant expr.
00691       match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
00692     TestAddrMode.ScaledReg = AddLHS;
00693     TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
00694       
00695     // If this addressing mode is legal, commit it and remember that we folded
00696     // this instruction.
00697     if (TLI.isLegalAddressingMode(TestAddrMode, AccessTy)) {
00698       AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
00699       AddrMode = TestAddrMode;
00700       return true;
00701     }
00702   }
00703 
00704   // Otherwise, not (x+c)*scale, just return what we have.
00705   return true;
00706 }
00707 
00708 /// MightBeFoldableInst - This is a little filter, which returns true if an
00709 /// addressing computation involving I might be folded into a load/store
00710 /// accessing it.  This doesn't need to be perfect, but needs to accept at least
00711 /// the set of instructions that MatchOperationAddr can.
00712 static bool MightBeFoldableInst(Instruction *I) {
00713   switch (I->getOpcode()) {
00714   case Instruction::BitCast:
00715     // Don't touch identity bitcasts.
00716     if (I->getType() == I->getOperand(0)->getType())
00717       return false;
00718     return isa<PointerType>(I->getType()) || isa<IntegerType>(I->getType());
00719   case Instruction::PtrToInt:
00720     // PtrToInt is always a noop, as we know that the int type is pointer sized.
00721     return true;
00722   case Instruction::IntToPtr:
00723     // We know the input is intptr_t, so this is foldable.
00724     return true;
00725   case Instruction::Add:
00726     return true;
00727   case Instruction::Mul:
00728   case Instruction::Shl:
00729     // Can only handle X*C and X << C.
00730     return isa<ConstantInt>(I->getOperand(1));
00731   case Instruction::GetElementPtr:
00732     return true;
00733   default:
00734     return false;
00735   }
00736 }
00737 
00738 
00739 /// MatchOperationAddr - Given an instruction or constant expr, see if we can
00740 /// fold the operation into the addressing mode.  If so, update the addressing
00741 /// mode and return true, otherwise return false without modifying AddrMode.
00742 bool AddressingModeMatcher::MatchOperationAddr(User *AddrInst, unsigned Opcode,
00743                                                unsigned Depth) {
00744   // Avoid exponential behavior on extremely deep expression trees.
00745   if (Depth >= 5) return false;
00746   
00747   switch (Opcode) {
00748   case Instruction::PtrToInt:
00749     // PtrToInt is always a noop, as we know that the int type is pointer sized.
00750     return MatchAddr(AddrInst->getOperand(0), Depth);
00751   case Instruction::IntToPtr:
00752     // This inttoptr is a no-op if the integer type is pointer sized.
00753     if (TLI.getValueType(AddrInst->getOperand(0)->getType()) ==
00754         TLI.getPointerTy())
00755       return MatchAddr(AddrInst->getOperand(0), Depth);
00756     return false;
00757   case Instruction::BitCast:
00758     // BitCast is always a noop, and we can handle it as long as it is
00759     // int->int or pointer->pointer (we don't want int<->fp or something).
00760     if ((isa<PointerType>(AddrInst->getOperand(0)->getType()) ||
00761          isa<IntegerType>(AddrInst->getOperand(0)->getType())) &&
00762         // Don't touch identity bitcasts.  These were probably put here by LSR,
00763         // and we don't want to mess around with them.  Assume it knows what it
00764         // is doing.
00765         AddrInst->getOperand(0)->getType() != AddrInst->getType())
00766       return MatchAddr(AddrInst->getOperand(0), Depth);
00767     return false;
00768   case Instruction::Add: {
00769     // Check to see if we can merge in the RHS then the LHS.  If so, we win.
00770     ExtAddrMode BackupAddrMode = AddrMode;
00771     unsigned OldSize = AddrModeInsts.size();
00772     if (MatchAddr(AddrInst->getOperand(1), Depth+1) &&
00773         MatchAddr(AddrInst->getOperand(0), Depth+1))
00774       return true;
00775     
00776     // Restore the old addr mode info.
00777     AddrMode = BackupAddrMode;
00778     AddrModeInsts.resize(OldSize);
00779     
00780     // Otherwise this was over-aggressive.  Try merging in the LHS then the RHS.
00781     if (MatchAddr(AddrInst->getOperand(0), Depth+1) &&
00782         MatchAddr(AddrInst->getOperand(1), Depth+1))
00783       return true;
00784     
00785     // Otherwise we definitely can't merge the ADD in.
00786     AddrMode = BackupAddrMode;
00787     AddrModeInsts.resize(OldSize);
00788     break;
00789   }
00790   //case Instruction::Or:
00791   // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
00792   //break;
00793   case Instruction::Mul:
00794   case Instruction::Shl: {
00795     // Can only handle X*C and X << C.
00796     ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
00797     if (!RHS) return false;
00798     int64_t Scale = RHS->getSExtValue();
00799     if (Opcode == Instruction::Shl)
00800       Scale = 1 << Scale;
00801     
00802     return MatchScaledValue(AddrInst->getOperand(0), Scale, Depth);
00803   }
00804   case Instruction::GetElementPtr: {
00805     // Scan the GEP.  We check it if it contains constant offsets and at most
00806     // one variable offset.
00807     int VariableOperand = -1;
00808     unsigned VariableScale = 0;
00809     
00810     int64_t ConstantOffset = 0;
00811     const TargetData *TD = TLI.getTargetData();
00812     gep_type_iterator GTI = gep_type_begin(AddrInst);
00813     for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
00814       if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
00815         const StructLayout *SL = TD->getStructLayout(STy);
00816         unsigned Idx =
00817           cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
00818         ConstantOffset += SL->getElementOffset(Idx);
00819       } else {
00820         uint64_t TypeSize = TD->getTypePaddedSize(GTI.getIndexedType());
00821         if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
00822           ConstantOffset += CI->getSExtValue()*TypeSize;
00823         } else if (TypeSize) {  // Scales of zero don't do anything.
00824           // We only allow one variable index at the moment.
00825           if (VariableOperand != -1)
00826             return false;
00827           
00828           // Remember the variable index.
00829           VariableOperand = i;
00830           VariableScale = TypeSize;
00831         }
00832       }
00833     }
00834     
00835     // A common case is for the GEP to only do a constant offset.  In this case,
00836     // just add it to the disp field and check validity.
00837     if (VariableOperand == -1) {
00838       AddrMode.BaseOffs += ConstantOffset;
00839       if (ConstantOffset == 0 || TLI.isLegalAddressingMode(AddrMode, AccessTy)){
00840         // Check to see if we can fold the base pointer in too.
00841         if (MatchAddr(AddrInst->getOperand(0), Depth+1))
00842           return true;
00843       }
00844       AddrMode.BaseOffs -= ConstantOffset;
00845       return false;
00846     }
00847 
00848     // Save the valid addressing mode in case we can't match.
00849     ExtAddrMode BackupAddrMode = AddrMode;
00850     
00851     // Check that this has no base reg yet.  If so, we won't have a place to
00852     // put the base of the GEP (assuming it is not a null ptr).
00853     bool SetBaseReg = true;
00854     if (isa<ConstantPointerNull>(AddrInst->getOperand(0)))
00855       SetBaseReg = false;   // null pointer base doesn't need representation.
00856     else if (AddrMode.HasBaseReg)
00857       return false;  // Base register already specified, can't match GEP.
00858     else {
00859       // Otherwise, we'll use the GEP base as the BaseReg.
00860       AddrMode.HasBaseReg = true;
00861       AddrMode.BaseReg = AddrInst->getOperand(0);
00862     }
00863     
00864     // See if the scale and offset amount is valid for this target.
00865     AddrMode.BaseOffs += ConstantOffset;
00866     
00867     if (!MatchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
00868                           Depth)) {
00869       AddrMode = BackupAddrMode;
00870       return false;
00871     }
00872     
00873     // If we have a null as the base of the GEP, folding in the constant offset
00874     // plus variable scale is all we can do.
00875     if (!SetBaseReg) return true;
00876       
00877     // If this match succeeded, we know that we can form an address with the
00878     // GepBase as the basereg.  Match the base pointer of the GEP more
00879     // aggressively by zeroing out BaseReg and rematching.  If the base is
00880     // (for example) another GEP, this allows merging in that other GEP into
00881     // the addressing mode we're forming.
00882     AddrMode.HasBaseReg = false;
00883     AddrMode.BaseReg = 0;
00884     bool Success = MatchAddr(AddrInst->getOperand(0), Depth+1);
00885     assert(Success && "MatchAddr should be able to fill in BaseReg!");
00886     Success=Success;
00887     return true;
00888   }
00889   }
00890   return false;
00891 }
00892 
00893 /// MatchAddr - If we can, try to add the value of 'Addr' into the current
00894 /// addressing mode.  If Addr can't be added to AddrMode this returns false and
00895 /// leaves AddrMode unmodified.  This assumes that Addr is either a pointer type
00896 /// or intptr_t for the target.
00897 ///
00898 bool AddressingModeMatcher::MatchAddr(Value *Addr, unsigned Depth) {
00899   if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
00900     // Fold in immediates if legal for the target.
00901     AddrMode.BaseOffs += CI->getSExtValue();
00902     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
00903       return true;
00904     AddrMode.BaseOffs -= CI->getSExtValue();
00905   } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
00906     // If this is a global variable, try to fold it into the addressing mode.
00907     if (AddrMode.BaseGV == 0) {
00908       AddrMode.BaseGV = GV;
00909       if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
00910         return true;
00911       AddrMode.BaseGV = 0;
00912     }
00913   } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
00914     ExtAddrMode BackupAddrMode = AddrMode;
00915     unsigned OldSize = AddrModeInsts.size();
00916 
00917     // Check to see if it is possible to fold this operation.
00918     if (MatchOperationAddr(I, I->getOpcode(), Depth)) {
00919       // Okay, it's possible to fold this.  Check to see if it is actually
00920       // *profitable* to do so.  We use a simple cost model to avoid increasing
00921       // register pressure too much.
00922       if (I->hasOneUse() ||
00923           IsProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
00924         AddrModeInsts.push_back(I);
00925         return true;
00926       }
00927       
00928       // It isn't profitable to do this, roll back.
00929       //cerr << "NOT FOLDING: " << *I;
00930       AddrMode = BackupAddrMode;
00931       AddrModeInsts.resize(OldSize);
00932     }
00933   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
00934     if (MatchOperationAddr(CE, CE->getOpcode(), Depth))
00935       return true;
00936   } else if (isa<ConstantPointerNull>(Addr)) {
00937     // Null pointer gets folded without affecting the addressing mode.
00938     return true;
00939   }
00940 
00941   // Worse case, the target should support [reg] addressing modes. :)
00942   if (!AddrMode.HasBaseReg) {
00943     AddrMode.HasBaseReg = true;
00944     AddrMode.BaseReg = Addr;
00945     // Still check for legality in case the target supports [imm] but not [i+r].
00946     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
00947       return true;
00948     AddrMode.HasBaseReg = false;
00949     AddrMode.BaseReg = 0;
00950   }
00951 
00952   // If the base register is already taken, see if we can do [r+r].
00953   if (AddrMode.Scale == 0) {
00954     AddrMode.Scale = 1;
00955     AddrMode.ScaledReg = Addr;
00956     if (TLI.isLegalAddressingMode(AddrMode, AccessTy))
00957       return true;
00958     AddrMode.Scale = 0;
00959     AddrMode.ScaledReg = 0;
00960   }
00961   // Couldn't match.
00962   return false;
00963 }
00964 
00965 
00966 /// IsOperandAMemoryOperand - Check to see if all uses of OpVal by the specified
00967 /// inline asm call are due to memory operands.  If so, return true, otherwise
00968 /// return false.
00969 static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
00970                                     const TargetLowering &TLI) {
00971   std::vector<InlineAsm::ConstraintInfo>
00972   Constraints = IA->ParseConstraints();
00973   
00974   unsigned ArgNo = 1;   // ArgNo - The operand of the CallInst.
00975   for (unsigned i = 0, e = Constraints.size(); i != e; ++i) {
00976     TargetLowering::AsmOperandInfo OpInfo(Constraints[i]);
00977     
00978     // Compute the value type for each operand.
00979     switch (OpInfo.Type) {
00980       case InlineAsm::isOutput:
00981         if (OpInfo.isIndirect)
00982           OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
00983         break;
00984       case InlineAsm::isInput:
00985         OpInfo.CallOperandVal = CI->getOperand(ArgNo++);
00986         break;
00987       case InlineAsm::isClobber:
00988         // Nothing to do.
00989         break;
00990     }
00991     
00992     // Compute the constraint code and ConstraintType to use.
00993     TLI.ComputeConstraintToUse(OpInfo, SDValue(),
00994                              OpInfo.ConstraintType == TargetLowering::C_Memory);
00995     
00996     // If this asm operand is our Value*, and if it isn't an indirect memory
00997     // operand, we can't fold it!
00998     if (OpInfo.CallOperandVal == OpVal &&
00999         (OpInfo.ConstraintType != TargetLowering::C_Memory ||
01000          !OpInfo.isIndirect))
01001       return false;
01002   }
01003   
01004   return true;
01005 }
01006 
01007 
01008 /// FindAllMemoryUses - Recursively walk all the uses of I until we find a
01009 /// memory use.  If we find an obviously non-foldable instruction, return true.
01010 /// Add the ultimately found memory instructions to MemoryUses.
01011 static bool FindAllMemoryUses(Instruction *I,
01012                 SmallVectorImpl<std::pair<Instruction*,unsigned> > &MemoryUses,
01013                               SmallPtrSet<Instruction*, 16> &ConsideredInsts,
01014                               const TargetLowering &TLI) {
01015   // If we already considered this instruction, we're done.
01016   if (!ConsideredInsts.insert(I))
01017     return false;
01018   
01019   // If this is an obviously unfoldable instruction, bail out.
01020   if (!MightBeFoldableInst(I))
01021     return true;
01022 
01023   // Loop over all the uses, recursively processing them.
01024   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
01025        UI != E; ++UI) {
01026     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
01027       MemoryUses.push_back(std::make_pair(LI, UI.getOperandNo()));
01028       continue;
01029     }
01030     
01031     if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
01032       if (UI.getOperandNo() == 0) return true; // Storing addr, not into addr.
01033       MemoryUses.push_back(std::make_pair(SI, UI.getOperandNo()));
01034       continue;
01035     }
01036     
01037     if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
01038       InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
01039       if (IA == 0) return true;
01040       
01041       // If this is a memory operand, we're cool, otherwise bail out.
01042       if (!IsOperandAMemoryOperand(CI, IA, I, TLI))
01043         return true;
01044       continue;
01045     }
01046     
01047     if (FindAllMemoryUses(cast<Instruction>(*UI), MemoryUses, ConsideredInsts,
01048                           TLI))
01049       return true;
01050   }
01051 
01052   return false;
01053 }
01054 
01055 
01056 /// ValueAlreadyLiveAtInst - Retrn true if Val is already known to be live at
01057 /// the use site that we're folding it into.  If so, there is no cost to
01058 /// include it in the addressing mode.  KnownLive1 and KnownLive2 are two values
01059 /// that we know are live at the instruction already.
01060 bool AddressingModeMatcher::ValueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
01061                                                    Value *KnownLive2) {
01062   // If Val is either of the known-live values, we know it is live!
01063   if (Val == 0 || Val == KnownLive1 || Val == KnownLive2)
01064     return true;
01065   
01066   // All values other than instructions and arguments (e.g. constants) are live.
01067   if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
01068   
01069   // If Val is a constant sized alloca in the entry block, it is live, this is
01070   // true because it is just a reference to the stack/frame pointer, which is
01071   // live for the whole function.
01072   if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
01073     if (AI->isStaticAlloca())
01074       return true;
01075   
01076   // Check to see if this value is already used in the memory instruction's
01077   // block.  If so, it's already live into the block at the very least, so we
01078   // can reasonably fold it.
01079   BasicBlock *MemBB = MemoryInst->getParent();
01080   for (Value::use_iterator UI = Val->use_begin(), E = Val->use_end();
01081        UI != E; ++UI)
01082     // We know that uses of arguments and instructions have to be instructions.
01083     if (cast<Instruction>(*UI)->getParent() == MemBB)
01084       return true;
01085   
01086   return false;
01087 }
01088 
01089 
01090 
01091 /// IsProfitableToFoldIntoAddressingMode - It is possible for the addressing
01092 /// mode of the machine to fold the specified instruction into a load or store
01093 /// that ultimately uses it.  However, the specified instruction has multiple
01094 /// uses.  Given this, it may actually increase register pressure to fold it
01095 /// into the load.  For example, consider this code:
01096 ///
01097 ///     X = ...
01098 ///     Y = X+1
01099 ///     use(Y)   -> nonload/store
01100 ///     Z = Y+1
01101 ///     load Z
01102 ///
01103 /// In this case, Y has multiple uses, and can be folded into the load of Z
01104 /// (yielding load [X+2]).  However, doing this will cause both "X" and "X+1" to
01105 /// be live at the use(Y) line.  If we don't fold Y into load Z, we use one
01106 /// fewer register.  Since Y can't be folded into "use(Y)" we don't increase the
01107 /// number of computations either.
01108 ///
01109 /// Note that this (like most of CodeGenPrepare) is just a rough heuristic.  If
01110 /// X was live across 'load Z' for other reasons, we actually *would* want to
01111 /// fold the addressing mode in the Z case.  This would make Y die earlier.
01112 bool AddressingModeMatcher::
01113 IsProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
01114                                      ExtAddrMode &AMAfter) {
01115   if (IgnoreProfitability) return true;
01116   
01117   // AMBefore is the addressing mode before this instruction was folded into it,
01118   // and AMAfter is the addressing mode after the instruction was folded.  Get
01119   // the set of registers referenced by AMAfter and subtract out those
01120   // referenced by AMBefore: this is the set of values which folding in this
01121   // address extends the lifetime of.
01122   //
01123   // Note that there are only two potential values being referenced here,
01124   // BaseReg and ScaleReg (global addresses are always available, as are any
01125   // folded immediates).
01126   Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
01127   
01128   // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
01129   // lifetime wasn't extended by adding this instruction.
01130   if (ValueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
01131     BaseReg = 0;
01132   if (ValueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
01133     ScaledReg = 0;
01134 
01135   // If folding this instruction (and it's subexprs) didn't extend any live
01136   // ranges, we're ok with it.
01137   if (BaseReg == 0 && ScaledReg == 0)
01138     return true;
01139 
01140   // If all uses of this instruction are ultimately load/store/inlineasm's,
01141   // check to see if their addressing modes will include this instruction.  If
01142   // so, we can fold it into all uses, so it doesn't matter if it has multiple
01143   // uses.
01144   SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
01145   SmallPtrSet<Instruction*, 16> ConsideredInsts;
01146   if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI))
01147     return false;  // Has a non-memory, non-foldable use!
01148   
01149   // Now that we know that all uses of this instruction are part of a chain of
01150   // computation involving only operations that could theoretically be folded
01151   // into a memory use, loop over each of these uses and see if they could
01152   // *actually* fold the instruction.
01153   SmallVector<Instruction*, 32> MatchedAddrModeInsts;
01154   for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
01155     Instruction *User = MemoryUses[i].first;
01156     unsigned OpNo = MemoryUses[i].second;
01157     
01158     // Get the access type of this use.  If the use isn't a pointer, we don't
01159     // know what it accesses.
01160     Value *Address = User->getOperand(OpNo);
01161     if (!isa<PointerType>(Address->getType()))
01162       return false;
01163     const Type *AddressAccessTy =
01164       cast<PointerType>(Address->getType())->getElementType();
01165     
01166     // Do a match against the root of this address, ignoring profitability. This
01167     // will tell us if the addressing mode for the memory operation will
01168     // *actually* cover the shared instruction.
01169     ExtAddrMode Result;
01170     AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, AddressAccessTy,
01171                                   MemoryInst, Result);
01172     Matcher.IgnoreProfitability = true;
01173     bool Success = Matcher.MatchAddr(Address, 0);
01174     Success = Success; assert(Success && "Couldn't select *anything*?");
01175 
01176     // If the match didn't cover I, then it won't be shared by it.
01177     if (std::find(MatchedAddrModeInsts.begin(), MatchedAddrModeInsts.end(),
01178                   I) == MatchedAddrModeInsts.end())
01179       return false;
01180     
01181     MatchedAddrModeInsts.clear();
01182   }
01183   
01184   return true;
01185 }
01186 
01187 
01188 //===----------------------------------------------------------------------===//
01189 // Memory Optimization
01190 //===----------------------------------------------------------------------===//
01191 
01192 /// IsNonLocalValue - Return true if the specified values are defined in a
01193 /// different basic block than BB.
01194 static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
01195   if (Instruction *I = dyn_cast<Instruction>(V))
01196     return I->getParent() != BB;
01197   return false;
01198 }
01199 
01200 /// OptimizeMemoryInst - Load and Store Instructions have often have
01201 /// addressing modes that can do significant amounts of computation.  As such,
01202 /// instruction selection will try to get the load or store to do as much
01203 /// computation as possible for the program.  The problem is that isel can only
01204 /// see within a single block.  As such, we sink as much legal addressing mode
01205 /// stuff into the block as possible.
01206 ///
01207 /// This method is used to optimize both load/store and inline asms with memory
01208 /// operands.
01209 bool CodeGenPrepare::OptimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
01210                                         const Type *AccessTy,
01211                                         DenseMap<Value*,Value*> &SunkAddrs) {
01212   // Figure out what addressing mode will be built up for this operation.
01213   SmallVector<Instruction*, 16> AddrModeInsts;
01214   ExtAddrMode AddrMode = AddressingModeMatcher::Match(Addr, AccessTy,MemoryInst,
01215                                                       AddrModeInsts, *TLI);
01216 
01217   // Check to see if any of the instructions supersumed by this addr mode are
01218   // non-local to I's BB.
01219   bool AnyNonLocal = false;
01220   for (unsigned i = 0, e = AddrModeInsts.size(); i != e; ++i) {
01221     if (IsNonLocalValue(AddrModeInsts[i], MemoryInst->getParent())) {
01222       AnyNonLocal = true;
01223       break;
01224     }
01225   }
01226 
01227   // If all the instructions matched are already in this BB, don't do anything.
01228   if (!AnyNonLocal) {
01229     DEBUG(cerr << "CGP: Found      local addrmode: " << AddrMode << "\n");
01230     return false;
01231   }
01232 
01233   // Insert this computation right after this user.  Since our caller is
01234   // scanning from the top of the BB to the bottom, reuse of the expr are
01235   // guaranteed to happen later.
01236   BasicBlock::iterator InsertPt = MemoryInst;
01237 
01238   // Now that we determined the addressing expression we want to use and know
01239   // that we have to sink it into this block.  Check to see if we have already
01240   // done this for some other load/store instr in this block.  If so, reuse the
01241   // computation.
01242   Value *&SunkAddr = SunkAddrs[Addr];
01243   if (SunkAddr) {
01244     DEBUG(cerr << "CGP: Reusing nonlocal addrmode: " << AddrMode << "\n");
01245     if (SunkAddr->getType() != Addr->getType())
01246       SunkAddr = new BitCastInst(SunkAddr, Addr->getType(), "tmp", InsertPt);
01247   } else {
01248     DEBUG(cerr << "CGP: SINKING nonlocal addrmode: " << AddrMode << "\n");
01249     const Type *IntPtrTy = TLI->getTargetData()->getIntPtrType();
01250 
01251     Value *Result = 0;
01252     // Start with the scale value.
01253     if (AddrMode.Scale) {
01254       Value *V = AddrMode.ScaledReg;
01255       if (V->getType() == IntPtrTy) {
01256         // done.
01257       } else if (isa<PointerType>(V->getType())) {
01258         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
01259       } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
01260                  cast<IntegerType>(V->getType())->getBitWidth()) {
01261         V = new TruncInst(V, IntPtrTy, "sunkaddr", InsertPt);
01262       } else {
01263         V = new SExtInst(V, IntPtrTy, "sunkaddr", InsertPt);
01264       }
01265       if (AddrMode.Scale != 1)
01266         V = BinaryOperator::CreateMul(V, ConstantInt::get(IntPtrTy,
01267                                                           AddrMode.Scale),
01268                                       "sunkaddr", InsertPt);
01269       Result = V;
01270     }
01271 
01272     // Add in the base register.
01273     if (AddrMode.BaseReg) {
01274       Value *V = AddrMode.BaseReg;
01275       if (V->getType() != IntPtrTy)
01276         V = new PtrToIntInst(V, IntPtrTy, "sunkaddr", InsertPt);
01277       if (Result)
01278         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
01279       else
01280         Result = V;
01281     }
01282 
01283     // Add in the BaseGV if present.
01284     if (AddrMode.BaseGV) {
01285       Value *V = new PtrToIntInst(AddrMode.BaseGV, IntPtrTy, "sunkaddr",
01286                                   InsertPt);
01287       if (Result)
01288         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
01289       else
01290         Result = V;
01291     }
01292 
01293     // Add in the Base Offset if present.
01294     if (AddrMode.BaseOffs) {
01295       Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
01296       if (Result)
01297         Result = BinaryOperator::CreateAdd(Result, V, "sunkaddr", InsertPt);
01298       else
01299         Result = V;
01300     }
01301 
01302     if (Result == 0)
01303       SunkAddr = Constant::getNullValue(Addr->getType());
01304     else
01305       SunkAddr = new IntToPtrInst(Result, Addr->getType(), "sunkaddr",InsertPt);
01306   }
01307 
01308   MemoryInst->replaceUsesOfWith(Addr, SunkAddr);
01309 
01310   if (Addr->use_empty())
01311     RecursivelyDeleteTriviallyDeadInstructions(Addr);
01312   return true;
01313 }
01314 
01315 /// OptimizeInlineAsmInst - If there are any memory operands, use
01316 /// OptimizeMemoryInst to sink their address computing into the block when
01317 /// possible / profitable.
01318 bool CodeGenPrepare::OptimizeInlineAsmInst(Instruction *I, CallSite CS,
01319                                            DenseMap<Value*,Value*> &SunkAddrs) {
01320   bool MadeChange = false;
01321   InlineAsm *IA = cast<InlineAsm>(CS.getCalledValue());
01322 
01323   // Do a prepass over the constraints, canonicalizing them, and building up the
01324   // ConstraintOperands list.
01325   std::vector<InlineAsm::ConstraintInfo>
01326     ConstraintInfos = IA->ParseConstraints();
01327 
01328   /// ConstraintOperands - Information about all of the constraints.
01329   std::vector<TargetLowering::AsmOperandInfo> ConstraintOperands;
01330   unsigned ArgNo = 0;   // ArgNo - The argument of the CallInst.
01331   for (unsigned i = 0, e = ConstraintInfos.size(); i != e; ++i) {
01332     ConstraintOperands.
01333       push_back(TargetLowering::AsmOperandInfo(ConstraintInfos[i]));
01334     TargetLowering::AsmOperandInfo &OpInfo = ConstraintOperands.back();
01335 
01336     // Compute the value type for each operand.
01337     switch (OpInfo.Type) {
01338     case InlineAsm::isOutput:
01339       if (OpInfo.isIndirect)
01340         OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
01341       break;
01342     case InlineAsm::isInput:
01343       OpInfo.CallOperandVal = CS.getArgument(ArgNo++);
01344       break;
01345     case InlineAsm::isClobber:
01346       // Nothing to do.
01347       break;
01348     }
01349 
01350     // Compute the constraint code and ConstraintType to use.
01351     TLI->ComputeConstraintToUse(OpInfo, SDValue(),
01352                              OpInfo.ConstraintType == TargetLowering::C_Memory);
01353 
01354     if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
01355         OpInfo.isIndirect) {
01356       Value *OpVal = OpInfo.CallOperandVal;
01357       MadeChange |= OptimizeMemoryInst(I, OpVal, OpVal->getType(), SunkAddrs);
01358     }
01359   }
01360 
01361   return MadeChange;
01362 }
01363 
01364 bool CodeGenPrepare::OptimizeExtUses(Instruction *I) {
01365   BasicBlock *DefBB = I->getParent();
01366 
01367   // If both result of the {s|z}xt and its source are live out, rewrite all
01368   // other uses of the source with result of extension.
01369   Value *Src = I->getOperand(0);
01370   if (Src->hasOneUse())
01371     return false;
01372 
01373   // Only do this xform if truncating is free.
01374   if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
01375     return false;
01376 
01377   // Only safe to perform the optimization if the source is also defined in
01378   // this block.
01379   if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
01380     return false;
01381 
01382   bool DefIsLiveOut = false;
01383   for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
01384        UI != E; ++UI) {
01385     Instruction *User = cast<Instruction>(*UI);
01386 
01387     // Figure out which BB this ext is used in.
01388     BasicBlock *UserBB = User->getParent();
01389     if (UserBB == DefBB) continue;
01390     DefIsLiveOut = true;
01391     break;
01392   }
01393   if (!DefIsLiveOut)
01394     return false;
01395 
01396   // Make sure non of the uses are PHI nodes.
01397   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
01398        UI != E; ++UI) {
01399     Instruction *User = cast<Instruction>(*UI);
01400     BasicBlock *UserBB = User->getParent();
01401     if (UserBB == DefBB) continue;
01402     // Be conservative. We don't want this xform to end up introducing
01403     // reloads just before load / store instructions.
01404     if (isa<PHINode>(User) || isa<LoadInst>(User) || isa<StoreInst>(User))
01405       return false;
01406   }
01407 
01408   // InsertedTruncs - Only insert one trunc in each block once.
01409   DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
01410 
01411   bool MadeChange = false;
01412   for (Value::use_iterator UI = Src->use_begin(), E = Src->use_end();
01413        UI != E; ++UI) {
01414     Use &TheUse = UI.getUse();
01415     Instruction *User = cast<Instruction>(*UI);
01416 
01417     // Figure out which BB this ext is used in.
01418     BasicBlock *UserBB = User->getParent();
01419     if (UserBB == DefBB) continue;
01420 
01421     // Both src and def are live in this block. Rewrite the use.
01422     Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
01423 
01424     if (!InsertedTrunc) {
01425       BasicBlock::iterator InsertPt = UserBB->getFirstNonPHI();
01426 
01427       InsertedTrunc = new TruncInst(I, Src->getType(), "", InsertPt);
01428     }
01429 
01430     // Replace a use of the {s|z}ext source with a use of the result.
01431     TheUse = InsertedTrunc;
01432 
01433     MadeChange = true;
01434   }
01435 
01436   return MadeChange;
01437 }
01438 
01439 // In this pass we look for GEP and cast instructions that are used
01440 // across basic blocks and rewrite them to improve basic-block-at-a-time
01441 // selection.
01442 bool CodeGenPrepare::OptimizeBlock(BasicBlock &BB) {
01443   bool MadeChange = false;
01444 
01445   // Split all critical edges where the dest block has a PHI.
01446   TerminatorInst *BBTI = BB.getTerminator();
01447   if (BBTI->getNumSuccessors() > 1) {
01448     for (unsigned i = 0, e = BBTI->getNumSuccessors(); i != e; ++i) {
01449       BasicBlock *SuccBB = BBTI->getSuccessor(i);
01450       if (isa<PHINode>(SuccBB->begin()) && isCriticalEdge(BBTI, i, true))
01451         SplitEdgeNicely(BBTI, i, BackEdges, this);
01452     }
01453   }
01454 
01455   // Keep track of non-local addresses that have been sunk into this block.
01456   // This allows us to avoid inserting duplicate code for blocks with multiple
01457   // load/stores of the same address.
01458   DenseMap<Value*, Value*> SunkAddrs;
01459 
01460   for (BasicBlock::iterator BBI = BB.begin(), E = BB.end(); BBI != E; ) {
01461     Instruction *I = BBI++;
01462 
01463     if (CastInst *CI = dyn_cast<CastInst>(I)) {
01464       // If the source of the cast is a constant, then this should have
01465       // already been constant folded.  The only reason NOT to constant fold
01466       // it is if something (e.g. LSR) was careful to place the constant
01467       // evaluation in a block other than then one that uses it (e.g. to hoist
01468       // the address of globals out of a loop).  If this is the case, we don't
01469       // want to forward-subst the cast.
01470       if (isa<Constant>(CI->getOperand(0)))
01471         continue;
01472 
01473       bool Change = false;
01474       if (TLI) {
01475         Change = OptimizeNoopCopyExpression(CI, *TLI);
01476         MadeChange |= Change;
01477       }
01478 
01479       if (!Change && (isa<ZExtInst>(I) || isa<SExtInst>(I)))
01480         MadeChange |= OptimizeExtUses(I);
01481     } else if (CmpInst *CI = dyn_cast<CmpInst>(I)) {
01482       MadeChange |= OptimizeCmpExpression(CI);
01483     } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
01484       if (TLI)
01485         MadeChange |= OptimizeMemoryInst(I, I->getOperand(0), LI->getType(),
01486                                          SunkAddrs);
01487     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
01488       if (TLI)
01489         MadeChange |= OptimizeMemoryInst(I, SI->getOperand(1),
01490                                          SI->getOperand(0)->getType(),
01491                                          SunkAddrs);
01492     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
01493       if (GEPI->hasAllZeroIndices()) {
01494         /// The GEP operand must be a pointer, so must its result -> BitCast
01495         Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
01496                                           GEPI->getName(), GEPI);
01497         GEPI->replaceAllUsesWith(NC);
01498         GEPI->eraseFromParent();
01499         MadeChange = true;
01500         BBI = NC;
01501       }
01502     } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
01503       // If we found an inline asm expession, and if the target knows how to
01504       // lower it to normal LLVM code, do so now.
01505       if (TLI && isa<InlineAsm>(CI->getCalledValue()))
01506         if (const TargetAsmInfo *TAI =
01507             TLI->getTargetMachine().getTargetAsmInfo()) {
01508           if (TAI->ExpandInlineAsm(CI))
01509             BBI = BB.begin();
01510           else
01511             // Sink address computing for memory operands into the block.
01512             MadeChange |= OptimizeInlineAsmInst(I, &(*CI), SunkAddrs);
01513         }
01514     }
01515   }
01516 
01517   return MadeChange;
01518 }