1 //===- Pass.cpp - LLVM Pass Infrastructure Implementation -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/Pass.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Module.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/StringMap.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/PassNameParser.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/System/Atomic.h"
27 #include "llvm/System/Mutex.h"
28 #include "llvm/System/Threading.h"
34 //===----------------------------------------------------------------------===//
35 // Pass Implementation
38 Pass::Pass(PassKind K, intptr_t pid) : Resolver(0), PassID(pid), Kind(K) {
39 assert(pid && "pid cannot be 0");
42 Pass::Pass(PassKind K, const void *pid)
43 : Resolver(0), PassID((intptr_t)pid), Kind(K) {
44 assert(pid && "pid cannot be 0");
47 // Force out-of-line virtual method.
52 // Force out-of-line virtual method.
53 ModulePass::~ModulePass() { }
55 Pass *ModulePass::createPrinterPass(raw_ostream &O,
56 const std::string &Banner) const {
57 return createPrintModulePass(&O, false, Banner);
60 PassManagerType ModulePass::getPotentialPassManagerType() const {
61 return PMT_ModulePassManager;
64 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
65 return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0;
68 // dumpPassStructure - Implement the -debug-passes=Structure option
69 void Pass::dumpPassStructure(unsigned Offset) {
70 dbgs().indent(Offset*2) << getPassName() << "\n";
73 /// getPassName - Return a nice clean name for a pass. This usually
74 /// implemented in terms of the name that is registered by one of the
75 /// Registration templates, but can be overloaded directly.
77 const char *Pass::getPassName() const {
78 if (const StaticPassInfo *PI = getPassInfo())
79 return PI->getPassName();
80 return "Unnamed pass: implement Pass::getPassName()";
83 void Pass::preparePassManager(PMStack &) {
84 // By default, don't do anything.
87 PassManagerType Pass::getPotentialPassManagerType() const {
88 // Default implementation.
92 void Pass::getAnalysisUsage(AnalysisUsage &) const {
93 // By default, no analysis results are used, all are invalidated.
96 void Pass::releaseMemory() {
97 // By default, don't do anything.
100 void Pass::verifyAnalysis() const {
101 // By default, don't do anything.
104 void *Pass::getAdjustedAnalysisPointer(const StaticPassInfo *) {
108 ImmutablePass *Pass::getAsImmutablePass() {
112 PMDataManager *Pass::getAsPMDataManager() {
116 void Pass::setResolver(AnalysisResolver *AR) {
117 assert(!Resolver && "Resolver is already set");
121 // print - Print out the internal state of the pass. This is called by Analyze
122 // to print out the contents of an analysis. Otherwise it is not necessary to
123 // implement this method.
125 void Pass::print(raw_ostream &O,const Module*) const {
126 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
129 // dump - call print(cerr);
130 void Pass::dump() const {
134 //===----------------------------------------------------------------------===//
135 // ImmutablePass Implementation
137 // Force out-of-line virtual method.
138 ImmutablePass::~ImmutablePass() { }
140 void ImmutablePass::initializePass() {
141 // By default, don't do anything.
144 //===----------------------------------------------------------------------===//
145 // FunctionPass Implementation
148 Pass *FunctionPass::createPrinterPass(raw_ostream &O,
149 const std::string &Banner) const {
150 return createPrintFunctionPass(Banner, &O);
153 // run - On a module, we run this pass by initializing, runOnFunction'ing once
154 // for every function in the module, then by finalizing.
156 bool FunctionPass::runOnModule(Module &M) {
157 bool Changed = doInitialization(M);
159 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
160 if (!I->isDeclaration()) // Passes are not run on external functions!
161 Changed |= runOnFunction(*I);
163 return Changed | doFinalization(M);
166 // run - On a function, we simply initialize, run the function, then finalize.
168 bool FunctionPass::run(Function &F) {
169 // Passes are not run on external functions!
170 if (F.isDeclaration()) return false;
172 bool Changed = doInitialization(*F.getParent());
173 Changed |= runOnFunction(F);
174 return Changed | doFinalization(*F.getParent());
177 bool FunctionPass::doInitialization(Module &) {
178 // By default, don't do anything.
182 bool FunctionPass::doFinalization(Module &) {
183 // By default, don't do anything.
187 PassManagerType FunctionPass::getPotentialPassManagerType() const {
188 return PMT_FunctionPassManager;
191 //===----------------------------------------------------------------------===//
192 // BasicBlockPass Implementation
195 Pass *BasicBlockPass::createPrinterPass(raw_ostream &O,
196 const std::string &Banner) const {
198 llvm_unreachable("BasicBlockPass printing unsupported.");
202 // To run this pass on a function, we simply call runOnBasicBlock once for each
205 bool BasicBlockPass::runOnFunction(Function &F) {
206 bool Changed = doInitialization(F);
207 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
208 Changed |= runOnBasicBlock(*I);
209 return Changed | doFinalization(F);
212 bool BasicBlockPass::doInitialization(Module &) {
213 // By default, don't do anything.
217 bool BasicBlockPass::doInitialization(Function &) {
218 // By default, don't do anything.
222 bool BasicBlockPass::doFinalization(Function &) {
223 // By default, don't do anything.
227 bool BasicBlockPass::doFinalization(Module &) {
228 // By default, don't do anything.
232 PassManagerType BasicBlockPass::getPotentialPassManagerType() const {
233 return PMT_BasicBlockPassManager;
236 //===----------------------------------------------------------------------===//
237 // Pass Registration mechanism
240 class PassRegistrar {
241 /// Guards the contents of this class.
242 mutable sys::SmartMutex<true> Lock;
244 /// PassInfoMap - Keep track of the passinfo object for each registered llvm
246 typedef std::map<intptr_t, const StaticPassInfo*> MapType;
249 typedef StringMap<const StaticPassInfo*> StringMapType;
250 StringMapType PassInfoStringMap;
252 /// AnalysisGroupInfo - Keep track of information for each analysis group.
253 struct AnalysisGroupInfo {
254 std::set<const StaticPassInfo *> Implementations;
257 /// AnalysisGroupInfoMap - Information for each analysis group.
258 std::map<const StaticPassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
262 const StaticPassInfo *GetPassInfo(intptr_t TI) const {
263 sys::SmartScopedLock<true> Guard(Lock);
264 MapType::const_iterator I = PassInfoMap.find(TI);
265 return I != PassInfoMap.end() ? I->second : 0;
268 const StaticPassInfo *GetPassInfo(StringRef Arg) const {
269 sys::SmartScopedLock<true> Guard(Lock);
270 StringMapType::const_iterator I = PassInfoStringMap.find(Arg);
271 return I != PassInfoStringMap.end() ? I->second : 0;
274 void RegisterPass(const StaticPassInfo &PI) {
275 sys::SmartScopedLock<true> Guard(Lock);
277 PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
278 assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted;
279 PassInfoStringMap[PI.getPassArgument()] = &PI;
282 void UnregisterPass(const StaticPassInfo &PI) {
283 sys::SmartScopedLock<true> Guard(Lock);
284 MapType::iterator I = PassInfoMap.find(PI.getTypeInfo());
285 assert(I != PassInfoMap.end() && "Pass registered but not in map!");
287 // Remove pass from the map.
288 PassInfoMap.erase(I);
289 PassInfoStringMap.erase(PI.getPassArgument());
292 void EnumerateWith(PassRegistrationListener *L) {
293 sys::SmartScopedLock<true> Guard(Lock);
294 for (MapType::const_iterator I = PassInfoMap.begin(),
295 E = PassInfoMap.end(); I != E; ++I)
296 L->passEnumerate(I->second);
300 /// Analysis Group Mechanisms.
301 void RegisterAnalysisGroup(StaticPassInfo *InterfaceInfo,
302 const StaticPassInfo *ImplementationInfo,
304 sys::SmartScopedLock<true> Guard(Lock);
305 AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
306 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
307 "Cannot add a pass to the same analysis group more than once!");
308 AGI.Implementations.insert(ImplementationInfo);
310 assert(InterfaceInfo->getNormalCtor() == 0 &&
311 "Default implementation for analysis group already specified!");
312 assert(ImplementationInfo->getNormalCtor() &&
313 "Cannot specify pass as default if it does not have a default ctor");
314 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
320 static std::vector<PassRegistrationListener*> *Listeners = 0;
321 static sys::SmartMutex<true> ListenersLock;
323 static PassRegistrar *PassRegistrarObj = 0;
324 static PassRegistrar *getPassRegistrar() {
325 // Use double-checked locking to safely initialize the registrar when
326 // we're running in multithreaded mode.
327 PassRegistrar* tmp = PassRegistrarObj;
328 if (llvm_is_multithreaded()) {
331 llvm_acquire_global_lock();
332 tmp = PassRegistrarObj;
334 tmp = new PassRegistrar();
336 PassRegistrarObj = tmp;
338 llvm_release_global_lock();
341 PassRegistrarObj = new PassRegistrar();
344 return PassRegistrarObj;
349 // FIXME: We use ManagedCleanup to erase the pass registrar on shutdown.
350 // Unfortunately, passes are registered with static ctors, and having
351 // llvm_shutdown clear this map prevents successful ressurection after
352 // llvm_shutdown is run. Ideally we should find a solution so that we don't
353 // leak the map, AND can still resurrect after shutdown.
354 void cleanupPassRegistrar(void*) {
355 if (PassRegistrarObj) {
356 delete PassRegistrarObj;
357 PassRegistrarObj = 0;
360 ManagedCleanup<&cleanupPassRegistrar> registrarCleanup ATTRIBUTE_USED;
364 // getPassInfo - Return the PassInfo data structure that corresponds to this
366 const StaticPassInfo *Pass::getPassInfo() const {
367 return lookupPassInfo(PassID);
370 const StaticPassInfo *Pass::lookupPassInfo(intptr_t TI) {
371 return getPassRegistrar()->GetPassInfo(TI);
374 const StaticPassInfo *Pass::lookupPassInfo(StringRef Arg) {
375 return getPassRegistrar()->GetPassInfo(Arg);
378 void PassInfo::registerPass() {
379 getPassRegistrar()->RegisterPass(*this);
381 // Notify any listeners.
382 sys::SmartScopedLock<true> Lock(ListenersLock);
384 for (std::vector<PassRegistrationListener*>::iterator
385 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
386 (*I)->passRegistered(this);
389 void PassInfo::unregisterPass() {
390 getPassRegistrar()->UnregisterPass(*this);
393 Pass *StaticPassInfo::createPass() const {
394 assert((!isAnalysisGroup() || NormalCtor) &&
395 "No default implementation found for analysis group!");
397 "Cannot call createPass on PassInfo without default ctor!");
401 //===----------------------------------------------------------------------===//
402 // Analysis Group Implementation Code
403 //===----------------------------------------------------------------------===//
405 // RegisterAGBase implementation
407 RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID,
408 intptr_t PassID, bool isDefault)
409 : PassInfo(Name, InterfaceID) {
411 StaticPassInfo *InterfaceInfo =
412 const_cast<StaticPassInfo*>(Pass::lookupPassInfo(InterfaceID));
413 if (InterfaceInfo == 0) {
414 // First reference to Interface, register it now.
416 InterfaceInfo = this;
418 assert(isAnalysisGroup() &&
419 "Trying to join an analysis group that is a normal pass!");
422 const StaticPassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID);
423 assert(ImplementationInfo &&
424 "Must register pass before adding to AnalysisGroup!");
426 // Make sure we keep track of the fact that the implementation implements
428 StaticPassInfo *IIPI = const_cast<StaticPassInfo*>(ImplementationInfo);
429 IIPI->addInterfaceImplemented(InterfaceInfo);
431 getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
436 //===----------------------------------------------------------------------===//
437 // PassRegistrationListener implementation
440 // PassRegistrationListener ctor - Add the current object to the list of
441 // PassRegistrationListeners...
442 PassRegistrationListener::PassRegistrationListener() {
443 sys::SmartScopedLock<true> Lock(ListenersLock);
444 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
445 Listeners->push_back(this);
448 // dtor - Remove object from list of listeners...
449 PassRegistrationListener::~PassRegistrationListener() {
450 sys::SmartScopedLock<true> Lock(ListenersLock);
451 std::vector<PassRegistrationListener*>::iterator I =
452 std::find(Listeners->begin(), Listeners->end(), this);
453 assert(Listeners && I != Listeners->end() &&
454 "PassRegistrationListener not registered!");
457 if (Listeners->empty()) {
463 // enumeratePasses - Iterate over the registered passes, calling the
464 // passEnumerate callback on each PassInfo object.
466 void PassRegistrationListener::enumeratePasses() {
467 getPassRegistrar()->EnumerateWith(this);
470 PassNameParser::~PassNameParser() {}
472 //===----------------------------------------------------------------------===//
473 // AnalysisUsage Class Implementation
477 struct GetCFGOnlyPasses : public PassRegistrationListener {
478 typedef AnalysisUsage::VectorType VectorType;
479 VectorType &CFGOnlyList;
480 GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
482 void passEnumerate(const StaticPassInfo *P) {
483 if (P->isCFGOnlyPass())
484 CFGOnlyList.push_back(P);
489 // setPreservesCFG - This function should be called to by the pass, iff they do
492 // 1. Add or remove basic blocks from the function
493 // 2. Modify terminator instructions in any way.
495 // This function annotates the AnalysisUsage info object to say that analyses
496 // that only depend on the CFG are preserved by this pass.
498 void AnalysisUsage::setPreservesCFG() {
499 // Since this transformation doesn't modify the CFG, it preserves all analyses
500 // that only depend on the CFG (like dominators, loop info, etc...)
501 GetCFGOnlyPasses(Preserved).enumeratePasses();
504 AnalysisUsage &AnalysisUsage::addRequiredID(AnalysisID ID) {
505 assert(ID && "Pass class not registered!");
506 Required.push_back(ID);
510 AnalysisUsage &AnalysisUsage::addRequiredTransitiveID(AnalysisID ID) {
511 assert(ID && "Pass class not registered!");
512 Required.push_back(ID);
513 RequiredTransitive.push_back(ID);