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); }
97 bool FunctionPassManager::run(Function &F) {
99 MP->materializeFunction(&F);
100 } catch (std::string& errstr) {
101 std::cerr << "Error reading bytecode file: " << errstr << "\n";
104 std::cerr << "Error reading bytecode file!\n";
111 //===----------------------------------------------------------------------===//
112 // TimingInfo Class - This class is used to calculate information about the
113 // amount of time each pass takes to execute. This only happens with
114 // -time-passes is enabled on the command line.
116 bool llvm::TimePassesIsEnabled = false;
117 static cl::opt<bool,true>
118 EnableTiming("time-passes", cl::location(TimePassesIsEnabled),
119 cl::desc("Time each pass, printing elapsed time for each on exit"));
121 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
122 // a non null value (if the -time-passes option is enabled) or it leaves it
123 // null. It may be called multiple times.
124 void TimingInfo::createTheTimeInfo() {
125 if (!TimePassesIsEnabled || TheTimeInfo) return;
127 // Constructed the first time this is called, iff -time-passes is enabled.
128 // This guarantees that the object will be constructed before static globals,
129 // thus it will be destroyed before them.
130 static TimingInfo TTI;
134 void PMDebug::PrintArgumentInformation(const Pass *P) {
135 // Print out passes in pass manager...
136 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
137 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
138 PrintArgumentInformation(PM->getContainedPass(i));
140 } else { // Normal pass. Print argument information...
141 // Print out arguments for registered passes that are _optimizations_
142 if (const PassInfo *PI = P->getPassInfo())
143 if (PI->getPassType() & PassInfo::Optimization)
144 std::cerr << " -" << PI->getPassArgument();
148 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
149 Pass *P, Module *M) {
150 if (PassDebugging >= Executions) {
151 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
153 if (M) std::cerr << "' on Module '" << M->getModuleIdentifier() << "'\n";
154 std::cerr << "'...\n";
158 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
159 Pass *P, Function *F) {
160 if (PassDebugging >= Executions) {
161 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
163 if (F) std::cerr << "' on Function '" << F->getName();
164 std::cerr << "'...\n";
168 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
169 Pass *P, BasicBlock *BB) {
170 if (PassDebugging >= Executions) {
171 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
173 if (BB) std::cerr << "' on BasicBlock '" << BB->getName();
174 std::cerr << "'...\n";
178 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
179 Pass *P, const std::vector<AnalysisID> &Set){
180 if (PassDebugging >= Details && !Set.empty()) {
181 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
182 for (unsigned i = 0; i != Set.size(); ++i) {
183 if (i) std::cerr << ",";
184 std::cerr << " " << Set[i]->getPassName();
190 //===----------------------------------------------------------------------===//
191 // Pass Implementation
194 void ModulePass::addToPassManager(ModulePassManager *PM, AnalysisUsage &AU) {
195 PM->addPass(this, AU);
198 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
199 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
202 // dumpPassStructure - Implement the -debug-passes=Structure option
203 void Pass::dumpPassStructure(unsigned Offset) {
204 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
207 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligible name for the pass.
209 const char *Pass::getPassName() const {
210 if (const PassInfo *PI = getPassInfo())
211 return PI->getPassName();
212 return typeid(*this).name();
215 // print - Print out the internal state of the pass. This is called by Analyze
216 // to print out the contents of an analysis. Otherwise it is not necessary to
217 // implement this method.
219 void Pass::print(std::ostream &O,const Module*) const {
220 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
223 // dump - call print(std::cerr);
224 void Pass::dump() const {
228 //===----------------------------------------------------------------------===//
229 // ImmutablePass Implementation
231 void ImmutablePass::addToPassManager(ModulePassManager *PM,
233 PM->addPass(this, AU);
237 //===----------------------------------------------------------------------===//
238 // FunctionPass Implementation
241 // run - On a module, we run this pass by initializing, runOnFunction'ing once
242 // for every function in the module, then by finalizing.
244 bool FunctionPass::runOnModule(Module &M) {
245 bool Changed = doInitialization(M);
247 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
248 if (!I->isExternal()) // Passes are not run on external functions!
249 Changed |= runOnFunction(*I);
251 return Changed | doFinalization(M);
254 // run - On a function, we simply initialize, run the function, then finalize.
256 bool FunctionPass::run(Function &F) {
257 if (F.isExternal()) return false;// Passes are not run on external functions!
259 bool Changed = doInitialization(*F.getParent());
260 Changed |= runOnFunction(F);
261 return Changed | doFinalization(*F.getParent());
264 void FunctionPass::addToPassManager(ModulePassManager *PM,
266 PM->addPass(this, AU);
269 void FunctionPass::addToPassManager(FunctionPassManagerT *PM,
271 PM->addPass(this, AU);
274 //===----------------------------------------------------------------------===//
275 // BasicBlockPass Implementation
278 // To run this pass on a function, we simply call runOnBasicBlock once for each
281 bool BasicBlockPass::runOnFunction(Function &F) {
282 bool Changed = doInitialization(F);
283 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
284 Changed |= runOnBasicBlock(*I);
285 return Changed | doFinalization(F);
288 // To run directly on the basic block, we initialize, runOnBasicBlock, then
291 bool BasicBlockPass::runPass(BasicBlock &BB) {
292 Function &F = *BB.getParent();
293 Module &M = *F.getParent();
294 bool Changed = doInitialization(M);
295 Changed |= doInitialization(F);
296 Changed |= runOnBasicBlock(BB);
297 Changed |= doFinalization(F);
298 Changed |= doFinalization(M);
302 void BasicBlockPass::addToPassManager(FunctionPassManagerT *PM,
304 PM->addPass(this, AU);
307 void BasicBlockPass::addToPassManager(BasicBlockPassManager *PM,
309 PM->addPass(this, AU);
313 //===----------------------------------------------------------------------===//
314 // Pass Registration mechanism
316 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
317 static std::vector<PassRegistrationListener*> *Listeners = 0;
319 // getPassInfo - Return the PassInfo data structure that corresponds to this
321 const PassInfo *Pass::getPassInfo() const {
322 if (PassInfoCache) return PassInfoCache;
323 return lookupPassInfo(typeid(*this));
326 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
327 if (PassInfoMap == 0) return 0;
328 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
329 return (I != PassInfoMap->end()) ? I->second : 0;
332 void RegisterPassBase::registerPass() {
333 if (PassInfoMap == 0)
334 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
336 assert(PassInfoMap->find(PIObj.getTypeInfo()) == PassInfoMap->end() &&
337 "Pass already registered!");
338 PassInfoMap->insert(std::make_pair(TypeInfo(PIObj.getTypeInfo()), &PIObj));
340 // Notify any listeners...
342 for (std::vector<PassRegistrationListener*>::iterator
343 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
344 (*I)->passRegistered(&PIObj);
347 void RegisterPassBase::unregisterPass() {
348 assert(PassInfoMap && "Pass registered but not in map!");
349 std::map<TypeInfo, PassInfo*>::iterator I =
350 PassInfoMap->find(PIObj.getTypeInfo());
351 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
353 // Remove pass from the map...
354 PassInfoMap->erase(I);
355 if (PassInfoMap->empty()) {
360 // Notify any listeners...
362 for (std::vector<PassRegistrationListener*>::iterator
363 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
364 (*I)->passUnregistered(&PIObj);
367 //===----------------------------------------------------------------------===//
368 // Analysis Group Implementation Code
369 //===----------------------------------------------------------------------===//
371 struct AnalysisGroupInfo {
372 const PassInfo *DefaultImpl;
373 std::set<const PassInfo *> Implementations;
374 AnalysisGroupInfo() : DefaultImpl(0) {}
377 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
379 // RegisterAGBase implementation
381 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
382 const std::type_info *Pass, bool isDefault)
383 : RegisterPassBase(Interface, PassInfo::AnalysisGroup),
384 ImplementationInfo(0), isDefaultImplementation(isDefault) {
386 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
387 if (InterfaceInfo == 0) {
388 // First reference to Interface, register it now.
390 InterfaceInfo = &PIObj;
392 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
393 "Trying to join an analysis group that is a normal pass!");
396 ImplementationInfo = Pass::lookupPassInfo(*Pass);
397 assert(ImplementationInfo &&
398 "Must register pass before adding to AnalysisGroup!");
400 // Make sure we keep track of the fact that the implementation implements
402 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
403 IIPI->addInterfaceImplemented(InterfaceInfo);
405 // Lazily allocate to avoid nasty initialization order dependencies
406 if (AnalysisGroupInfoMap == 0)
407 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
409 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
410 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
411 "Cannot add a pass to the same analysis group more than once!");
412 AGI.Implementations.insert(ImplementationInfo);
414 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
415 "Default implementation for analysis group already specified!");
416 assert(ImplementationInfo->getNormalCtor() &&
417 "Cannot specify pass as default if it does not have a default ctor");
418 AGI.DefaultImpl = ImplementationInfo;
419 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
424 void RegisterAGBase::setGroupName(const char *Name) {
425 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
426 InterfaceInfo->setPassName(Name);
429 RegisterAGBase::~RegisterAGBase() {
430 if (ImplementationInfo) {
431 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
432 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
434 assert(AGI.Implementations.count(ImplementationInfo) &&
435 "Pass not a member of analysis group?");
437 if (AGI.DefaultImpl == ImplementationInfo)
440 AGI.Implementations.erase(ImplementationInfo);
442 // Last member of this analysis group? Unregister PassInfo, delete map entry
443 if (AGI.Implementations.empty()) {
444 assert(AGI.DefaultImpl == 0 &&
445 "Default implementation didn't unregister?");
446 AnalysisGroupInfoMap->erase(InterfaceInfo);
447 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
448 delete AnalysisGroupInfoMap;
449 AnalysisGroupInfoMap = 0;
454 if (InterfaceInfo == &PIObj)
459 //===----------------------------------------------------------------------===//
460 // PassRegistrationListener implementation
463 // PassRegistrationListener ctor - Add the current object to the list of
464 // PassRegistrationListeners...
465 PassRegistrationListener::PassRegistrationListener() {
466 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
467 Listeners->push_back(this);
470 // dtor - Remove object from list of listeners...
471 PassRegistrationListener::~PassRegistrationListener() {
472 std::vector<PassRegistrationListener*>::iterator I =
473 std::find(Listeners->begin(), Listeners->end(), this);
474 assert(Listeners && I != Listeners->end() &&
475 "PassRegistrationListener not registered!");
478 if (Listeners->empty()) {
484 // enumeratePasses - Iterate over the registered passes, calling the
485 // passEnumerate callback on each PassInfo object.
487 void PassRegistrationListener::enumeratePasses() {
489 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
490 E = PassInfoMap->end(); I != E; ++I)
491 passEnumerate(I->second);