1 //===- DataStructureOpt.cpp - Data Structure Analysis Based Optimizations -===//
3 // This pass uses DSA to a series of simple optimizations, like marking
4 // unwritten global variables 'constant'.
6 //===----------------------------------------------------------------------===//
8 #include "llvm/Analysis/DataStructure.h"
9 #include "llvm/Analysis/DSGraph.h"
10 #include "llvm/Module.h"
11 #include "llvm/Constant.h"
12 #include "Support/Statistic.h"
16 NumGlobalsConstanted("ds-opt", "Number of globals marked constant");
18 NumGlobalsIsolated("ds-opt", "Number of globals with references dropped");
20 class DSOpt : public Pass {
24 TD = &getAnalysis<TDDataStructures>();
25 bool Changed = OptimizeGlobals(M);
29 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
30 AU.addRequired<TDDataStructures>(); // Uses TD Datastructures
31 AU.addPreserved<LocalDataStructures>(); // Preserves local...
32 AU.addPreserved<TDDataStructures>(); // Preserves bu...
33 AU.addPreserved<BUDataStructures>(); // Preserves td...
37 bool OptimizeGlobals(Module &M);
40 RegisterOpt<DSOpt> X("ds-opt", "DSA-based simple optimizations");
44 /// OptimizeGlobals - This method uses information taken from DSA to optimize
47 bool DSOpt::OptimizeGlobals(Module &M) {
48 DSGraph &GG = TD->getGlobalsGraph();
49 const DSGraph::ScalarMapTy &SM = GG.getScalarMap();
52 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
53 if (!I->isExternal()) { // Loop over all of the non-external globals...
54 // Look up the node corresponding to this global, if it exists.
56 DSGraph::ScalarMapTy::const_iterator SMI = SM.find(I);
57 if (SMI != SM.end()) GNode = SMI->second.getNode();
59 if (GNode == 0 && I->hasInternalLinkage()) {
60 // If there is no entry in the scalar map for this global, it was never
61 // referenced in the program. If it has internal linkage, that means we
62 // can delete it. We don't ACTUALLY want to delete the global, just
63 // remove anything that references the global: later passes will take
65 if (!I->use_empty()) {
66 I->replaceAllUsesWith(Constant::getNullValue((Type*)I->getType()));
69 } else if (GNode && GNode->isComplete()) {
71 // If the node has not been read or written, and it is not externally
72 // visible, kill any references to it so it can be DCE'd.
73 if (!GNode->isModified() && !GNode->isRead() &&I->hasInternalLinkage()){
74 if (!I->use_empty()) {
75 I->replaceAllUsesWith(Constant::getNullValue((Type*)I->getType()));
80 // We expect that there will almost always be a node for this global.
81 // If there is, and the node doesn't have the M bit set, we can set the
82 // 'constant' bit on the global.
83 if (!GNode->isModified() && !I->isConstant()) {
85 ++NumGlobalsConstanted;