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"
26 //===----------------------------------------------------------------------===//
27 // AnalysisResolver Class Implementation
30 AnalysisResolver::~AnalysisResolver() {
32 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
33 assert(P->Resolver == 0 && "Pass already in a PassManager!");
37 //===----------------------------------------------------------------------===//
38 // PassManager implementation - The PassManager class is a simple Pimpl class
39 // that wraps the PassManagerT template.
41 PassManager::PassManager() : PM(new ModulePassManager()) {}
42 PassManager::~PassManager() { delete PM; }
43 void PassManager::add(Pass *P) {
44 ModulePass *MP = dynamic_cast<ModulePass*>(P);
45 assert(MP && "Not a modulepass?");
48 bool PassManager::run(Module &M) { return PM->runOnModule(M); }
50 //===----------------------------------------------------------------------===//
51 // FunctionPassManager implementation - The FunctionPassManager class
52 // is a simple Pimpl class that wraps the PassManagerT template. It
53 // is like PassManager, but only deals in FunctionPasses.
55 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
56 PM(new FunctionPassManagerT()), MP(P) {}
57 FunctionPassManager::~FunctionPassManager() { delete PM; }
58 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
59 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
61 /// doInitialization - Run all of the initializers for the function passes.
63 bool FunctionPassManager::doInitialization() {
64 return PM->doInitialization(*MP->getModule());
67 bool FunctionPassManager::run(Function &F) {
69 if (MP->materializeFunction(&F, &errstr)) {
70 cerr << "Error reading bytecode file: " << errstr << "\n";
73 return PM->runOnFunction(F);
76 /// doFinalization - Run all of the initializers for the function passes.
78 bool FunctionPassManager::doFinalization() {
79 return PM->doFinalization(*MP->getModule());
83 //===----------------------------------------------------------------------===//
84 // TimingInfo Class - This class is used to calculate information about the
85 // amount of time each pass takes to execute. This only happens with
86 // -time-passes is enabled on the command line.
88 bool llvm::TimePassesIsEnabled = false;
89 static cl::opt<bool,true>
90 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
91 cl::desc("Time each pass, printing elapsed time for each on exit"));
93 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
94 // a non null value (if the -time-passes option is enabled) or it leaves it
95 // null. It may be called multiple times.
96 void TimingInfo::createTheTimeInfo() {
97 if (!TimePassesIsEnabled || TheTimeInfo) return;
99 // Constructed the first time this is called, iff -time-passes is enabled.
100 // This guarantees that the object will be constructed before static globals,
101 // thus it will be destroyed before them.
102 static ManagedStatic<TimingInfo> TTI;
106 void PMDebug::PrintArgumentInformation(const Pass *P) {
107 // Print out passes in pass manager...
108 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
109 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
110 PrintArgumentInformation(PM->getContainedPass(i));
112 } else { // Normal pass. Print argument information...
113 // Print out arguments for registered passes that are _optimizations_
114 if (const PassInfo *PI = P->getPassInfo())
115 if (!PI->isAnalysisGroup())
116 cerr << " -" << PI->getPassArgument();
120 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
121 Pass *P, Module *M) {
122 if (PassDebugging >= Executions) {
123 cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
125 if (M) cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
130 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
131 Pass *P, Function *F) {
132 if (PassDebugging >= Executions) {
133 cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
135 if (F) cerr << "' on Function '" << F->getName();
140 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
141 Pass *P, BasicBlock *BB) {
142 if (PassDebugging >= Executions) {
143 cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
145 if (BB) cerr << "' on BasicBlock '" << BB->getName();
150 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
151 Pass *P, const std::vector<AnalysisID> &Set){
152 if (PassDebugging >= Details && !Set.empty()) {
153 cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
154 for (unsigned i = 0; i != Set.size(); ++i) {
156 cerr << " " << Set[i]->getPassName();
162 //===----------------------------------------------------------------------===//
163 // Pass Implementation
166 void ModulePass::addToPassManager(ModulePassManager *PM, AnalysisUsage &AU) {
167 PM->addPass(this, AU);
170 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
171 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
174 // dumpPassStructure - Implement the -debug-passes=Structure option
175 void Pass::dumpPassStructure(unsigned Offset) {
176 cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
179 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
181 const char *Pass::getPassName() const {
182 if (const PassInfo *PI = getPassInfo())
183 return PI->getPassName();
184 return typeid(*this).name();
187 // print - Print out the internal state of the pass. This is called by Analyze
188 // to print out the contents of an analysis. Otherwise it is not necessary to
189 // implement this method.
191 void Pass::print(std::ostream &O,const Module*) const {
192 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
195 // dump - call print(cerr);
196 void Pass::dump() const {
197 print(*cerr.stream(), 0);
200 //===----------------------------------------------------------------------===//
201 // ImmutablePass Implementation
203 void ImmutablePass::addToPassManager(ModulePassManager *PM,
205 PM->addPass(this, AU);
209 //===----------------------------------------------------------------------===//
210 // FunctionPass Implementation
213 // run - On a module, we run this pass by initializing, runOnFunction'ing once
214 // for every function in the module, then by finalizing.
216 bool FunctionPass::runOnModule(Module &M) {
217 bool Changed = doInitialization(M);
219 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
220 if (!I->isExternal()) // Passes are not run on external functions!
221 Changed |= runOnFunction(*I);
223 return Changed | doFinalization(M);
226 // run - On a function, we simply initialize, run the function, then finalize.
228 bool FunctionPass::run(Function &F) {
229 if (F.isExternal()) return false;// Passes are not run on external functions!
231 bool Changed = doInitialization(*F.getParent());
232 Changed |= runOnFunction(F);
233 return Changed | doFinalization(*F.getParent());
236 void FunctionPass::addToPassManager(ModulePassManager *PM,
238 PM->addPass(this, AU);
241 void FunctionPass::addToPassManager(FunctionPassManagerT *PM,
243 PM->addPass(this, AU);
246 //===----------------------------------------------------------------------===//
247 // BasicBlockPass Implementation
250 // To run this pass on a function, we simply call runOnBasicBlock once for each
253 bool BasicBlockPass::runOnFunction(Function &F) {
254 bool Changed = doInitialization(F);
255 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
256 Changed |= runOnBasicBlock(*I);
257 return Changed | doFinalization(F);
260 // To run directly on the basic block, we initialize, runOnBasicBlock, then
263 bool BasicBlockPass::runPass(BasicBlock &BB) {
264 Function &F = *BB.getParent();
265 Module &M = *F.getParent();
266 bool Changed = doInitialization(M);
267 Changed |= doInitialization(F);
268 Changed |= runOnBasicBlock(BB);
269 Changed |= doFinalization(F);
270 Changed |= doFinalization(M);
274 void BasicBlockPass::addToPassManager(FunctionPassManagerT *PM,
276 PM->addPass(this, AU);
279 void BasicBlockPass::addToPassManager(BasicBlockPassManager *PM,
281 PM->addPass(this, AU);
285 //===----------------------------------------------------------------------===//
286 // Pass Registration mechanism
289 class PassRegistrar {
290 /// PassInfoMap - Keep track of the passinfo object for each registered llvm
292 std::map<TypeInfo, PassInfo*> PassInfoMap;
294 /// AnalysisGroupInfo - Keep track of information for each analysis group.
295 struct AnalysisGroupInfo {
296 const PassInfo *DefaultImpl;
297 std::set<const PassInfo *> Implementations;
298 AnalysisGroupInfo() : DefaultImpl(0) {}
301 /// AnalysisGroupInfoMap - Information for each analysis group.
302 std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
306 const PassInfo *GetPassInfo(const std::type_info &TI) const {
307 std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.find(TI);
308 return I != PassInfoMap.end() ? I->second : 0;
311 void RegisterPass(PassInfo &PI) {
313 PassInfoMap.insert(std::make_pair(TypeInfo(PI.getTypeInfo()),&PI)).second;
314 assert(Inserted && "Pass registered multiple times!");
317 void UnregisterPass(PassInfo &PI) {
318 std::map<TypeInfo, PassInfo*>::iterator I =
319 PassInfoMap.find(PI.getTypeInfo());
320 assert(I != PassInfoMap.end() && "Pass registered but not in map!");
322 // Remove pass from the map.
323 PassInfoMap.erase(I);
326 void EnumerateWith(PassRegistrationListener *L) {
327 for (std::map<TypeInfo, PassInfo*>::const_iterator I = PassInfoMap.begin(),
328 E = PassInfoMap.end(); I != E; ++I)
329 L->passEnumerate(I->second);
333 /// Analysis Group Mechanisms.
334 void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
335 const PassInfo *ImplementationInfo,
337 AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
338 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
339 "Cannot add a pass to the same analysis group more than once!");
340 AGI.Implementations.insert(ImplementationInfo);
342 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
343 "Default implementation for analysis group already specified!");
344 assert(ImplementationInfo->getNormalCtor() &&
345 "Cannot specify pass as default if it does not have a default ctor");
346 AGI.DefaultImpl = ImplementationInfo;
347 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
353 static ManagedStatic<PassRegistrar> PassRegistrarObj;
354 static std::vector<PassRegistrationListener*> *Listeners = 0;
356 // getPassInfo - Return the PassInfo data structure that corresponds to this
358 const PassInfo *Pass::getPassInfo() const {
359 if (PassInfoCache) return PassInfoCache;
360 return lookupPassInfo(typeid(*this));
363 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
364 return PassRegistrarObj->GetPassInfo(TI);
367 void RegisterPassBase::registerPass() {
368 PassRegistrarObj->RegisterPass(PIObj);
370 // Notify any listeners.
372 for (std::vector<PassRegistrationListener*>::iterator
373 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
374 (*I)->passRegistered(&PIObj);
377 void RegisterPassBase::unregisterPass() {
378 PassRegistrarObj->UnregisterPass(PIObj);
381 //===----------------------------------------------------------------------===//
382 // Analysis Group Implementation Code
383 //===----------------------------------------------------------------------===//
385 // RegisterAGBase implementation
387 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
388 const std::type_info *Pass, bool isDefault)
389 : RegisterPassBase(Interface),
390 ImplementationInfo(0), isDefaultImplementation(isDefault) {
392 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
393 if (InterfaceInfo == 0) {
394 // First reference to Interface, register it now.
396 InterfaceInfo = &PIObj;
398 assert(PIObj.isAnalysisGroup() &&
399 "Trying to join an analysis group that is a normal pass!");
402 ImplementationInfo = Pass::lookupPassInfo(*Pass);
403 assert(ImplementationInfo &&
404 "Must register pass before adding to AnalysisGroup!");
406 // Make sure we keep track of the fact that the implementation implements
408 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
409 IIPI->addInterfaceImplemented(InterfaceInfo);
411 PassRegistrarObj->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
415 void RegisterAGBase::setGroupName(const char *Name) {
416 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
417 InterfaceInfo->setPassName(Name);
421 //===----------------------------------------------------------------------===//
422 // PassRegistrationListener implementation
425 // PassRegistrationListener ctor - Add the current object to the list of
426 // PassRegistrationListeners...
427 PassRegistrationListener::PassRegistrationListener() {
428 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
429 Listeners->push_back(this);
432 // dtor - Remove object from list of listeners...
433 PassRegistrationListener::~PassRegistrationListener() {
434 std::vector<PassRegistrationListener*>::iterator I =
435 std::find(Listeners->begin(), Listeners->end(), this);
436 assert(Listeners && I != Listeners->end() &&
437 "PassRegistrationListener not registered!");
440 if (Listeners->empty()) {
446 // enumeratePasses - Iterate over the registered passes, calling the
447 // passEnumerate callback on each PassInfo object.
449 void PassRegistrationListener::enumeratePasses() {
450 PassRegistrarObj->EnumerateWith(this);
453 //===----------------------------------------------------------------------===//
454 // AnalysisUsage Class Implementation
458 struct GetCFGOnlyPasses : public PassRegistrationListener {
459 std::vector<AnalysisID> &CFGOnlyList;
460 GetCFGOnlyPasses(std::vector<AnalysisID> &L) : CFGOnlyList(L) {}
462 void passEnumerate(const PassInfo *P) {
463 if (P->isCFGOnlyPass())
464 CFGOnlyList.push_back(P);
469 // setPreservesCFG - This function should be called to by the pass, iff they do
472 // 1. Add or remove basic blocks from the function
473 // 2. Modify terminator instructions in any way.
475 // This function annotates the AnalysisUsage info object to say that analyses
476 // that only depend on the CFG are preserved by this pass.
478 void AnalysisUsage::setPreservesCFG() {
479 // Since this transformation doesn't modify the CFG, it preserves all analyses
480 // that only depend on the CFG (like dominators, loop info, etc...)
481 GetCFGOnlyPasses(Preserved).enumeratePasses();