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 // 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 std::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 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 std::cerr << " -" << PI->getPassArgument();
120 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
121 Pass *P, Module *M) {
122 if (PassDebugging >= Executions) {
123 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
125 if (M) std::cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
126 std::cerr << "'...\n";
130 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
131 Pass *P, Function *F) {
132 if (PassDebugging >= Executions) {
133 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
135 if (F) std::cerr << "' on Function '" << F->getName();
136 std::cerr << "'...\n";
140 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
141 Pass *P, BasicBlock *BB) {
142 if (PassDebugging >= Executions) {
143 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
145 if (BB) std::cerr << "' on BasicBlock '" << BB->getName();
146 std::cerr << "'...\n";
150 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
151 Pass *P, const std::vector<AnalysisID> &Set){
152 if (PassDebugging >= Details && !Set.empty()) {
153 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
154 for (unsigned i = 0; i != Set.size(); ++i) {
155 if (i) std::cerr << ",";
156 std::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 std::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(std::cerr);
196 void Pass::dump() const {
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
288 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
289 static std::vector<PassRegistrationListener*> *Listeners = 0;
291 // getPassInfo - Return the PassInfo data structure that corresponds to this
293 const PassInfo *Pass::getPassInfo() const {
294 if (PassInfoCache) return PassInfoCache;
295 return lookupPassInfo(typeid(*this));
298 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
299 if (PassInfoMap == 0) return 0;
300 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
301 return (I != PassInfoMap->end()) ? I->second : 0;
304 void RegisterPassBase::registerPass() {
305 if (PassInfoMap == 0)
306 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
308 assert(PassInfoMap->find(PIObj.getTypeInfo()) == PassInfoMap->end() &&
309 "Pass already registered!");
310 PassInfoMap->insert(std::make_pair(TypeInfo(PIObj.getTypeInfo()), &PIObj));
312 // Notify any listeners...
314 for (std::vector<PassRegistrationListener*>::iterator
315 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
316 (*I)->passRegistered(&PIObj);
319 void RegisterPassBase::unregisterPass() {
320 assert(PassInfoMap && "Pass registered but not in map!");
321 std::map<TypeInfo, PassInfo*>::iterator I =
322 PassInfoMap->find(PIObj.getTypeInfo());
323 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
325 // Remove pass from the map...
326 PassInfoMap->erase(I);
327 if (PassInfoMap->empty()) {
332 // Notify any listeners...
334 for (std::vector<PassRegistrationListener*>::iterator
335 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
336 (*I)->passUnregistered(&PIObj);
339 //===----------------------------------------------------------------------===//
340 // Analysis Group Implementation Code
341 //===----------------------------------------------------------------------===//
343 struct AnalysisGroupInfo {
344 const PassInfo *DefaultImpl;
345 std::set<const PassInfo *> Implementations;
346 AnalysisGroupInfo() : DefaultImpl(0) {}
349 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
351 // RegisterAGBase implementation
353 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
354 const std::type_info *Pass, bool isDefault)
355 : RegisterPassBase(Interface),
356 ImplementationInfo(0), isDefaultImplementation(isDefault) {
358 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
359 if (InterfaceInfo == 0) {
360 // First reference to Interface, register it now.
362 InterfaceInfo = &PIObj;
364 assert(PIObj.isAnalysisGroup() &&
365 "Trying to join an analysis group that is a normal pass!");
368 ImplementationInfo = Pass::lookupPassInfo(*Pass);
369 assert(ImplementationInfo &&
370 "Must register pass before adding to AnalysisGroup!");
372 // Make sure we keep track of the fact that the implementation implements
374 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
375 IIPI->addInterfaceImplemented(InterfaceInfo);
377 // Lazily allocate to avoid nasty initialization order dependencies
378 if (AnalysisGroupInfoMap == 0)
379 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
381 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
382 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
383 "Cannot add a pass to the same analysis group more than once!");
384 AGI.Implementations.insert(ImplementationInfo);
386 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
387 "Default implementation for analysis group already specified!");
388 assert(ImplementationInfo->getNormalCtor() &&
389 "Cannot specify pass as default if it does not have a default ctor");
390 AGI.DefaultImpl = ImplementationInfo;
391 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
396 void RegisterAGBase::setGroupName(const char *Name) {
397 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
398 InterfaceInfo->setPassName(Name);
401 RegisterAGBase::~RegisterAGBase() {
402 if (ImplementationInfo) {
403 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
404 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
406 assert(AGI.Implementations.count(ImplementationInfo) &&
407 "Pass not a member of analysis group?");
409 if (AGI.DefaultImpl == ImplementationInfo)
412 AGI.Implementations.erase(ImplementationInfo);
414 // Last member of this analysis group? Unregister PassInfo, delete map entry
415 if (AGI.Implementations.empty()) {
416 assert(AGI.DefaultImpl == 0 &&
417 "Default implementation didn't unregister?");
418 AnalysisGroupInfoMap->erase(InterfaceInfo);
419 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
420 delete AnalysisGroupInfoMap;
421 AnalysisGroupInfoMap = 0;
426 if (InterfaceInfo == &PIObj)
431 //===----------------------------------------------------------------------===//
432 // PassRegistrationListener implementation
435 // PassRegistrationListener ctor - Add the current object to the list of
436 // PassRegistrationListeners...
437 PassRegistrationListener::PassRegistrationListener() {
438 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
439 Listeners->push_back(this);
442 // dtor - Remove object from list of listeners...
443 PassRegistrationListener::~PassRegistrationListener() {
444 std::vector<PassRegistrationListener*>::iterator I =
445 std::find(Listeners->begin(), Listeners->end(), this);
446 assert(Listeners && I != Listeners->end() &&
447 "PassRegistrationListener not registered!");
450 if (Listeners->empty()) {
456 // enumeratePasses - Iterate over the registered passes, calling the
457 // passEnumerate callback on each PassInfo object.
459 void PassRegistrationListener::enumeratePasses() {
461 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
462 E = PassInfoMap->end(); I != E; ++I)
463 passEnumerate(I->second);
466 //===----------------------------------------------------------------------===//
467 // AnalysisUsage Class Implementation
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...)
484 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
485 E = PassInfoMap->end(); I != E; ++I)
486 if (I->second->isCFGOnlyPass())
487 Preserved.push_back(I->second);