blob: ad5b8947edc788d57b98567fb186ea612ec3877a [file] [log] [blame]
Chris Lattner934fe852003-06-28 21:54:55 +00001//===- DataStructureOpt.cpp - Data Structure Analysis Based Optimizations -===//
2//
3// This pass uses DSA to a series of simple optimizations, like marking
4// unwritten global variables 'constant'.
5//
6//===----------------------------------------------------------------------===//
7
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"
13
14namespace {
15 Statistic<>
16 NumGlobalsConstanted("ds-opt", "Number of globals marked constant");
17
18 class DSOpt : public Pass {
19 TDDataStructures *TD;
20 public:
21 bool run(Module &M) {
22 TD = &getAnalysis<TDDataStructures>();
23 bool Changed = OptimizeGlobals(M);
24 return Changed;
25 }
26
27 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
28 AU.addRequired<TDDataStructures>(); // Uses TD Datastructures
29 AU.addPreserved<LocalDataStructures>(); // Preserves local...
30 AU.addPreserved<TDDataStructures>(); // Preserves bu...
31 AU.addPreserved<BUDataStructures>(); // Preserves td...
32 }
33
34 private:
35 bool OptimizeGlobals(Module &M);
36 };
37
38 RegisterOpt<DSOpt> X("ds-opt", "DSA-based simple optimizations");
39}
40
41
42/// OptimizeGlobals - This method uses information taken from DSA to optimize
43/// global variables.
44///
45bool DSOpt::OptimizeGlobals(Module &M) {
46 DSGraph &GG = TD->getGlobalsGraph();
47 const DSGraph::ScalarMapTy &SM = GG.getScalarMap();
48 bool Changed = false;
49
50 for (Module::giterator I = M.gbegin(), E = M.gend(); I != E; ++I)
51 if (!I->isExternal()) { // Loop over all of the non-external globals...
52 // Look up the node corresponding to this global, if it exists.
53 DSNode *GNode = 0;
54 DSGraph::ScalarMapTy::const_iterator SMI = SM.find(I);
55 if (SMI != SM.end()) GNode = SMI->second.getNode();
56
57 if (GNode == 0 && I->hasInternalLinkage()) {
58 // If there is no entry in the scalar map for this global, it was never
59 // referenced in the program. If it has internal linkage, that means we
60 // can delete it. We don't ACTUALLY want to delete the global, just
61 // remove anything that references the global: later passes will take
62 // care of nuking it.
63 I->replaceAllUsesWith(Constant::getNullValue((Type*)I->getType()));
64 } else if (GNode && GNode->isComplete()) {
65 // We expect that there will almost always be a node for this global.
66 // If there is, and the node doesn't have the M bit set, we can set the
67 // 'constant' bit on the global.
68 if (!GNode->isModified() && !I->isConstant()) {
69 I->setConstant(true);
70 ++NumGlobalsConstanted;
71 Changed = true;
72 }
73 }
74 }
75 return Changed;
76}