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 "llvm/ADT/STLExtras.h"
21 #include "llvm/Support/TypeInfo.h"
26 //===----------------------------------------------------------------------===//
27 // AnalysisID Class Implementation
30 // getCFGOnlyAnalyses - A wrapper around the CFGOnlyAnalyses which make it
31 // initializer order independent.
32 static std::vector<const PassInfo*> &getCFGOnlyAnalyses() {
33 static std::vector<const PassInfo*> CFGOnlyAnalyses;
34 return CFGOnlyAnalyses;
37 void RegisterPassBase::setOnlyUsesCFG() {
38 getCFGOnlyAnalyses().push_back(&PIObj);
41 //===----------------------------------------------------------------------===//
42 // AnalysisResolver Class Implementation
45 AnalysisResolver::~AnalysisResolver() {
47 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
48 assert(P->Resolver == 0 && "Pass already in a PassManager!");
52 //===----------------------------------------------------------------------===//
53 // AnalysisUsage Class Implementation
56 // setPreservesCFG - This function should be called to by the pass, iff they do
59 // 1. Add or remove basic blocks from the function
60 // 2. Modify terminator instructions in any way.
62 // This function annotates the AnalysisUsage info object to say that analyses
63 // that only depend on the CFG are preserved by this pass.
65 void AnalysisUsage::setPreservesCFG() {
66 // Since this transformation doesn't modify the CFG, it preserves all analyses
67 // that only depend on the CFG (like dominators, loop info, etc...)
69 Preserved.insert(Preserved.end(),
70 getCFGOnlyAnalyses().begin(), getCFGOnlyAnalyses().end());
74 //===----------------------------------------------------------------------===//
75 // PassManager implementation - The PassManager class is a simple Pimpl class
76 // that wraps the PassManagerT template.
78 PassManager::PassManager() : PM(new ModulePassManager()) {}
79 PassManager::~PassManager() { delete PM; }
80 void PassManager::add(Pass *P) {
81 ModulePass *MP = dynamic_cast<ModulePass*>(P);
82 assert(MP && "Not a modulepass?");
85 bool PassManager::run(Module &M) { return PM->runOnModule(M); }
87 //===----------------------------------------------------------------------===//
88 // FunctionPassManager implementation - The FunctionPassManager class
89 // is a simple Pimpl class that wraps the PassManagerT template. It
90 // is like PassManager, but only deals in FunctionPasses.
92 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
93 PM(new FunctionPassManagerT()), MP(P) {}
94 FunctionPassManager::~FunctionPassManager() { delete PM; }
95 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
96 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
98 /// doInitialization - Run all of the initializers for the function passes.
100 bool FunctionPassManager::doInitialization() {
101 return PM->doInitialization(*MP->getModule());
104 bool FunctionPassManager::run(Function &F) {
106 if (MP->materializeFunction(&F, &errstr)) {
107 std::cerr << "Error reading bytecode file: " << errstr << "\n";
110 return PM->runOnFunction(F);
113 /// doFinalization - Run all of the initializers for the function passes.
115 bool FunctionPassManager::doFinalization() {
116 return PM->doFinalization(*MP->getModule());
120 //===----------------------------------------------------------------------===//
121 // TimingInfo Class - This class is used to calculate information about the
122 // amount of time each pass takes to execute. This only happens with
123 // -time-passes is enabled on the command line.
125 bool llvm::TimePassesIsEnabled = false;
126 static cl::opt<bool,true>
127 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
128 cl::desc("Time each pass, printing elapsed time for each on exit"));
130 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
131 // a non null value (if the -time-passes option is enabled) or it leaves it
132 // null. It may be called multiple times.
133 void TimingInfo::createTheTimeInfo() {
134 if (!TimePassesIsEnabled || TheTimeInfo) return;
136 // Constructed the first time this is called, iff -time-passes is enabled.
137 // This guarantees that the object will be constructed before static globals,
138 // thus it will be destroyed before them.
139 static TimingInfo TTI;
143 void PMDebug::PrintArgumentInformation(const Pass *P) {
144 // Print out passes in pass manager...
145 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
146 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
147 PrintArgumentInformation(PM->getContainedPass(i));
149 } else { // Normal pass. Print argument information...
150 // Print out arguments for registered passes that are _optimizations_
151 if (const PassInfo *PI = P->getPassInfo())
152 if (!PI->isAnalysisGroup())
153 std::cerr << " -" << PI->getPassArgument();
157 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
158 Pass *P, Module *M) {
159 if (PassDebugging >= Executions) {
160 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
162 if (M) std::cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
163 std::cerr << "'...\n";
167 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
168 Pass *P, Function *F) {
169 if (PassDebugging >= Executions) {
170 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
172 if (F) std::cerr << "' on Function '" << F->getName();
173 std::cerr << "'...\n";
177 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
178 Pass *P, BasicBlock *BB) {
179 if (PassDebugging >= Executions) {
180 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
182 if (BB) std::cerr << "' on BasicBlock '" << BB->getName();
183 std::cerr << "'...\n";
187 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
188 Pass *P, const std::vector<AnalysisID> &Set){
189 if (PassDebugging >= Details && !Set.empty()) {
190 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
191 for (unsigned i = 0; i != Set.size(); ++i) {
192 if (i) std::cerr << ",";
193 std::cerr << " " << Set[i]->getPassName();
199 //===----------------------------------------------------------------------===//
200 // Pass Implementation
203 void ModulePass::addToPassManager(ModulePassManager *PM, AnalysisUsage &AU) {
204 PM->addPass(this, AU);
207 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
208 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
211 // dumpPassStructure - Implement the -debug-passes=Structure option
212 void Pass::dumpPassStructure(unsigned Offset) {
213 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
216 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
218 const char *Pass::getPassName() const {
219 if (const PassInfo *PI = getPassInfo())
220 return PI->getPassName();
221 return typeid(*this).name();
224 // print - Print out the internal state of the pass. This is called by Analyze
225 // to print out the contents of an analysis. Otherwise it is not necessary to
226 // implement this method.
228 void Pass::print(std::ostream &O,const Module*) const {
229 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
232 // dump - call print(std::cerr);
233 void Pass::dump() const {
237 //===----------------------------------------------------------------------===//
238 // ImmutablePass Implementation
240 void ImmutablePass::addToPassManager(ModulePassManager *PM,
242 PM->addPass(this, AU);
246 //===----------------------------------------------------------------------===//
247 // FunctionPass Implementation
250 // run - On a module, we run this pass by initializing, runOnFunction'ing once
251 // for every function in the module, then by finalizing.
253 bool FunctionPass::runOnModule(Module &M) {
254 bool Changed = doInitialization(M);
256 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
257 if (!I->isExternal()) // Passes are not run on external functions!
258 Changed |= runOnFunction(*I);
260 return Changed | doFinalization(M);
263 // run - On a function, we simply initialize, run the function, then finalize.
265 bool FunctionPass::run(Function &F) {
266 if (F.isExternal()) return false;// Passes are not run on external functions!
268 bool Changed = doInitialization(*F.getParent());
269 Changed |= runOnFunction(F);
270 return Changed | doFinalization(*F.getParent());
273 void FunctionPass::addToPassManager(ModulePassManager *PM,
275 PM->addPass(this, AU);
278 void FunctionPass::addToPassManager(FunctionPassManagerT *PM,
280 PM->addPass(this, AU);
283 //===----------------------------------------------------------------------===//
284 // BasicBlockPass Implementation
287 // To run this pass on a function, we simply call runOnBasicBlock once for each
290 bool BasicBlockPass::runOnFunction(Function &F) {
291 bool Changed = doInitialization(F);
292 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
293 Changed |= runOnBasicBlock(*I);
294 return Changed | doFinalization(F);
297 // To run directly on the basic block, we initialize, runOnBasicBlock, then
300 bool BasicBlockPass::runPass(BasicBlock &BB) {
301 Function &F = *BB.getParent();
302 Module &M = *F.getParent();
303 bool Changed = doInitialization(M);
304 Changed |= doInitialization(F);
305 Changed |= runOnBasicBlock(BB);
306 Changed |= doFinalization(F);
307 Changed |= doFinalization(M);
311 void BasicBlockPass::addToPassManager(FunctionPassManagerT *PM,
313 PM->addPass(this, AU);
316 void BasicBlockPass::addToPassManager(BasicBlockPassManager *PM,
318 PM->addPass(this, AU);
322 //===----------------------------------------------------------------------===//
323 // Pass Registration mechanism
325 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
326 static std::vector<PassRegistrationListener*> *Listeners = 0;
328 // getPassInfo - Return the PassInfo data structure that corresponds to this
330 const PassInfo *Pass::getPassInfo() const {
331 if (PassInfoCache) return PassInfoCache;
332 return lookupPassInfo(typeid(*this));
335 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
336 if (PassInfoMap == 0) return 0;
337 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
338 return (I != PassInfoMap->end()) ? I->second : 0;
341 void RegisterPassBase::registerPass() {
342 if (PassInfoMap == 0)
343 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
345 assert(PassInfoMap->find(PIObj.getTypeInfo()) == PassInfoMap->end() &&
346 "Pass already registered!");
347 PassInfoMap->insert(std::make_pair(TypeInfo(PIObj.getTypeInfo()), &PIObj));
349 // Notify any listeners...
351 for (std::vector<PassRegistrationListener*>::iterator
352 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
353 (*I)->passRegistered(&PIObj);
356 void RegisterPassBase::unregisterPass() {
357 assert(PassInfoMap && "Pass registered but not in map!");
358 std::map<TypeInfo, PassInfo*>::iterator I =
359 PassInfoMap->find(PIObj.getTypeInfo());
360 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
362 // Remove pass from the map...
363 PassInfoMap->erase(I);
364 if (PassInfoMap->empty()) {
369 // Notify any listeners...
371 for (std::vector<PassRegistrationListener*>::iterator
372 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
373 (*I)->passUnregistered(&PIObj);
376 //===----------------------------------------------------------------------===//
377 // Analysis Group Implementation Code
378 //===----------------------------------------------------------------------===//
380 struct AnalysisGroupInfo {
381 const PassInfo *DefaultImpl;
382 std::set<const PassInfo *> Implementations;
383 AnalysisGroupInfo() : DefaultImpl(0) {}
386 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
388 // RegisterAGBase implementation
390 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
391 const std::type_info *Pass, bool isDefault)
392 : RegisterPassBase(Interface),
393 ImplementationInfo(0), isDefaultImplementation(isDefault) {
395 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
396 if (InterfaceInfo == 0) {
397 // First reference to Interface, register it now.
399 InterfaceInfo = &PIObj;
401 assert(PIObj.isAnalysisGroup() &&
402 "Trying to join an analysis group that is a normal pass!");
405 ImplementationInfo = Pass::lookupPassInfo(*Pass);
406 assert(ImplementationInfo &&
407 "Must register pass before adding to AnalysisGroup!");
409 // Make sure we keep track of the fact that the implementation implements
411 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
412 IIPI->addInterfaceImplemented(InterfaceInfo);
414 // Lazily allocate to avoid nasty initialization order dependencies
415 if (AnalysisGroupInfoMap == 0)
416 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
418 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
419 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
420 "Cannot add a pass to the same analysis group more than once!");
421 AGI.Implementations.insert(ImplementationInfo);
423 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
424 "Default implementation for analysis group already specified!");
425 assert(ImplementationInfo->getNormalCtor() &&
426 "Cannot specify pass as default if it does not have a default ctor");
427 AGI.DefaultImpl = ImplementationInfo;
428 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
433 void RegisterAGBase::setGroupName(const char *Name) {
434 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
435 InterfaceInfo->setPassName(Name);
438 RegisterAGBase::~RegisterAGBase() {
439 if (ImplementationInfo) {
440 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
441 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
443 assert(AGI.Implementations.count(ImplementationInfo) &&
444 "Pass not a member of analysis group?");
446 if (AGI.DefaultImpl == ImplementationInfo)
449 AGI.Implementations.erase(ImplementationInfo);
451 // Last member of this analysis group? Unregister PassInfo, delete map entry
452 if (AGI.Implementations.empty()) {
453 assert(AGI.DefaultImpl == 0 &&
454 "Default implementation didn't unregister?");
455 AnalysisGroupInfoMap->erase(InterfaceInfo);
456 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
457 delete AnalysisGroupInfoMap;
458 AnalysisGroupInfoMap = 0;
463 if (InterfaceInfo == &PIObj)
468 //===----------------------------------------------------------------------===//
469 // PassRegistrationListener implementation
472 // PassRegistrationListener ctor - Add the current object to the list of
473 // PassRegistrationListeners...
474 PassRegistrationListener::PassRegistrationListener() {
475 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
476 Listeners->push_back(this);
479 // dtor - Remove object from list of listeners...
480 PassRegistrationListener::~PassRegistrationListener() {
481 std::vector<PassRegistrationListener*>::iterator I =
482 std::find(Listeners->begin(), Listeners->end(), this);
483 assert(Listeners && I != Listeners->end() &&
484 "PassRegistrationListener not registered!");
487 if (Listeners->empty()) {
493 // enumeratePasses - Iterate over the registered passes, calling the
494 // passEnumerate callback on each PassInfo object.
496 void PassRegistrationListener::enumeratePasses() {
498 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
499 E = PassInfoMap->end(); I != E; ++I)
500 passEnumerate(I->second);