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 // Force out-of-line virtual method.
43 // Force out-of-line virtual method.
44 ModulePass::~ModulePass() { }
46 Pass *ModulePass::createPrinterPass(raw_ostream &O,
47 const std::string &Banner) const {
48 return createPrintModulePass(&O, false, Banner);
51 PassManagerType ModulePass::getPotentialPassManagerType() const {
52 return PMT_ModulePassManager;
55 bool Pass::mustPreserveAnalysisID(const PassInfo *AnalysisID) const {
56 return Resolver->getAnalysisIfAvailable(AnalysisID, true) != 0;
59 // dumpPassStructure - Implement the -debug-passes=Structure option
60 void Pass::dumpPassStructure(unsigned Offset) {
61 dbgs().indent(Offset*2) << getPassName() << "\n";
64 /// getPassName - Return a nice clean name for a pass. This usually
65 /// implemented in terms of the name that is registered by one of the
66 /// Registration templates, but can be overloaded directly.
68 const char *Pass::getPassName() const {
69 if (const PassInfo *PI = getPassInfo())
70 return PI->getPassName();
71 return "Unnamed pass: implement Pass::getPassName()";
74 void Pass::preparePassManager(PMStack &) {
75 // By default, don't do anything.
78 PassManagerType Pass::getPotentialPassManagerType() const {
79 // Default implementation.
83 void Pass::getAnalysisUsage(AnalysisUsage &) const {
84 // By default, no analysis results are used, all are invalidated.
87 void Pass::releaseMemory() {
88 // By default, don't do anything.
91 void Pass::verifyAnalysis() const {
92 // By default, don't do anything.
95 // print - Print out the internal state of the pass. This is called by Analyze
96 // to print out the contents of an analysis. Otherwise it is not necessary to
97 // implement this method.
99 void Pass::print(raw_ostream &O,const Module*) const {
100 O << "Pass::print not implemented for pass: '" << getPassName() << "'!\n";
103 // dump - call print(cerr);
104 void Pass::dump() const {
108 //===----------------------------------------------------------------------===//
109 // ImmutablePass Implementation
111 // Force out-of-line virtual method.
112 ImmutablePass::~ImmutablePass() { }
114 void ImmutablePass::initializePass() {
115 // By default, don't do anything.
118 //===----------------------------------------------------------------------===//
119 // FunctionPass Implementation
122 Pass *FunctionPass::createPrinterPass(raw_ostream &O,
123 const std::string &Banner) const {
124 return createPrintFunctionPass(Banner, &O);
127 // run - On a module, we run this pass by initializing, runOnFunction'ing once
128 // for every function in the module, then by finalizing.
130 bool FunctionPass::runOnModule(Module &M) {
131 bool Changed = doInitialization(M);
133 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
134 if (!I->isDeclaration()) // Passes are not run on external functions!
135 Changed |= runOnFunction(*I);
137 return Changed | doFinalization(M);
140 // run - On a function, we simply initialize, run the function, then finalize.
142 bool FunctionPass::run(Function &F) {
143 // Passes are not run on external functions!
144 if (F.isDeclaration()) return false;
146 bool Changed = doInitialization(*F.getParent());
147 Changed |= runOnFunction(F);
148 return Changed | doFinalization(*F.getParent());
151 bool FunctionPass::doInitialization(Module &) {
152 // By default, don't do anything.
156 bool FunctionPass::doFinalization(Module &) {
157 // By default, don't do anything.
161 PassManagerType FunctionPass::getPotentialPassManagerType() const {
162 return PMT_FunctionPassManager;
165 //===----------------------------------------------------------------------===//
166 // BasicBlockPass Implementation
169 Pass *BasicBlockPass::createPrinterPass(raw_ostream &O,
170 const std::string &Banner) const {
172 llvm_unreachable("BasicBlockPass printing unsupported.");
176 // To run this pass on a function, we simply call runOnBasicBlock once for each
179 bool BasicBlockPass::runOnFunction(Function &F) {
180 bool Changed = doInitialization(F);
181 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
182 Changed |= runOnBasicBlock(*I);
183 return Changed | doFinalization(F);
186 bool BasicBlockPass::doInitialization(Module &) {
187 // By default, don't do anything.
191 bool BasicBlockPass::doInitialization(Function &) {
192 // By default, don't do anything.
196 bool BasicBlockPass::doFinalization(Function &) {
197 // By default, don't do anything.
201 bool BasicBlockPass::doFinalization(Module &) {
202 // By default, don't do anything.
206 PassManagerType BasicBlockPass::getPotentialPassManagerType() const {
207 return PMT_BasicBlockPassManager;
210 //===----------------------------------------------------------------------===//
211 // Pass Registration mechanism
214 class PassRegistrar {
215 /// Guards the contents of this class.
216 mutable sys::SmartMutex<true> Lock;
218 /// PassInfoMap - Keep track of the passinfo object for each registered llvm
220 typedef std::map<intptr_t, const PassInfo*> MapType;
223 typedef StringMap<const PassInfo*> StringMapType;
224 StringMapType PassInfoStringMap;
226 /// AnalysisGroupInfo - Keep track of information for each analysis group.
227 struct AnalysisGroupInfo {
228 std::set<const PassInfo *> Implementations;
231 /// AnalysisGroupInfoMap - Information for each analysis group.
232 std::map<const PassInfo *, AnalysisGroupInfo> AnalysisGroupInfoMap;
236 const PassInfo *GetPassInfo(intptr_t TI) const {
237 sys::SmartScopedLock<true> Guard(Lock);
238 MapType::const_iterator I = PassInfoMap.find(TI);
239 return I != PassInfoMap.end() ? I->second : 0;
242 const PassInfo *GetPassInfo(StringRef Arg) const {
243 sys::SmartScopedLock<true> Guard(Lock);
244 StringMapType::const_iterator I = PassInfoStringMap.find(Arg);
245 return I != PassInfoStringMap.end() ? I->second : 0;
248 void RegisterPass(const PassInfo &PI) {
249 sys::SmartScopedLock<true> Guard(Lock);
251 PassInfoMap.insert(std::make_pair(PI.getTypeInfo(),&PI)).second;
252 assert(Inserted && "Pass registered multiple times!"); Inserted=Inserted;
253 PassInfoStringMap[PI.getPassArgument()] = &PI;
256 void UnregisterPass(const PassInfo &PI) {
257 sys::SmartScopedLock<true> Guard(Lock);
258 MapType::iterator I = PassInfoMap.find(PI.getTypeInfo());
259 assert(I != PassInfoMap.end() && "Pass registered but not in map!");
261 // Remove pass from the map.
262 PassInfoMap.erase(I);
263 PassInfoStringMap.erase(PI.getPassArgument());
266 void EnumerateWith(PassRegistrationListener *L) {
267 sys::SmartScopedLock<true> Guard(Lock);
268 for (MapType::const_iterator I = PassInfoMap.begin(),
269 E = PassInfoMap.end(); I != E; ++I)
270 L->passEnumerate(I->second);
274 /// Analysis Group Mechanisms.
275 void RegisterAnalysisGroup(PassInfo *InterfaceInfo,
276 const PassInfo *ImplementationInfo,
278 sys::SmartScopedLock<true> Guard(Lock);
279 AnalysisGroupInfo &AGI = AnalysisGroupInfoMap[InterfaceInfo];
280 assert(AGI.Implementations.count(ImplementationInfo) == 0 &&
281 "Cannot add a pass to the same analysis group more than once!");
282 AGI.Implementations.insert(ImplementationInfo);
284 assert(InterfaceInfo->getNormalCtor() == 0 &&
285 "Default implementation for analysis group already specified!");
286 assert(ImplementationInfo->getNormalCtor() &&
287 "Cannot specify pass as default if it does not have a default ctor");
288 InterfaceInfo->setNormalCtor(ImplementationInfo->getNormalCtor());
294 static std::vector<PassRegistrationListener*> *Listeners = 0;
295 static sys::SmartMutex<true> ListenersLock;
297 // FIXME: This should use ManagedStatic to manage the pass registrar.
298 // Unfortunately, we can't do this, because passes are registered with static
299 // ctors, and having llvm_shutdown clear this map prevents successful
300 // ressurection after llvm_shutdown is run.
301 static PassRegistrar *getPassRegistrar() {
302 static PassRegistrar *PassRegistrarObj = 0;
304 // Use double-checked locking to safely initialize the registrar when
305 // we're running in multithreaded mode.
306 PassRegistrar* tmp = PassRegistrarObj;
307 if (llvm_is_multithreaded()) {
310 llvm_acquire_global_lock();
311 tmp = PassRegistrarObj;
313 tmp = new PassRegistrar();
315 PassRegistrarObj = tmp;
317 llvm_release_global_lock();
320 PassRegistrarObj = new PassRegistrar();
323 return PassRegistrarObj;
326 // getPassInfo - Return the PassInfo data structure that corresponds to this
328 const PassInfo *Pass::getPassInfo() const {
329 return lookupPassInfo(PassID);
332 const PassInfo *Pass::lookupPassInfo(intptr_t TI) {
333 return getPassRegistrar()->GetPassInfo(TI);
336 const PassInfo *Pass::lookupPassInfo(StringRef Arg) {
337 return getPassRegistrar()->GetPassInfo(Arg);
340 void PassInfo::registerPass() {
341 getPassRegistrar()->RegisterPass(*this);
343 // Notify any listeners.
344 sys::SmartScopedLock<true> Lock(ListenersLock);
346 for (std::vector<PassRegistrationListener*>::iterator
347 I = Listeners->begin(), E = Listeners->end(); I != E; ++I)
348 (*I)->passRegistered(this);
351 void PassInfo::unregisterPass() {
352 getPassRegistrar()->UnregisterPass(*this);
355 //===----------------------------------------------------------------------===//
356 // Analysis Group Implementation Code
357 //===----------------------------------------------------------------------===//
359 // RegisterAGBase implementation
361 RegisterAGBase::RegisterAGBase(const char *Name, intptr_t InterfaceID,
362 intptr_t PassID, bool isDefault)
363 : PassInfo(Name, InterfaceID) {
365 PassInfo *InterfaceInfo =
366 const_cast<PassInfo*>(Pass::lookupPassInfo(InterfaceID));
367 if (InterfaceInfo == 0) {
368 // First reference to Interface, register it now.
370 InterfaceInfo = this;
372 assert(isAnalysisGroup() &&
373 "Trying to join an analysis group that is a normal pass!");
376 const PassInfo *ImplementationInfo = Pass::lookupPassInfo(PassID);
377 assert(ImplementationInfo &&
378 "Must register pass before adding to AnalysisGroup!");
380 // Make sure we keep track of the fact that the implementation implements
382 PassInfo *IIPI = const_cast<PassInfo*>(ImplementationInfo);
383 IIPI->addInterfaceImplemented(InterfaceInfo);
385 getPassRegistrar()->RegisterAnalysisGroup(InterfaceInfo, IIPI, isDefault);
390 //===----------------------------------------------------------------------===//
391 // PassRegistrationListener implementation
394 // PassRegistrationListener ctor - Add the current object to the list of
395 // PassRegistrationListeners...
396 PassRegistrationListener::PassRegistrationListener() {
397 sys::SmartScopedLock<true> Lock(ListenersLock);
398 if (!Listeners) Listeners = new std::vector<PassRegistrationListener*>();
399 Listeners->push_back(this);
402 // dtor - Remove object from list of listeners...
403 PassRegistrationListener::~PassRegistrationListener() {
404 sys::SmartScopedLock<true> Lock(ListenersLock);
405 std::vector<PassRegistrationListener*>::iterator I =
406 std::find(Listeners->begin(), Listeners->end(), this);
407 assert(Listeners && I != Listeners->end() &&
408 "PassRegistrationListener not registered!");
411 if (Listeners->empty()) {
417 // enumeratePasses - Iterate over the registered passes, calling the
418 // passEnumerate callback on each PassInfo object.
420 void PassRegistrationListener::enumeratePasses() {
421 getPassRegistrar()->EnumerateWith(this);
424 PassNameParser::~PassNameParser() {}
426 //===----------------------------------------------------------------------===//
427 // AnalysisUsage Class Implementation
431 struct GetCFGOnlyPasses : public PassRegistrationListener {
432 typedef AnalysisUsage::VectorType VectorType;
433 VectorType &CFGOnlyList;
434 GetCFGOnlyPasses(VectorType &L) : CFGOnlyList(L) {}
436 void passEnumerate(const PassInfo *P) {
437 if (P->isCFGOnlyPass())
438 CFGOnlyList.push_back(P);
443 // setPreservesCFG - This function should be called to by the pass, iff they do
446 // 1. Add or remove basic blocks from the function
447 // 2. Modify terminator instructions in any way.
449 // This function annotates the AnalysisUsage info object to say that analyses
450 // that only depend on the CFG are preserved by this pass.
452 void AnalysisUsage::setPreservesCFG() {
453 // Since this transformation doesn't modify the CFG, it preserves all analyses
454 // that only depend on the CFG (like dominators, loop info, etc...)
455 GetCFGOnlyPasses(Preserved).enumeratePasses();