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 "Support/STLExtras.h"
21 #include "Support/TypeInfo.h"
24 // IncludeFile - Stub function used to help linking out.
25 IncludeFile::IncludeFile(void*) {}
27 //===----------------------------------------------------------------------===//
28 // AnalysisID Class Implementation
31 // getCFGOnlyAnalyses - A wrapper around the CFGOnlyAnalyses which make it
32 // initializer order independent.
33 static std::vector<const PassInfo*> &getCFGOnlyAnalyses() {
34 static std::vector<const PassInfo*> CFGOnlyAnalyses;
35 return CFGOnlyAnalyses;
38 void RegisterPassBase::setOnlyUsesCFG() {
39 getCFGOnlyAnalyses().push_back(PIObj);
42 //===----------------------------------------------------------------------===//
43 // AnalysisResolver Class Implementation
46 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
47 assert(P->Resolver == 0 && "Pass already in a PassManager!");
51 //===----------------------------------------------------------------------===//
52 // AnalysisUsage Class Implementation
55 // setPreservesCFG - This function should be called to by the pass, iff they do
58 // 1. Add or remove basic blocks from the function
59 // 2. Modify terminator instructions in any way.
61 // This function annotates the AnalysisUsage info object to say that analyses
62 // that only depend on the CFG are preserved by this pass.
64 void AnalysisUsage::setPreservesCFG() {
65 // Since this transformation doesn't modify the CFG, it preserves all analyses
66 // that only depend on the CFG (like dominators, loop info, etc...)
68 Preserved.insert(Preserved.end(),
69 getCFGOnlyAnalyses().begin(), getCFGOnlyAnalyses().end());
73 //===----------------------------------------------------------------------===//
74 // PassManager implementation - The PassManager class is a simple Pimpl class
75 // that wraps the PassManagerT template.
77 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
78 PassManager::~PassManager() { delete PM; }
79 void PassManager::add(Pass *P) { PM->add(P); }
80 bool PassManager::run(Module &M) { return PM->run(M); }
82 //===----------------------------------------------------------------------===//
83 // FunctionPassManager implementation - The FunctionPassManager class
84 // is a simple Pimpl class that wraps the PassManagerT template. It
85 // is like PassManager, but only deals in FunctionPasses.
87 FunctionPassManager::FunctionPassManager(ModuleProvider *P) :
88 PM(new PassManagerT<Function>()), MP(P) {}
89 FunctionPassManager::~FunctionPassManager() { delete PM; }
90 void FunctionPassManager::add(FunctionPass *P) { PM->add(P); }
91 void FunctionPassManager::add(ImmutablePass *IP) { PM->add(IP); }
92 bool FunctionPassManager::run(Function &F) {
93 Function *mF = MP->getModule()->getNamedFunction(F.getName());
94 assert((&F == mF) && "ModuleProvider does not contain this function!");
95 MP->materializeFunction(&F);
100 //===----------------------------------------------------------------------===//
101 // TimingInfo Class - This class is used to calculate information about the
102 // amount of time each pass takes to execute. This only happens with
103 // -time-passes is enabled on the command line.
106 EnableTiming("time-passes",
107 cl::desc("Time each pass, printing elapsed time for each on exit"));
109 // createTheTimeInfo - This method either initializes the TheTimeInfo pointer to
110 // a non null value (if the -time-passes option is enabled) or it leaves it
111 // null. It may be called multiple times.
112 void TimingInfo::createTheTimeInfo() {
113 if (!EnableTiming || TheTimeInfo) return;
115 // Constructed the first time this is called, iff -time-passes is enabled.
116 // This guarantees that the object will be constructed before static globals,
117 // thus it will be destroyed before them.
118 static TimingInfo TTI;
122 void PMDebug::PrintArgumentInformation(const Pass *P) {
123 // Print out passes in pass manager...
124 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
125 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
126 PrintArgumentInformation(PM->getContainedPass(i));
128 } else { // Normal pass. Print argument information...
129 // Print out arguments for registered passes that are _optimizations_
130 if (const PassInfo *PI = P->getPassInfo())
131 if (PI->getPassType() & PassInfo::Optimization)
132 std::cerr << " -" << PI->getPassArgument();
136 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
137 Pass *P, Annotable *V) {
138 if (PassDebugging >= Executions) {
139 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
142 std::cerr << "' on ";
144 if (dynamic_cast<Module*>(V)) {
145 std::cerr << "Module\n"; return;
146 } else if (Function *F = dynamic_cast<Function*>(V))
147 std::cerr << "Function '" << F->getName();
148 else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
149 std::cerr << "BasicBlock '" << BB->getName();
150 else if (Value *Val = dynamic_cast<Value*>(V))
151 std::cerr << typeid(*Val).name() << " '" << Val->getName();
153 std::cerr << "'...\n";
157 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
158 Pass *P, const std::vector<AnalysisID> &Set){
159 if (PassDebugging >= Details && !Set.empty()) {
160 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
161 for (unsigned i = 0; i != Set.size(); ++i) {
162 if (i) std::cerr << ",";
163 std::cerr << " " << Set[i]->getPassName();
169 //===----------------------------------------------------------------------===//
170 // Pass Implementation
173 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
174 PM->addPass(this, AU);
177 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
178 return Resolver->getAnalysisToUpdate(AnalysisID) != 0;
181 // dumpPassStructure - Implement the -debug-passes=Structure option
182 void Pass::dumpPassStructure(unsigned Offset) {
183 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
186 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
188 const char *Pass::getPassName() const {
189 if (const PassInfo *PI = getPassInfo())
190 return PI->getPassName();
191 return typeid(*this).name();
194 // print - Print out the internal state of the pass. This is called by Analyze
195 // to print out the contents of an analysis. Otherwise it is not necessary to
196 // implement this method.
198 void Pass::print(std::ostream &O) const {
199 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
202 // dump - call print(std::cerr);
203 void Pass::dump() const {
207 //===----------------------------------------------------------------------===//
208 // ImmutablePass Implementation
210 void ImmutablePass::addToPassManager(PassManagerT<Module> *PM,
212 PM->addPass(this, AU);
216 //===----------------------------------------------------------------------===//
217 // FunctionPass Implementation
220 // run - On a module, we run this pass by initializing, runOnFunction'ing once
221 // for every function in the module, then by finalizing.
223 bool FunctionPass::run(Module &M) {
224 bool Changed = doInitialization(M);
226 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
227 if (!I->isExternal()) // Passes are not run on external functions!
228 Changed |= runOnFunction(*I);
230 return Changed | doFinalization(M);
233 // run - On a function, we simply initialize, run the function, then finalize.
235 bool FunctionPass::run(Function &F) {
236 if (F.isExternal()) return false;// Passes are not run on external functions!
238 return doInitialization(*F.getParent()) | runOnFunction(F)
239 | doFinalization(*F.getParent());
242 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
244 PM->addPass(this, AU);
247 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
249 PM->addPass(this, AU);
252 //===----------------------------------------------------------------------===//
253 // BasicBlockPass Implementation
256 // To run this pass on a function, we simply call runOnBasicBlock once for each
259 bool BasicBlockPass::runOnFunction(Function &F) {
260 bool Changed = doInitialization(F);
261 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
262 Changed |= runOnBasicBlock(*I);
263 return Changed | doFinalization(F);
266 // To run directly on the basic block, we initialize, runOnBasicBlock, then
269 bool BasicBlockPass::run(BasicBlock &BB) {
270 Function &F = *BB.getParent();
271 Module &M = *F.getParent();
272 return doInitialization(M) | doInitialization(F) | runOnBasicBlock(BB) |
273 doFinalization(F) | doFinalization(M);
276 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
278 PM->addPass(this, AU);
281 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
283 PM->addPass(this, AU);
287 //===----------------------------------------------------------------------===//
288 // Pass Registration mechanism
290 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
291 static std::vector<PassRegistrationListener*> *Listeners = 0;
293 // getPassInfo - Return the PassInfo data structure that corresponds to this
295 const PassInfo *Pass::getPassInfo() const {
296 if (PassInfoCache) return PassInfoCache;
297 return lookupPassInfo(typeid(*this));
300 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
301 if (PassInfoMap == 0) return 0;
302 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
303 return (I != PassInfoMap->end()) ? I->second : 0;
306 void RegisterPassBase::registerPass(PassInfo *PI) {
307 if (PassInfoMap == 0)
308 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
310 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
311 "Pass already registered!");
313 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
315 // Notify any listeners...
317 for (std::vector<PassRegistrationListener*>::iterator
318 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
319 (*I)->passRegistered(PI);
322 void RegisterPassBase::unregisterPass(PassInfo *PI) {
323 assert(PassInfoMap && "Pass registered but not in map!");
324 std::map<TypeInfo, PassInfo*>::iterator I =
325 PassInfoMap->find(PI->getTypeInfo());
326 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
328 // Remove pass from the map...
329 PassInfoMap->erase(I);
330 if (PassInfoMap->empty()) {
335 // Notify any listeners...
337 for (std::vector<PassRegistrationListener*>::iterator
338 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
339 (*I)->passUnregistered(PI);
341 // Delete the PassInfo object itself...
345 //===----------------------------------------------------------------------===//
346 // Analysis Group Implementation Code
347 //===----------------------------------------------------------------------===//
349 struct AnalysisGroupInfo {
350 const PassInfo *DefaultImpl;
351 std::set<const PassInfo *> Implementations;
352 AnalysisGroupInfo() : DefaultImpl(0) {}
355 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
357 // RegisterAGBase implementation
359 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
360 const std::type_info *Pass, bool isDefault)
361 : ImplementationInfo(0), isDefaultImplementation(isDefault) {
363 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
364 if (InterfaceInfo == 0) { // First reference to Interface, add it now.
365 InterfaceInfo = // Create the new PassInfo for the interface...
366 new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
367 registerPass(InterfaceInfo);
370 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
371 "Trying to join an analysis group that is a normal pass!");
374 ImplementationInfo = Pass::lookupPassInfo(*Pass);
375 assert(ImplementationInfo &&
376 "Must register pass before adding to AnalysisGroup!");
378 // Make sure we keep track of the fact that the implementation implements
380 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
381 IIPI->addInterfaceImplemented(InterfaceInfo);
383 // Lazily allocate to avoid nasty initialization order dependencies
384 if (AnalysisGroupInfoMap == 0)
385 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
387 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
388 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
389 "Cannot add a pass to the same analysis group more than once!");
390 AGI.Implementations.insert(ImplementationInfo);
392 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
393 "Default implementation for analysis group already specified!");
394 assert(ImplementationInfo->getNormalCtor() &&
395 "Cannot specify pass as default if it does not have a default ctor");
396 AGI.DefaultImpl = ImplementationInfo;
397 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
402 void RegisterAGBase::setGroupName(const char *Name) {
403 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
404 InterfaceInfo->setPassName(Name);
407 RegisterAGBase::~RegisterAGBase() {
408 if (ImplementationInfo) {
409 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
410 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
412 assert(AGI.Implementations.count(ImplementationInfo) &&
413 "Pass not a member of analysis group?");
415 if (AGI.DefaultImpl == ImplementationInfo)
418 AGI.Implementations.erase(ImplementationInfo);
420 // Last member of this analysis group? Unregister PassInfo, delete map entry
421 if (AGI.Implementations.empty()) {
422 assert(AGI.DefaultImpl == 0 &&
423 "Default implementation didn't unregister?");
424 AnalysisGroupInfoMap->erase(InterfaceInfo);
425 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
426 delete AnalysisGroupInfoMap;
427 AnalysisGroupInfoMap = 0;
430 unregisterPass(InterfaceInfo);
436 //===----------------------------------------------------------------------===//
437 // PassRegistrationListener implementation
440 // PassRegistrationListener ctor - Add the current object to the list of
441 // PassRegistrationListeners...
442 PassRegistrationListener::PassRegistrationListener() {
443 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
444 Listeners->push_back(this);
447 // dtor - Remove object from list of listeners...
448 PassRegistrationListener::~PassRegistrationListener() {
449 std::vector<PassRegistrationListener*>::iterator I =
450 std::find(Listeners->begin(), Listeners->end(), this);
451 assert(Listeners && I != Listeners->end() &&
452 "PassRegistrationListener not registered!");
455 if (Listeners->empty()) {
461 // enumeratePasses - Iterate over the registered passes, calling the
462 // passEnumerate callback on each PassInfo object.
464 void PassRegistrationListener::enumeratePasses() {
466 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
467 E = PassInfoMap->end(); I != E; ++I)
468 passEnumerate(I->second);