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/ManagedStatic.h"
22 #include "llvm/Support/TypeInfo.h"
27 //===----------------------------------------------------------------------===//
28 // AnalysisResolver Class Implementation
31 AnalysisResolver::~AnalysisResolver() {
33 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
34 assert(P->Resolver == 0 && "Pass already in a PassManager!");
38 //===----------------------------------------------------------------------===//
39 // PassManager implementation - The PassManager class is a simple Pimpl class
40 // that wraps the PassManagerT template.
42 PassManager::PassManager() : PM(new ModulePassManager()) {}
43 PassManager::~PassManager() { delete PM; }
44 void PassManager::add(Pass *P) {
45 ModulePass *MP = dynamic_cast<ModulePass*>(P);
46 assert(MP && "Not a modulepass?");
49 bool PassManager::run(Module &M) { return PM->runOnModule(M); }
51 //===----------------------------------------------------------------------===//
52 // FunctionPassManager implementation - The FunctionPassManager class
53 // is a simple Pimpl class that wraps the PassManagerT template. It
54 // is like PassManager, but only deals in FunctionPasses.
56 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
57 PM(new FunctionPassManagerT()), MP(P) {}
58 FunctionPassManager::~FunctionPassManager() { delete PM; }
59 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
60 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
62 /// doInitialization - Run all of the initializers for the function passes.
64 bool FunctionPassManager::doInitialization() {
65 return PM->doInitialization(*MP->getModule());
68 bool FunctionPassManager::run(Function &F) {
70 if (MP->materializeFunction(&F, &errstr)) {
71 std::cerr << "Error reading bytecode file: " << errstr << "\n";
74 return PM->runOnFunction(F);
77 /// doFinalization - Run all of the initializers for the function passes.
79 bool FunctionPassManager::doFinalization() {
80 return PM->doFinalization(*MP->getModule());
84 //===----------------------------------------------------------------------===//
85 // TimingInfo Class - This class is used to calculate information about the
86 // amount of time each pass takes to execute. This only happens with
87 // -time-passes is enabled on the command line.
89 bool llvm::TimePassesIsEnabled = false;
90 static cl::opt<bool,true>
91 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
92 cl::desc("Time each pass, printing elapsed time for each on exit"));
94 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
95 // a non null value (if the -time-passes option is enabled) or it leaves it
96 // null. It may be called multiple times.
97 void TimingInfo::createTheTimeInfo() {
98 if (!TimePassesIsEnabled || TheTimeInfo) return;
100 // Constructed the first time this is called, iff -time-passes is enabled.
101 // This guarantees that the object will be constructed before static globals,
102 // thus it will be destroyed before them.
103 static TimingInfo TTI;
107 void PMDebug::PrintArgumentInformation(const Pass *P) {
108 // Print out passes in pass manager...
109 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
110 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
111 PrintArgumentInformation(PM->getContainedPass(i));
113 } else { // Normal pass. Print argument information...
114 // Print out arguments for registered passes that are _optimizations_
115 if (const PassInfo *PI = P->getPassInfo())
116 if (!PI->isAnalysisGroup())
117 std::cerr << " -" << PI->getPassArgument();
121 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
122 Pass *P, Module *M) {
123 if (PassDebugging >= Executions) {
124 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
126 if (M) std::cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
127 std::cerr << "'...\n";
131 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
132 Pass *P, Function *F) {
133 if (PassDebugging >= Executions) {
134 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
136 if (F) std::cerr << "' on Function '" << F->getName();
137 std::cerr << "'...\n";
141 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
142 Pass *P, BasicBlock *BB) {
143 if (PassDebugging >= Executions) {
144 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
146 if (BB) std::cerr << "' on BasicBlock '" << BB->getName();
147 std::cerr << "'...\n";
151 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
152 Pass *P, const std::vector<AnalysisID> &Set){
153 if (PassDebugging >= Details && !Set.empty()) {
154 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
155 for (unsigned i = 0; i != Set.size(); ++i) {
156 if (i) std::cerr << ",";
157 std::cerr << " " << Set[i]->getPassName();
163 //===----------------------------------------------------------------------===//
164 // Pass Implementation
167 void ModulePass::addToPassManager(ModulePassManager *PM, AnalysisUsage &AU) {
168 PM->addPass(this, AU);
171 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
172 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
175 // dumpPassStructure - Implement the -debug-passes=Structure option
176 void Pass::dumpPassStructure(unsigned Offset) {
177 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
180 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
182 const char *Pass::getPassName() const {
183 if (const PassInfo *PI = getPassInfo())
184 return PI->getPassName();
185 return typeid(*this).name();
188 // print - Print out the internal state of the pass. This is called by Analyze
189 // to print out the contents of an analysis. Otherwise it is not necessary to
190 // implement this method.
192 void Pass::print(std::ostream &O,const Module*) const {
193 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
196 // dump - call print(std::cerr);
197 void Pass::dump() const {
201 //===----------------------------------------------------------------------===//
202 // ImmutablePass Implementation
204 void ImmutablePass::addToPassManager(ModulePassManager *PM,
206 PM->addPass(this, AU);
210 //===----------------------------------------------------------------------===//
211 // FunctionPass Implementation
214 // run - On a module, we run this pass by initializing, runOnFunction'ing once
215 // for every function in the module, then by finalizing.
217 bool FunctionPass::runOnModule(Module &M) {
218 bool Changed = doInitialization(M);
220 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
221 if (!I->isExternal()) // Passes are not run on external functions!
222 Changed |= runOnFunction(*I);
224 return Changed | doFinalization(M);
227 // run - On a function, we simply initialize, run the function, then finalize.
229 bool FunctionPass::run(Function &F) {
230 if (F.isExternal()) return false;// Passes are not run on external functions!
232 bool Changed = doInitialization(*F.getParent());
233 Changed |= runOnFunction(F);
234 return Changed | doFinalization(*F.getParent());
237 void FunctionPass::addToPassManager(ModulePassManager *PM,
239 PM->addPass(this, AU);
242 void FunctionPass::addToPassManager(FunctionPassManagerT *PM,
244 PM->addPass(this, AU);
247 //===----------------------------------------------------------------------===//
248 // BasicBlockPass Implementation
251 // To run this pass on a function, we simply call runOnBasicBlock once for each
254 bool BasicBlockPass::runOnFunction(Function &F) {
255 bool Changed = doInitialization(F);
256 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
257 Changed |= runOnBasicBlock(*I);
258 return Changed | doFinalization(F);
261 // To run directly on the basic block, we initialize, runOnBasicBlock, then
264 bool BasicBlockPass::runPass(BasicBlock &BB) {
265 Function &F = *BB.getParent();
266 Module &M = *F.getParent();
267 bool Changed = doInitialization(M);
268 Changed |= doInitialization(F);
269 Changed |= runOnBasicBlock(BB);
270 Changed |= doFinalization(F);
271 Changed |= doFinalization(M);
275 void BasicBlockPass::addToPassManager(FunctionPassManagerT *PM,
277 PM->addPass(this, AU);
280 void BasicBlockPass::addToPassManager(BasicBlockPassManager *PM,
282 PM->addPass(this, AU);
286 //===----------------------------------------------------------------------===//
287 // Pass Registration mechanism
290 class PassRegistrar {
291 /// PassInfoMap - Keep track of the passinfo object for each registered llvm
293 std::map<TypeInfo, PassInfo*> PassInfoMap;
295 /// AnalysisGroupInfo - Keep track of information for each analysis group.
296 struct AnalysisGroupInfo {
297 const PassInfo *DefaultImpl;
298 std::set<const PassInfo *> Implementations;
299 AnalysisGroupInfo() : DefaultImpl(0) {}
302 /// AnalysisGroupInfoMap - Information for each analysis group.
303 std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
307 const PassInfo *GetPassInfo(const std::type_info &TI) const {
308 std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.find(TI);
309 return I != PassInfoMap.end() ? I->second : 0;
312 void RegisterPass(PassInfo &PI) {
314 PassInfoMap.insert(std::make_pair(TypeInfo(PI.getTypeInfo()),&PI)).second;
315 assert(Inserted && "Pass registered multiple times!");
318 void UnregisterPass(PassInfo &PI) {
319 std::map<TypeInfo, PassInfo*>::iterator I =
320 PassInfoMap.find(PI.getTypeInfo());
321 assert(I != PassInfoMap.end() && "Pass registered but not in map!");
323 // Remove pass from the map.
324 PassInfoMap.erase(I);
327 void EnumerateWith(PassRegistrationListener *L) {
328 for (std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.begin(),
329 E = PassInfoMap.end(); I != E; ++I)
330 L->passEnumerate(I->second);
334 /// Analysis Group Mechanisms.
335 void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
336 const PassInfo *ImplementationInfo,
338 AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
339 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
340 "Cannot add a pass to the same analysis group more than once!");
341 AGI.Implementations.insert(ImplementationInfo);
343 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
344 "Default implementation for analysis group already specified!");
345 assert(ImplementationInfo->getNormalCtor() &&
346 "Cannot specify pass as default if it does not have a default ctor");
347 AGI.DefaultImpl = ImplementationInfo;
348 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
354 static ManagedStatic<PassRegistrar> PassRegistrarObj;
355 static std::vector<PassRegistrationListener*> *Listeners = 0;
357 // getPassInfo - Return the PassInfo data structure that corresponds to this
359 const PassInfo *Pass::getPassInfo() const {
360 if (PassInfoCache) return PassInfoCache;
361 return lookupPassInfo(typeid(*this));
364 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
365 return PassRegistrarObj->GetPassInfo(TI);
368 void RegisterPassBase::registerPass() {
369 PassRegistrarObj->RegisterPass(PIObj);
371 // Notify any listeners.
373 for (std::vector<PassRegistrationListener*>::iterator
374 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
375 (*I)->passRegistered(&PIObj);
378 void RegisterPassBase::unregisterPass() {
379 PassRegistrarObj->UnregisterPass(PIObj);
382 //===----------------------------------------------------------------------===//
383 // Analysis Group Implementation Code
384 //===----------------------------------------------------------------------===//
386 // RegisterAGBase implementation
388 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
389 const std::type_info *Pass, bool isDefault)
390 : RegisterPassBase(Interface),
391 ImplementationInfo(0), isDefaultImplementation(isDefault) {
393 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
394 if (InterfaceInfo == 0) {
395 // First reference to Interface, register it now.
397 InterfaceInfo = &PIObj;
399 assert(PIObj.isAnalysisGroup() &&
400 "Trying to join an analysis group that is a normal pass!");
403 ImplementationInfo = Pass::lookupPassInfo(*Pass);
404 assert(ImplementationInfo &&
405 "Must register pass before adding to AnalysisGroup!");
407 // Make sure we keep track of the fact that the implementation implements
409 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
410 IIPI->addInterfaceImplemented(InterfaceInfo);
412 PassRegistrarObj->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
416 void RegisterAGBase::setGroupName(const char *Name) {
417 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
418 InterfaceInfo->setPassName(Name);
422 //===----------------------------------------------------------------------===//
423 // PassRegistrationListener implementation
426 // PassRegistrationListener ctor - Add the current object to the list of
427 // PassRegistrationListeners...
428 PassRegistrationListener::PassRegistrationListener() {
429 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
430 Listeners->push_back(this);
433 // dtor - Remove object from list of listeners...
434 PassRegistrationListener::~PassRegistrationListener() {
435 std::vector<PassRegistrationListener*>::iterator I =
436 std::find(Listeners->begin(), Listeners->end(), this);
437 assert(Listeners && I != Listeners->end() &&
438 "PassRegistrationListener not registered!");
441 if (Listeners->empty()) {
447 // enumeratePasses - Iterate over the registered passes, calling the
448 // passEnumerate callback on each PassInfo object.
450 void PassRegistrationListener::enumeratePasses() {
451 PassRegistrarObj->EnumerateWith(this);
454 //===----------------------------------------------------------------------===//
455 // AnalysisUsage Class Implementation
459 struct GetCFGOnlyPasses : public PassRegistrationListener {
460 std::vector<AnalysisID> &CFGOnlyList;
461 GetCFGOnlyPasses(std::vector<AnalysisID> &L) : CFGOnlyList(L) {}
463 void passEnumerate(const PassInfo *P) {
464 if (P->isCFGOnlyPass())
465 CFGOnlyList.push_back(P);
470 // setPreservesCFG - This function should be called to by the pass, iff they do
473 // 1. Add or remove basic blocks from the function
474 // 2. Modify terminator instructions in any way.
476 // This function annotates the AnalysisUsage info object to say that analyses
477 // that only depend on the CFG are preserved by this pass.
479 void AnalysisUsage::setPreservesCFG() {
480 // Since this transformation doesn't modify the CFG, it preserves all analyses
481 // that only depend on the CFG (like dominators, loop info, etc...)
482 GetCFGOnlyPasses(Preserved).enumeratePasses();