1 //===- ConstantProp.cpp - Code to perform Simple Constant Propagation -----===//
3 // This file implements constant propagation and merging:
6 // * Converts instructions like "add int 1, 2" into 3
9 // * This pass has a habit of making definitions be dead. It is a good idea
10 // to to run a DIE pass sometime after running this pass.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/Scalar.h"
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/ConstantHandling.h"
17 #include "llvm/Instruction.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Support/InstIterator.h"
20 #include "Support/Statistic.h"
24 Statistic<> NumInstKilled("constprop", "Number of instructions killed");
26 struct ConstantPropagation : public FunctionPass {
27 bool runOnFunction(Function &F);
29 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
34 RegisterOpt<ConstantPropagation> X("constprop","Simple constant propagation");
37 Pass *createConstantPropagationPass() {
38 return new ConstantPropagation();
42 bool ConstantPropagation::runOnFunction(Function &F) {
43 // Initialize the worklist to all of the instructions ready to process...
44 std::set<Instruction*> WorkList(inst_begin(F), inst_end(F));
47 while (!WorkList.empty()) {
48 Instruction *I = *WorkList.begin();
49 WorkList.erase(WorkList.begin()); // Get an element from the worklist...
51 if (!I->use_empty()) // Don't muck with dead instructions...
52 if (Constant *C = ConstantFoldInstruction(I)) {
53 // Add all of the users of this instruction to the worklist, they might
54 // be constant propagatable now...
55 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
57 WorkList.insert(cast<Instruction>(*UI));
59 // Replace all of the uses of a variable with uses of the constant.
60 I->replaceAllUsesWith(C);
62 // We made a change to the function...