1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM Pass infrastructure. It is primarily
11 // responsible with ensuring that passes are executed and batched together
14 //===----------------------------------------------------------------------===//
16 #include "llvm/PassManager.h"
17 #include "PassManagerT.h" // PassManagerT implementation
18 #include "llvm/Module.h"
19 #include "llvm/ModuleProvider.h"
20 #include "Support/STLExtras.h"
21 #include "Support/TypeInfo.h"
26 // IncludeFile - Stub function used to help linking out.
27 IncludeFile::IncludeFile(void*) {}
29 //===----------------------------------------------------------------------===//
30 // AnalysisID Class Implementation
33 // getCFGOnlyAnalyses - A wrapper around the CFGOnlyAnalyses which make it
34 // initializer order independent.
35 static std::vector<const PassInfo*> &getCFGOnlyAnalyses() {
36 static std::vector<const PassInfo*> CFGOnlyAnalyses;
37 return CFGOnlyAnalyses;
40 void RegisterPassBase::setOnlyUsesCFG() {
41 getCFGOnlyAnalyses().push_back(PIObj);
44 //===----------------------------------------------------------------------===//
45 // AnalysisResolver Class Implementation
48 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
49 assert(P->Resolver == 0 && "Pass already in a PassManager!");
53 //===----------------------------------------------------------------------===//
54 // AnalysisUsage Class Implementation
57 // setPreservesCFG - This function should be called to by the pass, iff they do
60 // 1. Add or remove basic blocks from the function
61 // 2. Modify terminator instructions in any way.
63 // This function annotates the AnalysisUsage info object to say that analyses
64 // that only depend on the CFG are preserved by this pass.
66 void AnalysisUsage::setPreservesCFG() {
67 // Since this transformation doesn't modify the CFG, it preserves all analyses
68 // that only depend on the CFG (like dominators, loop info, etc...)
70 Preserved.insert(Preserved.end(),
71 getCFGOnlyAnalyses().begin(), getCFGOnlyAnalyses().end());
75 //===----------------------------------------------------------------------===//
76 // PassManager implementation - The PassManager class is a simple Pimpl class
77 // that wraps the PassManagerT template.
79 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
80 PassManager::~PassManager() { delete PM; }
81 void PassManager::add(Pass *P) { PM->add(P); }
82 bool PassManager::run(Module &M) { return PM->run(M); }
84 //===----------------------------------------------------------------------===//
85 // FunctionPassManager implementation - The FunctionPassManager class
86 // is a simple Pimpl class that wraps the PassManagerT template. It
87 // is like PassManager, but only deals in FunctionPasses.
89 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
90 PM(new PassManagerT<Function>()), MP(P) {}
91 FunctionPassManager::~FunctionPassManager() { delete PM; }
92 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
93 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
94 bool FunctionPassManager::run(Function &F) {
96 MP->materializeFunction(&F);
97 } catch (std::string& errstr) {
98 std::cerr << "Error reading bytecode file: " << errstr << "\n";
101 std::cerr << "Error reading bytecode file!\n";
108 //===----------------------------------------------------------------------===//
109 // TimingInfo Class - This class is used to calculate information about the
110 // amount of time each pass takes to execute. This only happens with
111 // -time-passes is enabled on the command line.
114 EnableTiming("time-passes",
115 cl::desc("Time each pass, printing elapsed time for each on exit"));
117 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
118 // a non null value (if the -time-passes option is enabled) or it leaves it
119 // null. It may be called multiple times.
120 void TimingInfo::createTheTimeInfo() {
121 if (!EnableTiming || TheTimeInfo) return;
123 // Constructed the first time this is called, iff -time-passes is enabled.
124 // This guarantees that the object will be constructed before static globals,
125 // thus it will be destroyed before them.
126 static TimingInfo TTI;
130 void PMDebug::PrintArgumentInformation(const Pass *P) {
131 // Print out passes in pass manager...
132 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
133 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
134 PrintArgumentInformation(PM->getContainedPass(i));
136 } else { // Normal pass. Print argument information...
137 // Print out arguments for registered passes that are _optimizations_
138 if (const PassInfo *PI = P->getPassInfo())
139 if (PI->getPassType() & PassInfo::Optimization)
140 std::cerr << " -" << PI->getPassArgument();
144 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
145 Pass *P, Module *M) {
146 if (PassDebugging >= Executions) {
147 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
149 if (M) std::cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
150 std::cerr << "'...\n";
154 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
155 Pass *P, Function *F) {
156 if (PassDebugging >= Executions) {
157 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
159 if (F) std::cerr << "' on Function '" << F->getName();
160 std::cerr << "'...\n";
164 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
165 Pass *P, BasicBlock *BB) {
166 if (PassDebugging >= Executions) {
167 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
169 if (BB) std::cerr << "' on BasicBlock '" << BB->getName();
170 std::cerr << "'...\n";
174 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
175 Pass *P, const std::vector<AnalysisID> &Set){
176 if (PassDebugging >= Details && !Set.empty()) {
177 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
178 for (unsigned i = 0; i != Set.size(); ++i) {
179 if (i) std::cerr << ",";
180 std::cerr << " " << Set[i]->getPassName();
186 //===----------------------------------------------------------------------===//
187 // Pass Implementation
190 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
191 PM->addPass(this, AU);
194 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
195 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
198 // dumpPassStructure - Implement the -debug-passes=Structure option
199 void Pass::dumpPassStructure(unsigned Offset) {
200 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
203 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
205 const char *Pass::getPassName() const {
206 if (const PassInfo *PI = getPassInfo())
207 return PI->getPassName();
208 return typeid(*this).name();
211 // print - Print out the internal state of the pass. This is called by Analyze
212 // to print out the contents of an analysis. Otherwise it is not necessary to
213 // implement this method.
215 void Pass::print(std::ostream &O) const {
216 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
219 // dump - call print(std::cerr);
220 void Pass::dump() const {
224 //===----------------------------------------------------------------------===//
225 // ImmutablePass Implementation
227 void ImmutablePass::addToPassManager(PassManagerT<Module> *PM,
229 PM->addPass(this, AU);
233 //===----------------------------------------------------------------------===//
234 // FunctionPass Implementation
237 // run - On a module, we run this pass by initializing, runOnFunction'ing once
238 // for every function in the module, then by finalizing.
240 bool FunctionPass::run(Module &M) {
241 bool Changed = doInitialization(M);
243 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
244 if (!I->isExternal()) // Passes are not run on external functions!
245 Changed |= runOnFunction(*I);
247 return Changed | doFinalization(M);
250 // run - On a function, we simply initialize, run the function, then finalize.
252 bool FunctionPass::run(Function &F) {
253 if (F.isExternal()) return false;// Passes are not run on external functions!
255 return doInitialization(*F.getParent()) | runOnFunction(F)
256 | doFinalization(*F.getParent());
259 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
261 PM->addPass(this, AU);
264 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
266 PM->addPass(this, AU);
269 //===----------------------------------------------------------------------===//
270 // BasicBlockPass Implementation
273 // To run this pass on a function, we simply call runOnBasicBlock once for each
276 bool BasicBlockPass::runOnFunction(Function &F) {
277 bool Changed = doInitialization(F);
278 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
279 Changed |= runOnBasicBlock(*I);
280 return Changed | doFinalization(F);
283 // To run directly on the basic block, we initialize, runOnBasicBlock, then
286 bool BasicBlockPass::run(BasicBlock &BB) {
287 Function &F = *BB.getParent();
288 Module &M = *F.getParent();
289 return doInitialization(M) | doInitialization(F) | runOnBasicBlock(BB) |
290 doFinalization(F) | doFinalization(M);
293 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
295 PM->addPass(this, AU);
298 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
300 PM->addPass(this, AU);
304 //===----------------------------------------------------------------------===//
305 // Pass Registration mechanism
307 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
308 static std::vector<PassRegistrationListener*> *Listeners = 0;
310 // getPassInfo - Return the PassInfo data structure that corresponds to this
312 const PassInfo *Pass::getPassInfo() const {
313 if (PassInfoCache) return PassInfoCache;
314 return lookupPassInfo(typeid(*this));
317 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
318 if (PassInfoMap == 0) return 0;
319 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
320 return (I != PassInfoMap->end()) ? I->second : 0;
323 void RegisterPassBase::registerPass(PassInfo *PI) {
324 if (PassInfoMap == 0)
325 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
327 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
328 "Pass already registered!");
330 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
332 // Notify any listeners...
334 for (std::vector<PassRegistrationListener*>::iterator
335 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
336 (*I)->passRegistered(PI);
339 void RegisterPassBase::unregisterPass(PassInfo *PI) {
340 assert(PassInfoMap && "Pass registered but not in map!");
341 std::map<TypeInfo, PassInfo*>::iterator I =
342 PassInfoMap->find(PI->getTypeInfo());
343 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
345 // Remove pass from the map...
346 PassInfoMap->erase(I);
347 if (PassInfoMap->empty()) {
352 // Notify any listeners...
354 for (std::vector<PassRegistrationListener*>::iterator
355 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
356 (*I)->passUnregistered(PI);
358 // Delete the PassInfo object itself...
362 //===----------------------------------------------------------------------===//
363 // Analysis Group Implementation Code
364 //===----------------------------------------------------------------------===//
366 struct AnalysisGroupInfo {
367 const PassInfo *DefaultImpl;
368 std::set<const PassInfo *> Implementations;
369 AnalysisGroupInfo() : DefaultImpl(0) {}
372 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
374 // RegisterAGBase implementation
376 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
377 const std::type_info *Pass, bool isDefault)
378 : ImplementationInfo(0), isDefaultImplementation(isDefault) {
380 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
381 if (InterfaceInfo == 0) { // First reference to Interface, add it now.
382 InterfaceInfo = // Create the new PassInfo for the interface...
383 new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
384 registerPass(InterfaceInfo);
387 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
388 "Trying to join an analysis group that is a normal pass!");
391 ImplementationInfo = Pass::lookupPassInfo(*Pass);
392 assert(ImplementationInfo &&
393 "Must register pass before adding to AnalysisGroup!");
395 // Make sure we keep track of the fact that the implementation implements
397 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
398 IIPI->addInterfaceImplemented(InterfaceInfo);
400 // Lazily allocate to avoid nasty initialization order dependencies
401 if (AnalysisGroupInfoMap == 0)
402 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
404 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
405 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
406 "Cannot add a pass to the same analysis group more than once!");
407 AGI.Implementations.insert(ImplementationInfo);
409 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
410 "Default implementation for analysis group already specified!");
411 assert(ImplementationInfo->getNormalCtor() &&
412 "Cannot specify pass as default if it does not have a default ctor");
413 AGI.DefaultImpl = ImplementationInfo;
414 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
419 void RegisterAGBase::setGroupName(const char *Name) {
420 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
421 InterfaceInfo->setPassName(Name);
424 RegisterAGBase::~RegisterAGBase() {
425 if (ImplementationInfo) {
426 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
427 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
429 assert(AGI.Implementations.count(ImplementationInfo) &&
430 "Pass not a member of analysis group?");
432 if (AGI.DefaultImpl == ImplementationInfo)
435 AGI.Implementations.erase(ImplementationInfo);
437 // Last member of this analysis group? Unregister PassInfo, delete map entry
438 if (AGI.Implementations.empty()) {
439 assert(AGI.DefaultImpl == 0 &&
440 "Default implementation didn't unregister?");
441 AnalysisGroupInfoMap->erase(InterfaceInfo);
442 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
443 delete AnalysisGroupInfoMap;
444 AnalysisGroupInfoMap = 0;
447 unregisterPass(InterfaceInfo);
453 //===----------------------------------------------------------------------===//
454 // PassRegistrationListener implementation
457 // PassRegistrationListener ctor - Add the current object to the list of
458 // PassRegistrationListeners...
459 PassRegistrationListener::PassRegistrationListener() {
460 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
461 Listeners->push_back(this);
464 // dtor - Remove object from list of listeners...
465 PassRegistrationListener::~PassRegistrationListener() {
466 std::vector<PassRegistrationListener*>::iterator I =
467 std::find(Listeners->begin(), Listeners->end(), this);
468 assert(Listeners && I != Listeners->end() &&
469 "PassRegistrationListener not registered!");
472 if (Listeners->empty()) {
478 // enumeratePasses - Iterate over the registered passes, calling the
479 // passEnumerate callback on each PassInfo object.
481 void PassRegistrationListener::enumeratePasses() {
483 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
484 E = PassInfoMap->end(); I != E; ++I)
485 passEnumerate(I->second);