Fine grainify namespacification
[oota-llvm.git] / lib / Transforms / Scalar / ConstantProp.cpp
1 //===- ConstantProp.cpp - Code to perform Simple Constant Propagation -----===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements constant propagation and merging:
11 //
12 // Specifically, this:
13 //   * Converts instructions like "add int 1, 2" into 3
14 //
15 // Notice that:
16 //   * This pass has a habit of making definitions be dead.  It is a good idea
17 //     to to run a DIE pass sometime after running this pass.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 #include "llvm/ConstantHandling.h"
24 #include "llvm/Instruction.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/InstIterator.h"
27 #include "Support/Statistic.h"
28 #include <set>
29
30 namespace llvm {
31
32 namespace {
33   Statistic<> NumInstKilled("constprop", "Number of instructions killed");
34
35   struct ConstantPropagation : public FunctionPass {
36     bool runOnFunction(Function &F);
37
38     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
39       AU.setPreservesCFG();
40     }
41   };
42
43   RegisterOpt<ConstantPropagation> X("constprop","Simple constant propagation");
44 }
45
46 Pass *createConstantPropagationPass() {
47   return new ConstantPropagation();
48 }
49
50
51 bool ConstantPropagation::runOnFunction(Function &F) {
52   // Initialize the worklist to all of the instructions ready to process...
53   std::set<Instruction*> WorkList(inst_begin(F), inst_end(F));
54   bool Changed = false;
55
56   while (!WorkList.empty()) {
57     Instruction *I = *WorkList.begin();
58     WorkList.erase(WorkList.begin());    // Get an element from the worklist...
59
60     if (!I->use_empty())                 // Don't muck with dead instructions...
61       if (Constant *C = ConstantFoldInstruction(I)) {
62         // Add all of the users of this instruction to the worklist, they might
63         // be constant propagatable now...
64         for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
65              UI != UE; ++UI)
66           WorkList.insert(cast<Instruction>(*UI));
67         
68         // Replace all of the uses of a variable with uses of the constant.
69         I->replaceAllUsesWith(C);
70
71         // We made a change to the function...
72         Changed = true;
73         ++NumInstKilled;
74       }
75   }
76   return Changed;
77 }
78
79 } // End llvm namespace