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 {
221 if (const PassInfo *PI = getPassInfo())
222 return PI->getPassName();
223 return typeid(*this).name();
226 // print - Print out the internal state of the pass. This is called by Analyse
227 // to print out the contents of an analysis. Otherwise it is not neccesary to
228 // implement this method.
230 void Pass::print(std::ostream &O) const {
231 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
234 // dump - call print(std::cerr);
235 void Pass::dump() const {
239 //===----------------------------------------------------------------------===//
240 // FunctionPass Implementation
243 // run - On a module, we run this pass by initializing, runOnFunction'ing once
244 // for every function in the module, then by finalizing.
246 bool FunctionPass::run(Module &M) {
247 bool Changed = doInitialization(M);
249 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
250 if (!I->isExternal()) // Passes are not run on external functions!
251 Changed |= runOnFunction(*I);
253 return Changed | doFinalization(M);
256 // run - On a function, we simply initialize, run the function, then finalize.
258 bool FunctionPass::run(Function &F) {
259 if (F.isExternal()) return false;// Passes are not run on external functions!
261 return doInitialization(*F.getParent()) | runOnFunction(F)
262 | doFinalization(*F.getParent());
265 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
267 PM->addPass(this, AU);
270 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
272 PM->addPass(this, AU);
275 //===----------------------------------------------------------------------===//
276 // BasicBlockPass Implementation
279 // To run this pass on a function, we simply call runOnBasicBlock once for each
282 bool BasicBlockPass::runOnFunction(Function &F) {
283 bool Changed = false;
284 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
285 Changed |= runOnBasicBlock(*I);
289 // To run directly on the basic block, we initialize, runOnBasicBlock, then
292 bool BasicBlockPass::run(BasicBlock &BB) {
293 Module &M = *BB.getParent()->getParent();
294 return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
297 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
299 PM->addPass(this, AU);
302 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
304 PM->addPass(this, AU);
308 //===----------------------------------------------------------------------===//
309 // Pass Registration mechanism
311 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
312 static std::vector<PassRegistrationListener*> *Listeners = 0;
314 // getPassInfo - Return the PassInfo data structure that corresponds to this
316 const PassInfo *Pass::getPassInfo() const {
317 if (PassInfoCache) return PassInfoCache;
318 if (PassInfoMap == 0) return 0;
319 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(typeid(*this));
320 return (I != PassInfoMap->end()) ? I->second : 0;
323 void RegisterPassBase::registerPass(PassInfo *PI) {
324 if (PassInfoMap == 0)
325 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
327 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
328 "Pass already registered!");
330 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
332 // Notify any listeners...
334 for (std::vector<PassRegistrationListener*>::iterator
335 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
336 (*I)->passRegistered(PI);
339 RegisterPassBase::~RegisterPassBase() {
340 assert(PassInfoMap && "Pass registered but not in map!");
341 std::map<TypeInfo, PassInfo*>::iterator I =
342 PassInfoMap->find(PIObj->getTypeInfo());
343 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
345 // Remove pass from the map...
346 PassInfoMap->erase(I);
347 if (PassInfoMap->empty()) {
352 // Notify any listeners...
354 for (std::vector<PassRegistrationListener*>::iterator
355 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
356 (*I)->passUnregistered(PIObj);
358 // Delete the PassInfo object itself...
364 //===----------------------------------------------------------------------===//
365 // PassRegistrationListener implementation
368 // PassRegistrationListener ctor - Add the current object to the list of
369 // PassRegistrationListeners...
370 PassRegistrationListener::PassRegistrationListener() {
371 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
372 Listeners->push_back(this);
375 // dtor - Remove object from list of listeners...
376 PassRegistrationListener::~PassRegistrationListener() {
377 std::vector<PassRegistrationListener*>::iterator I =
378 std::find(Listeners->begin(), Listeners->end(), this);
379 assert(Listeners && I != Listeners->end() &&
380 "PassRegistrationListener not registered!");
383 if (Listeners->empty()) {
389 // enumeratePasses - Iterate over the registered passes, calling the
390 // passEnumerate callback on each PassInfo object.
392 void PassRegistrationListener::enumeratePasses() {
394 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
395 E = PassInfoMap->end(); I != E; ++I)
396 passEnumerate(I->second);