1 //===- Pass.cpp - LLVM Pass Infrastructure Impementation ------------------===//
3 // This file implements the LLVM Pass infrastructure. It is primarily
4 // responsible with ensuring that passes are executed and batched together
7 //===----------------------------------------------------------------------===//
9 #include "llvm/PassManager.h"
10 #include "PassManagerT.h" // PassManagerT implementation
11 #include "llvm/Module.h"
12 #include "Support/STLExtras.h"
13 #include "Support/CommandLine.h"
14 #include "Support/TypeInfo.h"
20 //===----------------------------------------------------------------------===//
21 // AnalysisID Class Implementation
24 static std::vector<AnalysisID> CFGOnlyAnalyses;
26 // Source of unique analysis ID #'s.
27 unsigned AnalysisID::NextID = 0;
29 AnalysisID::AnalysisID(const AnalysisID &AID, bool DependsOnlyOnCFG) {
30 ID = AID.ID; // Implement the copy ctor part...
31 Constructor = AID.Constructor;
33 // If this analysis only depends on the CFG of the function, add it to the CFG
36 CFGOnlyAnalyses.push_back(AID);
40 //===----------------------------------------------------------------------===//
41 // AnalysisResolver Class Implementation
44 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
45 assert(P->Resolver == 0 && "Pass already in a PassManager!");
49 //===----------------------------------------------------------------------===//
50 // AnalysisUsage Class Implementation
53 // preservesCFG - This function should be called to by the pass, iff they do
56 // 1. Add or remove basic blocks from the function
57 // 2. Modify terminator instructions in any way.
59 // This function annotates the AnalysisUsage info object to say that analyses
60 // that only depend on the CFG are preserved by this pass.
62 void AnalysisUsage::preservesCFG() {
63 // Since this transformation doesn't modify the CFG, it preserves all analyses
64 // that only depend on the CFG (like dominators, loop info, etc...)
66 Preserved.insert(Preserved.end(),
67 CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
71 //===----------------------------------------------------------------------===//
72 // PassManager implementation - The PassManager class is a simple Pimpl class
73 // that wraps the PassManagerT template.
75 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
76 PassManager::~PassManager() { delete PM; }
77 void PassManager::add(Pass *P) { PM->add(P); }
78 bool PassManager::run(Module &M) { return PM->run(M); }
81 //===----------------------------------------------------------------------===//
82 // TimingInfo Class - This class is used to calculate information about the
83 // amount of time each pass takes to execute. This only happens with
84 // -time-passes is enabled on the command line.
87 EnableTiming("time-passes",
88 cl::desc("Time each pass, printing elapsed time for each on exit"));
90 static double getTime() {
93 return T.tv_sec + T.tv_usec/1000000.0;
96 // Create method. If Timing is enabled, this creates and returns a new timing
97 // object, otherwise it returns null.
99 TimingInfo *TimingInfo::create() {
100 return EnableTiming ? new TimingInfo() : 0;
103 void TimingInfo::passStarted(Pass *P) { TimingData[P] -= getTime(); }
104 void TimingInfo::passEnded(Pass *P) { TimingData[P] += getTime(); }
106 // TimingDtor - Print out information about timing information
107 TimingInfo::~TimingInfo() {
108 // Iterate over all of the data, converting it into the dual of the data map,
109 // so that the data is sorted by amount of time taken, instead of pointer.
111 std::vector<std::pair<double, Pass*> > Data;
112 double TotalTime = 0;
113 for (std::map<Pass*, double>::iterator I = TimingData.begin(),
114 E = TimingData.end(); I != E; ++I)
115 // Throw out results for "grouping" pass managers...
116 if (!dynamic_cast<AnalysisResolver*>(I->first)) {
117 Data.push_back(std::make_pair(I->second, I->first));
118 TotalTime += I->second;
121 // Sort the data by time as the primary key, in reverse order...
122 std::sort(Data.begin(), Data.end(), std::greater<std::pair<double, Pass*> >());
124 // Print out timing header...
125 std::cerr << std::string(79, '=') << "\n"
126 << " ... Pass execution timing report ...\n"
127 << std::string(79, '=') << "\n Total Execution Time: " << TotalTime
128 << " seconds\n\n % Time: Seconds:\tPass Name:\n";
130 // Loop through all of the timing data, printing it out...
131 for (unsigned i = 0, e = Data.size(); i != e; ++i) {
132 fprintf(stderr, " %6.2f%% %fs\t%s\n", Data[i].first*100 / TotalTime,
133 Data[i].first, Data[i].second->getPassName());
135 std::cerr << " 100.00% " << TotalTime << "s\tTOTAL\n"
136 << std::string(79, '=') << "\n";
140 //===----------------------------------------------------------------------===//
141 // Pass debugging information. Often it is useful to find out what pass is
142 // running when a crash occurs in a utility. When this library is compiled with
143 // debugging on, a command line option (--debug-pass) is enabled that causes the
144 // pass name to be printed before it executes.
147 // Different debug levels that can be enabled...
148 enum PassDebugLevel {
149 None, Structure, Executions, Details
152 static cl::opt<enum PassDebugLevel>
153 PassDebugging("debug-pass", cl::Hidden,
154 cl::desc("Print PassManager debugging information"),
156 clEnumVal(None , "disable debug output"),
157 // TODO: add option to print out pass names "PassOptions"
158 clEnumVal(Structure , "print pass structure before run()"),
159 clEnumVal(Executions, "print pass name before it is executed"),
160 clEnumVal(Details , "print pass details when it is executed"),
163 void PMDebug::PrintPassStructure(Pass *P) {
164 if (PassDebugging >= Structure)
165 P->dumpPassStructure();
168 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
169 Pass *P, Annotable *V) {
170 if (PassDebugging >= Executions) {
171 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
174 std::cerr << "' on ";
176 if (dynamic_cast<Module*>(V)) {
177 std::cerr << "Module\n"; return;
178 } else if (Function *F = dynamic_cast<Function*>(V))
179 std::cerr << "Function '" << F->getName();
180 else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
181 std::cerr << "BasicBlock '" << BB->getName();
182 else if (Value *Val = dynamic_cast<Value*>(V))
183 std::cerr << typeid(*Val).name() << " '" << Val->getName();
185 std::cerr << "'...\n";
189 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
190 Pass *P, const std::vector<AnalysisID> &Set){
191 if (PassDebugging >= Details && !Set.empty()) {
192 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
193 for (unsigned i = 0; i != Set.size(); ++i) {
194 // FIXME: This can use the local pass map!
195 Pass *P = Set[i]->createPass(); // Good thing this is just debug code...
196 std::cerr << " " << P->getPassName();
203 // dumpPassStructure - Implement the -debug-passes=Structure option
204 void Pass::dumpPassStructure(unsigned Offset) {
205 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
209 //===----------------------------------------------------------------------===//
210 // Pass Implementation
213 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
214 PM->addPass(this, AU);
218 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
220 const char *Pass::getPassName() const { return typeid(*this).name(); }
222 // print - Print out the internal state of the pass. This is called by Analyse
223 // to print out the contents of an analysis. Otherwise it is not neccesary to
224 // implement this method.
226 void Pass::print(std::ostream &O) const {
227 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
230 // dump - call print(std::cerr);
231 void Pass::dump() const {
235 //===----------------------------------------------------------------------===//
236 // FunctionPass Implementation
239 // run - On a module, we run this pass by initializing, runOnFunction'ing once
240 // for every function in the module, then by finalizing.
242 bool FunctionPass::run(Module &M) {
243 bool Changed = doInitialization(M);
245 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
246 if (!I->isExternal()) // Passes are not run on external functions!
247 Changed |= runOnFunction(*I);
249 return Changed | doFinalization(M);
252 // run - On a function, we simply initialize, run the function, then finalize.
254 bool FunctionPass::run(Function &F) {
255 if (F.isExternal()) return false;// Passes are not run on external functions!
257 return doInitialization(*F.getParent()) | runOnFunction(F)
258 | doFinalization(*F.getParent());
261 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
263 PM->addPass(this, AU);
266 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
268 PM->addPass(this, AU);
271 //===----------------------------------------------------------------------===//
272 // BasicBlockPass Implementation
275 // To run this pass on a function, we simply call runOnBasicBlock once for each
278 bool BasicBlockPass::runOnFunction(Function &F) {
279 bool Changed = false;
280 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
281 Changed |= runOnBasicBlock(*I);
285 // To run directly on the basic block, we initialize, runOnBasicBlock, then
288 bool BasicBlockPass::run(BasicBlock &BB) {
289 Module &M = *BB.getParent()->getParent();
290 return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
293 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
295 PM->addPass(this, AU);
298 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
300 PM->addPass(this, AU);
304 //===----------------------------------------------------------------------===//
305 // Pass Registration mechanism
307 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
308 static std::vector<PassRegistrationListener*> *Listeners = 0;
310 // getPassInfo - Return the PassInfo data structure that corresponds to this
312 const PassInfo *Pass::getPassInfo() const {
313 assert(PassInfoMap && "PassInfoMap not constructed yet??");
314 std::map<TypeInfo, PassInfo*>::iterator I =
315 PassInfoMap->find(typeid(*this));
316 assert(I != PassInfoMap->end() && "Pass has not been registered!");
320 void RegisterPassBase::registerPass(PassInfo *PI) {
321 if (PassInfoMap == 0)
322 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
324 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
325 "Pass already registered!");
327 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
329 // Notify any listeners...
331 for (std::vector<PassRegistrationListener*>::iterator
332 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
333 (*I)->passRegistered(PI);
336 RegisterPassBase::~RegisterPassBase() {
337 assert(PassInfoMap && "Pass registered but not in map!");
338 std::map<TypeInfo, PassInfo*>::iterator I =
339 PassInfoMap->find(PIObj->getTypeInfo());
340 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
342 // Remove pass from the map...
343 PassInfoMap->erase(I);
344 if (PassInfoMap->empty()) {
349 // Notify any listeners...
351 for (std::vector<PassRegistrationListener*>::iterator
352 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
353 (*I)->passUnregistered(PIObj);
355 // Delete the PassInfo object itself...
361 //===----------------------------------------------------------------------===//
362 // PassRegistrationListener implementation
365 // PassRegistrationListener ctor - Add the current object to the list of
366 // PassRegistrationListeners...
367 PassRegistrationListener::PassRegistrationListener() {
368 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
369 Listeners->push_back(this);
372 // dtor - Remove object from list of listeners...
373 PassRegistrationListener::~PassRegistrationListener() {
374 std::vector<PassRegistrationListener*>::iterator I =
375 std::find(Listeners->begin(), Listeners->end(), this);
376 assert(Listeners && I != Listeners->end() &&
377 "PassRegistrationListener not registered!");
380 if (Listeners->empty()) {
386 // enumeratePasses - Iterate over the registered passes, calling the
387 // passEnumerate callback on each PassInfo object.
389 void PassRegistrationListener::enumeratePasses() {
391 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
392 E = PassInfoMap->end(); I != E; ++I)
393 passEnumerate(I->second);