LLVM API Documentation
00001 //===-- Sink.cpp - Code Sinking -------------------------------------------===// 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 moves instructions into successor blocks, when possible, so that 00011 // they aren't executed on paths where their results aren't needed. 00012 // 00013 //===----------------------------------------------------------------------===// 00014 00015 #define DEBUG_TYPE "sink" 00016 #include "llvm/Transforms/Scalar.h" 00017 #include "llvm/ADT/Statistic.h" 00018 #include "llvm/Analysis/AliasAnalysis.h" 00019 #include "llvm/Analysis/Dominators.h" 00020 #include "llvm/Analysis/LoopInfo.h" 00021 #include "llvm/Analysis/ValueTracking.h" 00022 #include "llvm/Assembly/Writer.h" 00023 #include "llvm/IR/IntrinsicInst.h" 00024 #include "llvm/Support/CFG.h" 00025 #include "llvm/Support/Debug.h" 00026 #include "llvm/Support/raw_ostream.h" 00027 using namespace llvm; 00028 00029 STATISTIC(NumSunk, "Number of instructions sunk"); 00030 STATISTIC(NumSinkIter, "Number of sinking iterations"); 00031 00032 namespace { 00033 class Sinking : public FunctionPass { 00034 DominatorTree *DT; 00035 LoopInfo *LI; 00036 AliasAnalysis *AA; 00037 00038 public: 00039 static char ID; // Pass identification 00040 Sinking() : FunctionPass(ID) { 00041 initializeSinkingPass(*PassRegistry::getPassRegistry()); 00042 } 00043 00044 virtual bool runOnFunction(Function &F); 00045 00046 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 00047 AU.setPreservesCFG(); 00048 FunctionPass::getAnalysisUsage(AU); 00049 AU.addRequired<AliasAnalysis>(); 00050 AU.addRequired<DominatorTree>(); 00051 AU.addRequired<LoopInfo>(); 00052 AU.addPreserved<DominatorTree>(); 00053 AU.addPreserved<LoopInfo>(); 00054 } 00055 private: 00056 bool ProcessBlock(BasicBlock &BB); 00057 bool SinkInstruction(Instruction *I, SmallPtrSet<Instruction *, 8> &Stores); 00058 bool AllUsesDominatedByBlock(Instruction *Inst, BasicBlock *BB) const; 00059 bool IsAcceptableTarget(Instruction *Inst, BasicBlock *SuccToSinkTo) const; 00060 }; 00061 } // end anonymous namespace 00062 00063 char Sinking::ID = 0; 00064 INITIALIZE_PASS_BEGIN(Sinking, "sink", "Code sinking", false, false) 00065 INITIALIZE_PASS_DEPENDENCY(LoopInfo) 00066 INITIALIZE_PASS_DEPENDENCY(DominatorTree) 00067 INITIALIZE_AG_DEPENDENCY(AliasAnalysis) 00068 INITIALIZE_PASS_END(Sinking, "sink", "Code sinking", false, false) 00069 00070 FunctionPass *llvm::createSinkingPass() { return new Sinking(); } 00071 00072 /// AllUsesDominatedByBlock - Return true if all uses of the specified value 00073 /// occur in blocks dominated by the specified block. 00074 bool Sinking::AllUsesDominatedByBlock(Instruction *Inst, 00075 BasicBlock *BB) const { 00076 // Ignoring debug uses is necessary so debug info doesn't affect the code. 00077 // This may leave a referencing dbg_value in the original block, before 00078 // the definition of the vreg. Dwarf generator handles this although the 00079 // user might not get the right info at runtime. 00080 for (Value::use_iterator I = Inst->use_begin(), 00081 E = Inst->use_end(); I != E; ++I) { 00082 // Determine the block of the use. 00083 Instruction *UseInst = cast<Instruction>(*I); 00084 BasicBlock *UseBlock = UseInst->getParent(); 00085 if (PHINode *PN = dyn_cast<PHINode>(UseInst)) { 00086 // PHI nodes use the operand in the predecessor block, not the block with 00087 // the PHI. 00088 unsigned Num = PHINode::getIncomingValueNumForOperand(I.getOperandNo()); 00089 UseBlock = PN->getIncomingBlock(Num); 00090 } 00091 // Check that it dominates. 00092 if (!DT->dominates(BB, UseBlock)) 00093 return false; 00094 } 00095 return true; 00096 } 00097 00098 bool Sinking::runOnFunction(Function &F) { 00099 DT = &getAnalysis<DominatorTree>(); 00100 LI = &getAnalysis<LoopInfo>(); 00101 AA = &getAnalysis<AliasAnalysis>(); 00102 00103 bool MadeChange, EverMadeChange = false; 00104 00105 do { 00106 MadeChange = false; 00107 DEBUG(dbgs() << "Sinking iteration " << NumSinkIter << "\n"); 00108 // Process all basic blocks. 00109 for (Function::iterator I = F.begin(), E = F.end(); 00110 I != E; ++I) 00111 MadeChange |= ProcessBlock(*I); 00112 EverMadeChange |= MadeChange; 00113 NumSinkIter++; 00114 } while (MadeChange); 00115 00116 return EverMadeChange; 00117 } 00118 00119 bool Sinking::ProcessBlock(BasicBlock &BB) { 00120 // Can't sink anything out of a block that has less than two successors. 00121 if (BB.getTerminator()->getNumSuccessors() <= 1 || BB.empty()) return false; 00122 00123 // Don't bother sinking code out of unreachable blocks. In addition to being 00124 // unprofitable, it can also lead to infinite looping, because in an 00125 // unreachable loop there may be nowhere to stop. 00126 if (!DT->isReachableFromEntry(&BB)) return false; 00127 00128 bool MadeChange = false; 00129 00130 // Walk the basic block bottom-up. Remember if we saw a store. 00131 BasicBlock::iterator I = BB.end(); 00132 --I; 00133 bool ProcessedBegin = false; 00134 SmallPtrSet<Instruction *, 8> Stores; 00135 do { 00136 Instruction *Inst = I; // The instruction to sink. 00137 00138 // Predecrement I (if it's not begin) so that it isn't invalidated by 00139 // sinking. 00140 ProcessedBegin = I == BB.begin(); 00141 if (!ProcessedBegin) 00142 --I; 00143 00144 if (isa<DbgInfoIntrinsic>(Inst)) 00145 continue; 00146 00147 if (SinkInstruction(Inst, Stores)) 00148 ++NumSunk, MadeChange = true; 00149 00150 // If we just processed the first instruction in the block, we're done. 00151 } while (!ProcessedBegin); 00152 00153 return MadeChange; 00154 } 00155 00156 static bool isSafeToMove(Instruction *Inst, AliasAnalysis *AA, 00157 SmallPtrSet<Instruction *, 8> &Stores) { 00158 00159 if (Inst->mayWriteToMemory()) { 00160 Stores.insert(Inst); 00161 return false; 00162 } 00163 00164 if (LoadInst *L = dyn_cast<LoadInst>(Inst)) { 00165 AliasAnalysis::Location Loc = AA->getLocation(L); 00166 for (SmallPtrSet<Instruction *, 8>::iterator I = Stores.begin(), 00167 E = Stores.end(); I != E; ++I) 00168 if (AA->getModRefInfo(*I, Loc) & AliasAnalysis::Mod) 00169 return false; 00170 } 00171 00172 if (isa<TerminatorInst>(Inst) || isa<PHINode>(Inst)) 00173 return false; 00174 00175 return true; 00176 } 00177 00178 /// IsAcceptableTarget - Return true if it is possible to sink the instruction 00179 /// in the specified basic block. 00180 bool Sinking::IsAcceptableTarget(Instruction *Inst, 00181 BasicBlock *SuccToSinkTo) const { 00182 assert(Inst && "Instruction to be sunk is null"); 00183 assert(SuccToSinkTo && "Candidate sink target is null"); 00184 00185 // It is not possible to sink an instruction into its own block. This can 00186 // happen with loops. 00187 if (Inst->getParent() == SuccToSinkTo) 00188 return false; 00189 00190 // If the block has multiple predecessors, this would introduce computation 00191 // on different code paths. We could split the critical edge, but for now we 00192 // just punt. 00193 // FIXME: Split critical edges if not backedges. 00194 if (SuccToSinkTo->getUniquePredecessor() != Inst->getParent()) { 00195 // We cannot sink a load across a critical edge - there may be stores in 00196 // other code paths. 00197 if (!isSafeToSpeculativelyExecute(Inst)) 00198 return false; 00199 00200 // We don't want to sink across a critical edge if we don't dominate the 00201 // successor. We could be introducing calculations to new code paths. 00202 if (!DT->dominates(Inst->getParent(), SuccToSinkTo)) 00203 return false; 00204 00205 // Don't sink instructions into a loop. 00206 Loop *succ = LI->getLoopFor(SuccToSinkTo); 00207 Loop *cur = LI->getLoopFor(Inst->getParent()); 00208 if (succ != 0 && succ != cur) 00209 return false; 00210 } 00211 00212 // Finally, check that all the uses of the instruction are actually 00213 // dominated by the candidate 00214 return AllUsesDominatedByBlock(Inst, SuccToSinkTo); 00215 } 00216 00217 /// SinkInstruction - Determine whether it is safe to sink the specified machine 00218 /// instruction out of its current block into a successor. 00219 bool Sinking::SinkInstruction(Instruction *Inst, 00220 SmallPtrSet<Instruction *, 8> &Stores) { 00221 // Check if it's safe to move the instruction. 00222 if (!isSafeToMove(Inst, AA, Stores)) 00223 return false; 00224 00225 // FIXME: This should include support for sinking instructions within the 00226 // block they are currently in to shorten the live ranges. We often get 00227 // instructions sunk into the top of a large block, but it would be better to 00228 // also sink them down before their first use in the block. This xform has to 00229 // be careful not to *increase* register pressure though, e.g. sinking 00230 // "x = y + z" down if it kills y and z would increase the live ranges of y 00231 // and z and only shrink the live range of x. 00232 00233 // SuccToSinkTo - This is the successor to sink this instruction to, once we 00234 // decide. 00235 BasicBlock *SuccToSinkTo = 0; 00236 00237 // Instructions can only be sunk if all their uses are in blocks 00238 // dominated by one of the successors. 00239 // Look at all the postdominators and see if we can sink it in one. 00240 DomTreeNode *DTN = DT->getNode(Inst->getParent()); 00241 for (DomTreeNode::iterator I = DTN->begin(), E = DTN->end(); 00242 I != E && SuccToSinkTo == 0; ++I) { 00243 BasicBlock *Candidate = (*I)->getBlock(); 00244 if ((*I)->getIDom()->getBlock() == Inst->getParent() && 00245 IsAcceptableTarget(Inst, Candidate)) 00246 SuccToSinkTo = Candidate; 00247 } 00248 00249 // If no suitable postdominator was found, look at all the successors and 00250 // decide which one we should sink to, if any. 00251 for (succ_iterator I = succ_begin(Inst->getParent()), 00252 E = succ_end(Inst->getParent()); I != E && SuccToSinkTo == 0; ++I) { 00253 if (IsAcceptableTarget(Inst, *I)) 00254 SuccToSinkTo = *I; 00255 } 00256 00257 // If we couldn't find a block to sink to, ignore this instruction. 00258 if (SuccToSinkTo == 0) 00259 return false; 00260 00261 DEBUG(dbgs() << "Sink" << *Inst << " ("; 00262 WriteAsOperand(dbgs(), Inst->getParent(), false); 00263 dbgs() << " -> "; 00264 WriteAsOperand(dbgs(), SuccToSinkTo, false); 00265 dbgs() << ")\n"); 00266 00267 // Move the instruction. 00268 Inst->moveBefore(SuccToSinkTo->getFirstInsertionPt()); 00269 return true; 00270 }