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/TypeInfo.h"
15 #include <sys/resource.h>
16 #include <sys/unistd.h>
19 // IncludeFile - Stub function used to help linking out.
20 IncludeFile::IncludeFile(void*) {}
22 //===----------------------------------------------------------------------===//
23 // AnalysisID Class Implementation
26 static std::vector<const PassInfo*> CFGOnlyAnalyses;
28 void RegisterPassBase::setPreservesCFG() {
29 CFGOnlyAnalyses.push_back(PIObj);
32 //===----------------------------------------------------------------------===//
33 // AnalysisResolver Class Implementation
36 void AnalysisResolver::setAnalysisResolver(Pass *P, AnalysisResolver *AR) {
37 assert(P->Resolver == 0 && "Pass already in a PassManager!");
41 //===----------------------------------------------------------------------===//
42 // AnalysisUsage Class Implementation
45 // preservesCFG - This function should be called to by the pass, iff they do
48 // 1. Add or remove basic blocks from the function
49 // 2. Modify terminator instructions in any way.
51 // This function annotates the AnalysisUsage info object to say that analyses
52 // that only depend on the CFG are preserved by this pass.
54 void AnalysisUsage::preservesCFG() {
55 // Since this transformation doesn't modify the CFG, it preserves all analyses
56 // that only depend on the CFG (like dominators, loop info, etc...)
58 Preserved.insert(Preserved.end(),
59 CFGOnlyAnalyses.begin(), CFGOnlyAnalyses.end());
63 //===----------------------------------------------------------------------===//
64 // PassManager implementation - The PassManager class is a simple Pimpl class
65 // that wraps the PassManagerT template.
67 PassManager::PassManager() : PM(new PassManagerT<Module>()) {}
68 PassManager::~PassManager() { delete PM; }
69 void PassManager::add(Pass *P) { PM->add(P); }
70 bool PassManager::run(Module &M) { return PM->run(M); }
73 //===----------------------------------------------------------------------===//
74 // TimingInfo Class - This class is used to calculate information about the
75 // amount of time each pass takes to execute. This only happens with
76 // -time-passes is enabled on the command line.
79 EnableTiming("time-passes",
80 cl::desc("Time each pass, printing elapsed time for each on exit"));
82 static TimeRecord getTimeRecord() {
83 static unsigned long PageSize = 0;
87 PageSize = sysconf(_SC_PAGE_SIZE);
90 PageSize = sysconf(_SC_PAGESIZE);
92 PageSize = getpagesize();
100 if (getrusage(RUSAGE_SELF, &RU)) {
101 perror("getrusage call failed: -time-passes info incorrect!");
105 Result.Elapsed = T.tv_sec + T.tv_usec/1000000.0;
106 Result.UserTime = RU.ru_utime.tv_sec + RU.ru_utime.tv_usec/1000000.0;
107 Result.SystemTime = RU.ru_stime.tv_sec + RU.ru_stime.tv_usec/1000000.0;
108 Result.MaxRSS = RU.ru_maxrss*PageSize;
113 bool TimeRecord::operator<(const TimeRecord &TR) const {
114 // Primary sort key is User+System time
115 if (UserTime+SystemTime < TR.UserTime+TR.SystemTime)
117 if (UserTime+SystemTime > TR.UserTime+TR.SystemTime)
120 // Secondary sort key is Wall Time
121 return Elapsed < TR.Elapsed;
124 void TimeRecord::passStart(const TimeRecord &T) {
125 Elapsed -= T.Elapsed;
126 UserTime -= T.UserTime;
127 SystemTime -= T.SystemTime;
131 void TimeRecord::passEnd(const TimeRecord &T) {
132 Elapsed += T.Elapsed;
133 UserTime += T.UserTime;
134 SystemTime += T.SystemTime;
135 RSSTemp = T.MaxRSS - RSSTemp;
136 MaxRSS = std::max(MaxRSS, RSSTemp);
139 static void printVal(double Val, double Total) {
140 if (Total < 1e-7) // Avoid dividing by zero...
141 fprintf(stderr, " ----- ");
143 fprintf(stderr, " %7.4f (%5.1f%%)", Val, Val*100/Total);
146 void TimeRecord::print(const char *PassName, const TimeRecord &Total) const {
147 printVal(UserTime, Total.UserTime);
148 printVal(SystemTime, Total.SystemTime);
149 printVal(UserTime+SystemTime, Total.UserTime+Total.SystemTime);
150 printVal(Elapsed, Total.Elapsed);
152 fprintf(stderr, " ");
155 std::cerr << MaxRSS << "\t";
156 std::cerr << PassName << "\n";
160 // Create method. If Timing is enabled, this creates and returns a new timing
161 // object, otherwise it returns null.
163 TimingInfo *TimingInfo::create() {
164 return EnableTiming ? new TimingInfo() : 0;
167 void TimingInfo::passStarted(Pass *P) {
168 TimingData[P].passStart(getTimeRecord());
170 void TimingInfo::passEnded(Pass *P) {
171 TimingData[P].passEnd(getTimeRecord());
173 void TimeRecord::sum(const TimeRecord &TR) {
174 Elapsed += TR.Elapsed;
175 UserTime += TR.UserTime;
176 SystemTime += TR.SystemTime;
180 // TimingDtor - Print out information about timing information
181 TimingInfo::~TimingInfo() {
182 // Iterate over all of the data, converting it into the dual of the data map,
183 // so that the data is sorted by amount of time taken, instead of pointer.
185 std::vector<std::pair<TimeRecord, Pass*> > Data;
187 for (std::map<Pass*, TimeRecord>::iterator I = TimingData.begin(),
188 E = TimingData.end(); I != E; ++I)
189 // Throw out results for "grouping" pass managers...
190 if (!dynamic_cast<AnalysisResolver*>(I->first)) {
191 Data.push_back(std::make_pair(I->second, I->first));
192 Total.sum(I->second);
195 // Sort the data by time as the primary key, in reverse order...
196 std::sort(Data.begin(), Data.end(),
197 std::greater<std::pair<TimeRecord, Pass*> >());
199 // Print out timing header...
200 std::cerr << std::string(79, '=') << "\n"
201 << " ... Pass execution timing report ...\n"
202 << std::string(79, '=') << "\n Total Execution Time: "
203 << (Total.UserTime+Total.SystemTime) << " seconds ("
204 << Total.Elapsed << " wall clock)\n\n ---User Time--- "
205 << "--System Time-- --User+System-- ---Wall Time---";
208 std::cerr << " ---Mem---";
209 std::cerr << " --- Pass Name ---\n";
211 // Loop through all of the timing data, printing it out...
212 for (unsigned i = 0, e = Data.size(); i != e; ++i)
213 Data[i].first.print(Data[i].second->getPassName(), Total);
215 Total.print("TOTAL", Total);
219 void PMDebug::PrintArgumentInformation(const Pass *P) {
220 // Print out passes in pass manager...
221 if (const AnalysisResolver *PM = dynamic_cast<const AnalysisResolver*>(P)) {
222 for (unsigned i = 0, e = PM->getNumContainedPasses(); i != e; ++i)
223 PrintArgumentInformation(PM->getContainedPass(i));
225 } else { // Normal pass. Print argument information...
226 // Print out arguments for registered passes that are _optimizations_
227 if (const PassInfo *PI = P->getPassInfo())
228 if (PI->getPassType() & PassInfo::Optimization)
229 std::cerr << " -" << PI->getPassArgument();
233 void PMDebug::PrintPassInformation(unsigned Depth, const char *Action,
234 Pass *P, Annotable *V) {
235 if (PassDebugging >= Executions) {
236 std::cerr << (void*)P << std::string(Depth*2+1, ' ') << Action << " '"
239 std::cerr << "' on ";
241 if (dynamic_cast<Module*>(V)) {
242 std::cerr << "Module\n"; return;
243 } else if (Function *F = dynamic_cast<Function*>(V))
244 std::cerr << "Function '" << F->getName();
245 else if (BasicBlock *BB = dynamic_cast<BasicBlock*>(V))
246 std::cerr << "BasicBlock '" << BB->getName();
247 else if (Value *Val = dynamic_cast<Value*>(V))
248 std::cerr << typeid(*Val).name() << " '" << Val->getName();
250 std::cerr << "'...\n";
254 void PMDebug::PrintAnalysisSetInfo(unsigned Depth, const char *Msg,
255 Pass *P, const std::vector<AnalysisID> &Set){
256 if (PassDebugging >= Details && !Set.empty()) {
257 std::cerr << (void*)P << std::string(Depth*2+3, ' ') << Msg << " Analyses:";
258 for (unsigned i = 0; i != Set.size(); ++i)
259 std::cerr << " " << Set[i]->getPassName();
264 //===----------------------------------------------------------------------===//
265 // Pass Implementation
268 void Pass::addToPassManager(PassManagerT<Module> *PM, AnalysisUsage &AU) {
269 PM->addPass(this, AU);
272 // dumpPassStructure - Implement the -debug-passes=Structure option
273 void Pass::dumpPassStructure(unsigned Offset) {
274 std::cerr << std::string(Offset*2, ' ') << getPassName() << "\n";
277 // getPassName - Use C++ RTTI to get a SOMEWHAT intelligable name for the pass.
279 const char *Pass::getPassName() const {
280 if (const PassInfo *PI = getPassInfo())
281 return PI->getPassName();
282 return typeid(*this).name();
285 // print - Print out the internal state of the pass. This is called by Analyse
286 // to print out the contents of an analysis. Otherwise it is not neccesary to
287 // implement this method.
289 void Pass::print(std::ostream &O) const {
290 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
293 // dump - call print(std::cerr);
294 void Pass::dump() const {
298 //===----------------------------------------------------------------------===//
299 // FunctionPass Implementation
302 // run - On a module, we run this pass by initializing, runOnFunction'ing once
303 // for every function in the module, then by finalizing.
305 bool FunctionPass::run(Module &M) {
306 bool Changed = doInitialization(M);
308 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
309 if (!I->isExternal()) // Passes are not run on external functions!
310 Changed |= runOnFunction(*I);
312 return Changed | doFinalization(M);
315 // run - On a function, we simply initialize, run the function, then finalize.
317 bool FunctionPass::run(Function &F) {
318 if (F.isExternal()) return false;// Passes are not run on external functions!
320 return doInitialization(*F.getParent()) | runOnFunction(F)
321 | doFinalization(*F.getParent());
324 void FunctionPass::addToPassManager(PassManagerT<Module> *PM,
326 PM->addPass(this, AU);
329 void FunctionPass::addToPassManager(PassManagerT<Function> *PM,
331 PM->addPass(this, AU);
334 //===----------------------------------------------------------------------===//
335 // BasicBlockPass Implementation
338 // To run this pass on a function, we simply call runOnBasicBlock once for each
341 bool BasicBlockPass::runOnFunction(Function &F) {
342 bool Changed = false;
343 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
344 Changed |= runOnBasicBlock(*I);
348 // To run directly on the basic block, we initialize, runOnBasicBlock, then
351 bool BasicBlockPass::run(BasicBlock &BB) {
352 Module &M = *BB.getParent()->getParent();
353 return doInitialization(M) | runOnBasicBlock(BB) | doFinalization(M);
356 void BasicBlockPass::addToPassManager(PassManagerT<Function> *PM,
358 PM->addPass(this, AU);
361 void BasicBlockPass::addToPassManager(PassManagerT<BasicBlock> *PM,
363 PM->addPass(this, AU);
367 //===----------------------------------------------------------------------===//
368 // Pass Registration mechanism
370 static std::map<TypeInfo, PassInfo*> *PassInfoMap = 0;
371 static std::vector<PassRegistrationListener*> *Listeners = 0;
373 // getPassInfo - Return the PassInfo data structure that corresponds to this
375 const PassInfo *Pass::getPassInfo() const {
376 if (PassInfoCache) return PassInfoCache;
377 return lookupPassInfo(typeid(*this));
380 const PassInfo *Pass::lookupPassInfo(const std::type_info &TI) {
381 if (PassInfoMap == 0) return 0;
382 std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->find(TI);
383 return (I != PassInfoMap->end()) ? I->second : 0;
386 void RegisterPassBase::registerPass(PassInfo *PI) {
387 if (PassInfoMap == 0)
388 PassInfoMap = new std::map<TypeInfo, PassInfo*>();
390 assert(PassInfoMap->find(PI->getTypeInfo()) == PassInfoMap->end() &&
391 "Pass already registered!");
393 PassInfoMap->insert(std::make_pair(TypeInfo(PI->getTypeInfo()), PI));
395 // Notify any listeners...
397 for (std::vector<PassRegistrationListener*>::iterator
398 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
399 (*I)->passRegistered(PI);
402 void RegisterPassBase::unregisterPass(PassInfo *PI) {
403 assert(PassInfoMap && "Pass registered but not in map!");
404 std::map<TypeInfo, PassInfo*>::iterator I =
405 PassInfoMap->find(PI->getTypeInfo());
406 assert(I != PassInfoMap->end() && "Pass registered but not in map!");
408 // Remove pass from the map...
409 PassInfoMap->erase(I);
410 if (PassInfoMap->empty()) {
415 // Notify any listeners...
417 for (std::vector<PassRegistrationListener*>::iterator
418 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
419 (*I)->passUnregistered(PI);
421 // Delete the PassInfo object itself...
425 //===----------------------------------------------------------------------===//
426 // Analysis Group Implementation Code
427 //===----------------------------------------------------------------------===//
429 struct AnalysisGroupInfo {
430 const PassInfo *DefaultImpl;
431 std::set<const PassInfo *> Implementations;
432 AnalysisGroupInfo() : DefaultImpl(0) {}
435 static std::map<const PassInfo *, AnalysisGroupInfo> *AnalysisGroupInfoMap = 0;
437 // RegisterAGBase implementation
439 RegisterAGBase::RegisterAGBase(const std::type_info &Interface,
440 const std::type_info *Pass, bool isDefault)
441 : ImplementationInfo(0), isDefaultImplementation(isDefault) {
443 InterfaceInfo = const_cast<PassInfo*>(Pass::lookupPassInfo(Interface));
444 if (InterfaceInfo == 0) { // First reference to Interface, add it now.
445 InterfaceInfo = // Create the new PassInfo for the interface...
446 new PassInfo("", "", Interface, PassInfo::AnalysisGroup, 0, 0);
447 registerPass(InterfaceInfo);
450 assert(InterfaceInfo->getPassType() == PassInfo::AnalysisGroup &&
451 "Trying to join an analysis group that is a normal pass!");
454 ImplementationInfo = Pass::lookupPassInfo(*Pass);
455 assert(ImplementationInfo &&
456 "Must register pass before adding to AnalysisGroup!");
458 // Lazily allocate to avoid nasty initialization order dependencies
459 if (AnalysisGroupInfoMap == 0)
460 AnalysisGroupInfoMap = new std::map<const PassInfo *,AnalysisGroupInfo>();
462 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
463 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
464 "Cannot add a pass to the same analysis group more than once!");
465 AGI.Implementations.insert(ImplementationInfo);
467 assert(AGI.DefaultImpl == 0 && InterfaceInfo->getNormalCtor() == 0 &&
468 "Default implementation for analysis group already specified!");
469 assert(ImplementationInfo->getNormalCtor() &&
470 "Cannot specify pass as default if it does not have a default ctor");
471 AGI.DefaultImpl = ImplementationInfo;
472 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
477 void RegisterAGBase::setGroupName(const char *Name) {
478 assert(InterfaceInfo->getPassName()[0] == 0 && "Interface Name already set!");
479 InterfaceInfo->setPassName(Name);
482 RegisterAGBase::~RegisterAGBase() {
483 if (ImplementationInfo) {
484 assert(AnalysisGroupInfoMap && "Inserted into map, but map doesn't exist?");
485 AnalysisGroupInfo &AGI = (*AnalysisGroupInfoMap)[InterfaceInfo];
487 assert(AGI.Implementations.count(ImplementationInfo) &&
488 "Pass not a member of analysis group?");
490 if (AGI.DefaultImpl == ImplementationInfo)
493 AGI.Implementations.erase(ImplementationInfo);
495 // Last member of this analysis group? Unregister PassInfo, delete map entry
496 if (AGI.Implementations.empty()) {
497 assert(AGI.DefaultImpl == 0 &&
498 "Default implementation didn't unregister?");
499 AnalysisGroupInfoMap->erase(InterfaceInfo);
500 if (AnalysisGroupInfoMap->empty()) { // Delete map if empty
501 delete AnalysisGroupInfoMap;
502 AnalysisGroupInfoMap = 0;
505 unregisterPass(InterfaceInfo);
511 // findAnalysisGroupMember - Return an iterator pointing to one of the elements
512 // of Map if there is a pass in Map that is a member of the analysis group for
513 // the specified AnalysisGroupID.
515 static std::map<const PassInfo*, Pass*>::const_iterator
516 findAnalysisGroupMember(const PassInfo *AnalysisGroupID,
517 const std::map<const PassInfo*, Pass*> &Map) {
518 assert(AnalysisGroupID->getPassType() == PassInfo::AnalysisGroup &&
519 "AnalysisGroupID is not an analysis group!");
520 assert(AnalysisGroupInfoMap && AnalysisGroupInfoMap->count(AnalysisGroupID) &&
521 "Analysis Group does not have any registered members!");
523 // Get the set of all known implementations of this analysis group...
524 std::set<const PassInfo *> &Impls =
525 (*AnalysisGroupInfoMap)[AnalysisGroupID].Implementations;
527 // Scan over available passes, checking to see if any is a valid analysis
528 for (std::map<const PassInfo*, Pass*>::const_iterator I = Map.begin(),
529 E = Map.end(); I != E; ++I)
530 if (Impls.count(I->first)) // This is a valid analysis, return it.
533 return Map.end(); // Nothing of use found.
539 //===----------------------------------------------------------------------===//
540 // PassRegistrationListener implementation
543 // PassRegistrationListener ctor - Add the current object to the list of
544 // PassRegistrationListeners...
545 PassRegistrationListener::PassRegistrationListener() {
546 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
547 Listeners->push_back(this);
550 // dtor - Remove object from list of listeners...
551 PassRegistrationListener::~PassRegistrationListener() {
552 std::vector<PassRegistrationListener*>::iterator I =
553 std::find(Listeners->begin(), Listeners->end(), this);
554 assert(Listeners && I != Listeners->end() &&
555 "PassRegistrationListener not registered!");
558 if (Listeners->empty()) {
564 // enumeratePasses - Iterate over the registered passes, calling the
565 // passEnumerate callback on each PassInfo object.
567 void PassRegistrationListener::enumeratePasses() {
569 for (std::map<TypeInfo, PassInfo*>::iterator I = PassInfoMap->begin(),
570 E = PassInfoMap->end(); I != E; ++I)
571 passEnumerate(I->second);