blob: dc141d5b54e953dbe301b41591df99a9b10f3e7e [file] [log] [blame]
Misha Brukman82c89b92003-05-20 21:01:22 +00001//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
John Criswellb576c942003-10-20 19:43:21 +00002//
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//===----------------------------------------------------------------------===//
Chris Lattner138a1242001-06-27 23:38:11 +00009//
Misha Brukman82c89b92003-05-20 21:01:22 +000010// This file implements sparse conditional constant propagation and merging:
Chris Lattner138a1242001-06-27 23:38:11 +000011//
12// Specifically, this:
13// * Assumes values are constant unless proven otherwise
14// * Assumes BasicBlocks are dead unless proven otherwise
15// * Proves values to be constant, and replaces them with constants
Chris Lattner2a88bb72002-08-30 23:39:00 +000016// * Proves conditional branches to be unconditional
Chris Lattner138a1242001-06-27 23:38:11 +000017//
18// Notice that:
19// * This pass has a habit of making definitions be dead. It is a good idea
20// to to run a DCE pass sometime after running this pass.
21//
22//===----------------------------------------------------------------------===//
23
Chris Lattner022103b2002-05-07 20:03:00 +000024#include "llvm/Transforms/Scalar.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000025#include "llvm/Constants.h"
Chris Lattner79df7c02002-03-26 18:01:55 +000026#include "llvm/Function.h"
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +000027#include "llvm/GlobalVariable.h"
Chris Lattner9de28282003-04-25 02:50:03 +000028#include "llvm/Instructions.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000029#include "llvm/Pass.h"
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +000030#include "llvm/Type.h"
Chris Lattner2a632552002-04-18 15:13:15 +000031#include "llvm/Support/InstVisitor.h"
Chris Lattner58b7b082004-04-13 19:43:54 +000032#include "llvm/Transforms/Utils/Local.h"
Chris Lattner6806f562003-08-01 22:15:03 +000033#include "Support/Debug.h"
Chris Lattner80b2d6c2004-07-15 23:36:43 +000034#include "Support/hash_map"
Chris Lattnera92f6962002-10-01 22:38:41 +000035#include "Support/Statistic.h"
Chris Lattner6806f562003-08-01 22:15:03 +000036#include "Support/STLExtras.h"
Chris Lattner138a1242001-06-27 23:38:11 +000037#include <algorithm>
Chris Lattner138a1242001-06-27 23:38:11 +000038#include <set>
Chris Lattnerd7456022004-01-09 06:02:20 +000039using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000040
Chris Lattner138a1242001-06-27 23:38:11 +000041// InstVal class - This class represents the different lattice values that an
Chris Lattnerf57b8452002-04-27 06:56:12 +000042// instruction may occupy. It is a simple class with value semantics.
Chris Lattner138a1242001-06-27 23:38:11 +000043//
Chris Lattner0dbfc052002-04-29 21:26:08 +000044namespace {
Chris Lattnera92f6962002-10-01 22:38:41 +000045 Statistic<> NumInstRemoved("sccp", "Number of instructions removed");
46
Chris Lattner138a1242001-06-27 23:38:11 +000047class InstVal {
48 enum {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000049 undefined, // This instruction has no known value
50 constant, // This instruction has a constant value
Chris Lattnere9bb2df2001-12-03 22:26:30 +000051 overdefined // This instruction has an unknown value
52 } LatticeValue; // The current lattice position
53 Constant *ConstantVal; // If Constant value, the current value
Chris Lattner138a1242001-06-27 23:38:11 +000054public:
Chris Lattnere9bb2df2001-12-03 22:26:30 +000055 inline InstVal() : LatticeValue(undefined), ConstantVal(0) {}
Chris Lattner138a1242001-06-27 23:38:11 +000056
57 // markOverdefined - Return true if this is a new status to be in...
58 inline bool markOverdefined() {
Chris Lattnere9bb2df2001-12-03 22:26:30 +000059 if (LatticeValue != overdefined) {
60 LatticeValue = overdefined;
Chris Lattner138a1242001-06-27 23:38:11 +000061 return true;
62 }
63 return false;
64 }
65
66 // markConstant - Return true if this is a new status for us...
Chris Lattnere9bb2df2001-12-03 22:26:30 +000067 inline bool markConstant(Constant *V) {
68 if (LatticeValue != constant) {
69 LatticeValue = constant;
Chris Lattner138a1242001-06-27 23:38:11 +000070 ConstantVal = V;
71 return true;
72 } else {
Chris Lattnerb70d82f2001-09-07 16:43:22 +000073 assert(ConstantVal == V && "Marking constant with different value");
Chris Lattner138a1242001-06-27 23:38:11 +000074 }
75 return false;
76 }
77
Chris Lattnere9bb2df2001-12-03 22:26:30 +000078 inline bool isUndefined() const { return LatticeValue == undefined; }
79 inline bool isConstant() const { return LatticeValue == constant; }
80 inline bool isOverdefined() const { return LatticeValue == overdefined; }
Chris Lattner138a1242001-06-27 23:38:11 +000081
Chris Lattner1daee8b2004-01-12 03:57:30 +000082 inline Constant *getConstant() const {
83 assert(isConstant() && "Cannot get the constant of a non-constant!");
84 return ConstantVal;
85 }
Chris Lattner138a1242001-06-27 23:38:11 +000086};
87
Chris Lattner0dbfc052002-04-29 21:26:08 +000088} // end anonymous namespace
Chris Lattner138a1242001-06-27 23:38:11 +000089
90
91//===----------------------------------------------------------------------===//
92// SCCP Class
93//
Misha Brukman82c89b92003-05-20 21:01:22 +000094// This class does all of the work of Sparse Conditional Constant Propagation.
Chris Lattner138a1242001-06-27 23:38:11 +000095//
Chris Lattner0dbfc052002-04-29 21:26:08 +000096namespace {
97class SCCP : public FunctionPass, public InstVisitor<SCCP> {
Chris Lattner697954c2002-01-20 22:54:45 +000098 std::set<BasicBlock*> BBExecutable;// The basic blocks that are executable
Chris Lattner80b2d6c2004-07-15 23:36:43 +000099 hash_map<Value*, InstVal> ValueState; // The state each value is in...
Chris Lattner138a1242001-06-27 23:38:11 +0000100
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000101 // The reason for two worklists is that overdefined is the lowest state
102 // on the lattice, and moving things to overdefined as fast as possible
103 // makes SCCP converge much faster.
104 // By having a separate worklist, we accomplish this because everything
105 // possibly overdefined will become overdefined at the soonest possible
106 // point.
107 std::vector<Instruction*> OverdefinedInstWorkList;// The overdefined
108 // instruction work list
Chris Lattner071d0ad2002-05-07 04:29:32 +0000109 std::vector<Instruction*> InstWorkList;// The instruction work list
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000110
111
Chris Lattner697954c2002-01-20 22:54:45 +0000112 std::vector<BasicBlock*> BBWorkList; // The BasicBlock work list
Chris Lattner16b18fd2003-10-08 16:55:34 +0000113
Chris Lattner1daee8b2004-01-12 03:57:30 +0000114 /// UsersOfOverdefinedPHIs - Keep track of any users of PHI nodes that are not
115 /// overdefined, despite the fact that the PHI node is overdefined.
116 std::multimap<PHINode*, Instruction*> UsersOfOverdefinedPHIs;
117
Chris Lattner16b18fd2003-10-08 16:55:34 +0000118 /// KnownFeasibleEdges - Entries in this set are edges which have already had
119 /// PHI nodes retriggered.
120 typedef std::pair<BasicBlock*,BasicBlock*> Edge;
121 std::set<Edge> KnownFeasibleEdges;
Chris Lattner138a1242001-06-27 23:38:11 +0000122public:
123
Misha Brukman82c89b92003-05-20 21:01:22 +0000124 // runOnFunction - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner0dbfc052002-04-29 21:26:08 +0000125 // and return true if the function was modified.
126 //
Chris Lattner7e708292002-06-25 16:13:24 +0000127 bool runOnFunction(Function &F);
Chris Lattner0dbfc052002-04-29 21:26:08 +0000128
129 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnercb2610e2002-10-21 20:00:28 +0000130 AU.setPreservesCFG();
Chris Lattner0dbfc052002-04-29 21:26:08 +0000131 }
132
Chris Lattner138a1242001-06-27 23:38:11 +0000133
134 //===--------------------------------------------------------------------===//
135 // The implementation of this class
136 //
137private:
Chris Lattner2a632552002-04-18 15:13:15 +0000138 friend class InstVisitor<SCCP>; // Allow callbacks from visitor
Chris Lattner138a1242001-06-27 23:38:11 +0000139
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000140 // markConstant - Make a value be marked as "constant". If the value
Chris Lattner138a1242001-06-27 23:38:11 +0000141 // is not already a constant, add it to the instruction work list so that
142 // the users of the instruction are updated later.
143 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000144 inline void markConstant(InstVal &IV, Instruction *I, Constant *C) {
145 if (IV.markConstant(C)) {
146 DEBUG(std::cerr << "markConstant: " << *C << ": " << *I);
Chris Lattner071d0ad2002-05-07 04:29:32 +0000147 InstWorkList.push_back(I);
Chris Lattner138a1242001-06-27 23:38:11 +0000148 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000149 }
150 inline void markConstant(Instruction *I, Constant *C) {
151 markConstant(ValueState[I], I, C);
Chris Lattner138a1242001-06-27 23:38:11 +0000152 }
153
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000154 // markOverdefined - Make a value be marked as "overdefined". If the
155 // value is not already overdefined, add it to the overdefined instruction
156 // work list so that the users of the instruction are updated later.
157
Chris Lattner3d405b02003-10-08 16:21:03 +0000158 inline void markOverdefined(InstVal &IV, Instruction *I) {
159 if (IV.markOverdefined()) {
160 DEBUG(std::cerr << "markOverdefined: " << *I);
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000161 OverdefinedInstWorkList.push_back(I); // Only instructions go on the work list
Chris Lattner138a1242001-06-27 23:38:11 +0000162 }
Chris Lattner3d405b02003-10-08 16:21:03 +0000163 }
164 inline void markOverdefined(Instruction *I) {
165 markOverdefined(ValueState[I], I);
Chris Lattner138a1242001-06-27 23:38:11 +0000166 }
167
168 // getValueState - Return the InstVal object that corresponds to the value.
Misha Brukman5560c9d2003-08-18 14:43:39 +0000169 // This function is necessary because not all values should start out in the
Chris Lattner73e21422002-04-09 19:48:49 +0000170 // underdefined state... Argument's should be overdefined, and
Chris Lattner79df7c02002-03-26 18:01:55 +0000171 // constants should be marked as constants. If a value is not known to be an
Chris Lattner138a1242001-06-27 23:38:11 +0000172 // Instruction object, then use this accessor to get its value from the map.
173 //
174 inline InstVal &getValueState(Value *V) {
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000175 hash_map<Value*, InstVal>::iterator I = ValueState.find(V);
Chris Lattner138a1242001-06-27 23:38:11 +0000176 if (I != ValueState.end()) return I->second; // Common case, in the map
177
Reid Spencer21cb67e2004-07-18 00:31:05 +0000178 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
179 // The address of a global is a constant...
180 ValueState[V].markConstant(GV);
181 } else if (Constant *CPV = dyn_cast<Constant>(V)) { // Constants are constant
Chris Lattner138a1242001-06-27 23:38:11 +0000182 ValueState[CPV].markConstant(CPV);
Chris Lattner73e21422002-04-09 19:48:49 +0000183 } else if (isa<Argument>(V)) { // Arguments are overdefined
Chris Lattner138a1242001-06-27 23:38:11 +0000184 ValueState[V].markOverdefined();
Chris Lattner2a88bb72002-08-30 23:39:00 +0000185 }
Chris Lattner138a1242001-06-27 23:38:11 +0000186 // All others are underdefined by default...
187 return ValueState[V];
188 }
189
Chris Lattner16b18fd2003-10-08 16:55:34 +0000190 // markEdgeExecutable - Mark a basic block as executable, adding it to the BB
Chris Lattner138a1242001-06-27 23:38:11 +0000191 // work list if it is not already executable...
192 //
Chris Lattner16b18fd2003-10-08 16:55:34 +0000193 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
194 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
195 return; // This edge is already known to be executable!
196
197 if (BBExecutable.count(Dest)) {
198 DEBUG(std::cerr << "Marking Edge Executable: " << Source->getName()
199 << " -> " << Dest->getName() << "\n");
200
201 // The destination is already executable, but we just made an edge
Chris Lattner929c6fb2003-10-08 16:56:11 +0000202 // feasible that wasn't before. Revisit the PHI nodes in the block
203 // because they have potentially new operands.
Chris Lattner16b18fd2003-10-08 16:55:34 +0000204 for (BasicBlock::iterator I = Dest->begin();
Chris Lattner9de28282003-04-25 02:50:03 +0000205 PHINode *PN = dyn_cast<PHINode>(I); ++I)
Chris Lattnerbceb2b02003-04-25 03:35:10 +0000206 visitPHINode(*PN);
Chris Lattner9de28282003-04-25 02:50:03 +0000207
208 } else {
Chris Lattner16b18fd2003-10-08 16:55:34 +0000209 DEBUG(std::cerr << "Marking Block Executable: " << Dest->getName()<<"\n");
210 BBExecutable.insert(Dest); // Basic block is executable!
211 BBWorkList.push_back(Dest); // Add the block to the work list!
Chris Lattner9de28282003-04-25 02:50:03 +0000212 }
Chris Lattner138a1242001-06-27 23:38:11 +0000213 }
214
Chris Lattner138a1242001-06-27 23:38:11 +0000215
Chris Lattner2a632552002-04-18 15:13:15 +0000216 // visit implementations - Something changed in this instruction... Either an
Chris Lattnercb056de2001-06-29 23:56:23 +0000217 // operand made a transition, or the instruction is newly executable. Change
218 // the value type of I to reflect these changes if appropriate.
219 //
Chris Lattner7e708292002-06-25 16:13:24 +0000220 void visitPHINode(PHINode &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000221
222 // Terminators
Chris Lattner7e708292002-06-25 16:13:24 +0000223 void visitReturnInst(ReturnInst &I) { /*does not have an effect*/ }
224 void visitTerminatorInst(TerminatorInst &TI);
Chris Lattner2a632552002-04-18 15:13:15 +0000225
Chris Lattnerb8047602002-08-14 17:53:45 +0000226 void visitCastInst(CastInst &I);
Chris Lattner6e323722004-03-12 05:52:44 +0000227 void visitSelectInst(SelectInst &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000228 void visitBinaryOperator(Instruction &I);
229 void visitShiftInst(ShiftInst &I) { visitBinaryOperator(I); }
Chris Lattner2a632552002-04-18 15:13:15 +0000230
231 // Instructions that cannot be folded away...
Chris Lattner7e708292002-06-25 16:13:24 +0000232 void visitStoreInst (Instruction &I) { /*returns void*/ }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000233 void visitLoadInst (LoadInst &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000234 void visitGetElementPtrInst(GetElementPtrInst &I);
Chris Lattner58b7b082004-04-13 19:43:54 +0000235 void visitCallInst (CallInst &I);
Chris Lattner99b28e62003-08-27 01:08:35 +0000236 void visitInvokeInst (TerminatorInst &I) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000237 if (I.getType() != Type::VoidTy) markOverdefined(&I);
Chris Lattner99b28e62003-08-27 01:08:35 +0000238 visitTerminatorInst(I);
239 }
Chris Lattner36143fc2003-09-08 18:54:55 +0000240 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
Chris Lattner7e708292002-06-25 16:13:24 +0000241 void visitAllocationInst(Instruction &I) { markOverdefined(&I); }
Chris Lattnercda965e2003-10-18 05:56:52 +0000242 void visitVANextInst (Instruction &I) { markOverdefined(&I); }
243 void visitVAArgInst (Instruction &I) { markOverdefined(&I); }
Chris Lattner7e708292002-06-25 16:13:24 +0000244 void visitFreeInst (Instruction &I) { /*returns void*/ }
Chris Lattner2a632552002-04-18 15:13:15 +0000245
Chris Lattner7e708292002-06-25 16:13:24 +0000246 void visitInstruction(Instruction &I) {
Chris Lattner2a632552002-04-18 15:13:15 +0000247 // If a new instruction is added to LLVM that we don't handle...
Chris Lattner9de28282003-04-25 02:50:03 +0000248 std::cerr << "SCCP: Don't know how to handle: " << I;
Chris Lattner7e708292002-06-25 16:13:24 +0000249 markOverdefined(&I); // Just in case
Chris Lattner2a632552002-04-18 15:13:15 +0000250 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000251
Chris Lattnerb9a66342002-05-02 21:44:00 +0000252 // getFeasibleSuccessors - Return a vector of booleans to indicate which
253 // successors are reachable from a given terminator instruction.
254 //
Chris Lattner7e708292002-06-25 16:13:24 +0000255 void getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000256
Chris Lattner59f0ce22002-05-02 21:18:01 +0000257 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
258 // block to the 'To' basic block is currently feasible...
259 //
260 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
261
Chris Lattnercb056de2001-06-29 23:56:23 +0000262 // OperandChangedState - This method is invoked on all of the users of an
263 // instruction that was just changed state somehow.... Based on this
264 // information, we need to update the specified user of this instruction.
265 //
Chris Lattner59f0ce22002-05-02 21:18:01 +0000266 void OperandChangedState(User *U) {
267 // Only instructions use other variable values!
Chris Lattner7e708292002-06-25 16:13:24 +0000268 Instruction &I = cast<Instruction>(*U);
Chris Lattner9de28282003-04-25 02:50:03 +0000269 if (BBExecutable.count(I.getParent())) // Inst is executable?
270 visit(I);
Chris Lattner59f0ce22002-05-02 21:18:01 +0000271 }
Chris Lattnercb056de2001-06-29 23:56:23 +0000272};
Chris Lattnerf6293092002-07-23 18:06:35 +0000273
Chris Lattner9de28282003-04-25 02:50:03 +0000274 RegisterOpt<SCCP> X("sccp", "Sparse Conditional Constant Propagation");
Chris Lattner0dbfc052002-04-29 21:26:08 +0000275} // end anonymous namespace
276
277
278// createSCCPPass - This is the public interface to this file...
Chris Lattnerd7456022004-01-09 06:02:20 +0000279Pass *llvm::createSCCPPass() {
Chris Lattner0dbfc052002-04-29 21:26:08 +0000280 return new SCCP();
281}
282
Chris Lattner138a1242001-06-27 23:38:11 +0000283
Chris Lattner138a1242001-06-27 23:38:11 +0000284//===----------------------------------------------------------------------===//
285// SCCP Class Implementation
286
287
Misha Brukman82c89b92003-05-20 21:01:22 +0000288// runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
Chris Lattner0dbfc052002-04-29 21:26:08 +0000289// and return true if the function was modified.
Chris Lattner138a1242001-06-27 23:38:11 +0000290//
Chris Lattner7e708292002-06-25 16:13:24 +0000291bool SCCP::runOnFunction(Function &F) {
Chris Lattnerf57b8452002-04-27 06:56:12 +0000292 // Mark the first block of the function as being executable...
Chris Lattner16b18fd2003-10-08 16:55:34 +0000293 BBExecutable.insert(F.begin()); // Basic block is executable!
294 BBWorkList.push_back(F.begin()); // Add the block to the work list!
Chris Lattner138a1242001-06-27 23:38:11 +0000295
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000296 // Process the work lists until they are empty!
297 while (!BBWorkList.empty() || !InstWorkList.empty() ||
298 !OverdefinedInstWorkList.empty()) {
299 // Process the instruction work list...
300 while (!OverdefinedInstWorkList.empty()) {
301 Instruction *I = OverdefinedInstWorkList.back();
302 OverdefinedInstWorkList.pop_back();
303
304 DEBUG(std::cerr << "\nPopped off OI-WL: " << I);
305
306 // "I" got into the work list because it either made the transition from
307 // bottom to constant
308 //
309 // Anything on this worklist that is overdefined need not be visited
310 // since all of its users will have already been marked as overdefined
311 // Update all of the users of this instruction's value...
312 //
313 for_each(I->use_begin(), I->use_end(),
314 bind_obj(this, &SCCP::OperandChangedState));
315 }
Chris Lattner138a1242001-06-27 23:38:11 +0000316 // Process the instruction work list...
317 while (!InstWorkList.empty()) {
Chris Lattner071d0ad2002-05-07 04:29:32 +0000318 Instruction *I = InstWorkList.back();
319 InstWorkList.pop_back();
Chris Lattner138a1242001-06-27 23:38:11 +0000320
Chris Lattner2fc12302004-07-15 01:50:47 +0000321 DEBUG(std::cerr << "\nPopped off I-WL: " << *I);
Chris Lattner138a1242001-06-27 23:38:11 +0000322
323 // "I" got into the work list because it either made the transition from
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000324 // bottom to constant
Chris Lattner138a1242001-06-27 23:38:11 +0000325 //
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000326 // Anything on this worklist that is overdefined need not be visited
327 // since all of its users will have already been marked as overdefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000328 // Update all of the users of this instruction's value...
329 //
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000330 InstVal &Ival = getValueState (I);
331 if (!Ival.isOverdefined())
332 for_each(I->use_begin(), I->use_end(),
333 bind_obj(this, &SCCP::OperandChangedState));
Chris Lattner138a1242001-06-27 23:38:11 +0000334 }
335
336 // Process the basic block work list...
337 while (!BBWorkList.empty()) {
338 BasicBlock *BB = BBWorkList.back();
339 BBWorkList.pop_back();
340
Chris Lattner2fc12302004-07-15 01:50:47 +0000341 DEBUG(std::cerr << "\nPopped off BBWL: " << *BB);
Chris Lattner138a1242001-06-27 23:38:11 +0000342
Chris Lattner2a632552002-04-18 15:13:15 +0000343 // Notify all instructions in this basic block that they are newly
344 // executable.
345 visit(BB);
Chris Lattner138a1242001-06-27 23:38:11 +0000346 }
347 }
348
Chris Lattnerf016ea42002-05-22 17:17:27 +0000349 if (DebugFlag) {
Chris Lattner7e708292002-06-25 16:13:24 +0000350 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I)
351 if (!BBExecutable.count(I))
Chris Lattner9de28282003-04-25 02:50:03 +0000352 std::cerr << "BasicBlock Dead:" << *I;
Chris Lattnerf016ea42002-05-22 17:17:27 +0000353 }
Chris Lattner138a1242001-06-27 23:38:11 +0000354
Chris Lattnerf57b8452002-04-27 06:56:12 +0000355 // Iterate over all of the instructions in a function, replacing them with
Chris Lattner138a1242001-06-27 23:38:11 +0000356 // constants if we have found them to be of constant values.
357 //
358 bool MadeChanges = false;
Chris Lattner7e708292002-06-25 16:13:24 +0000359 for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB)
Chris Lattner221d6882002-02-12 21:07:25 +0000360 for (BasicBlock::iterator BI = BB->begin(); BI != BB->end();) {
Chris Lattner7e708292002-06-25 16:13:24 +0000361 Instruction &Inst = *BI;
362 InstVal &IV = ValueState[&Inst];
Chris Lattner221d6882002-02-12 21:07:25 +0000363 if (IV.isConstant()) {
364 Constant *Const = IV.getConstant();
Chris Lattner2fc12302004-07-15 01:50:47 +0000365 DEBUG(std::cerr << "Constant: " << *Const << " = " << Inst);
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000366
Chris Lattner221d6882002-02-12 21:07:25 +0000367 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner7e708292002-06-25 16:13:24 +0000368 Inst.replaceAllUsesWith(Const);
Chris Lattner138a1242001-06-27 23:38:11 +0000369
Chris Lattner0e9c5152002-05-02 20:32:51 +0000370 // Remove the operator from the list of definitions... and delete it.
Chris Lattner7e708292002-06-25 16:13:24 +0000371 BI = BB->getInstList().erase(BI);
Chris Lattner138a1242001-06-27 23:38:11 +0000372
Chris Lattner221d6882002-02-12 21:07:25 +0000373 // Hey, we just changed something!
374 MadeChanges = true;
Chris Lattner3dec1f22002-05-10 15:38:35 +0000375 ++NumInstRemoved;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000376 } else {
377 ++BI;
Chris Lattner221d6882002-02-12 21:07:25 +0000378 }
Chris Lattner138a1242001-06-27 23:38:11 +0000379 }
Chris Lattner138a1242001-06-27 23:38:11 +0000380
Chris Lattner59f0ce22002-05-02 21:18:01 +0000381 // Reset state so that the next invocation will have empty data structures
Chris Lattner0dbfc052002-04-29 21:26:08 +0000382 BBExecutable.clear();
383 ValueState.clear();
Chris Lattner80b2d6c2004-07-15 23:36:43 +0000384 std::vector<Instruction*>().swap(OverdefinedInstWorkList);
Chris Lattneraf663462002-11-04 02:54:22 +0000385 std::vector<Instruction*>().swap(InstWorkList);
386 std::vector<BasicBlock*>().swap(BBWorkList);
Chris Lattner0dbfc052002-04-29 21:26:08 +0000387
Chris Lattnerb70d82f2001-09-07 16:43:22 +0000388 return MadeChanges;
Chris Lattner138a1242001-06-27 23:38:11 +0000389}
390
Chris Lattnerb9a66342002-05-02 21:44:00 +0000391
392// getFeasibleSuccessors - Return a vector of booleans to indicate which
393// successors are reachable from a given terminator instruction.
394//
Chris Lattner7e708292002-06-25 16:13:24 +0000395void SCCP::getFeasibleSuccessors(TerminatorInst &TI, std::vector<bool> &Succs) {
Chris Lattner9de28282003-04-25 02:50:03 +0000396 Succs.resize(TI.getNumSuccessors());
Chris Lattner7e708292002-06-25 16:13:24 +0000397 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000398 if (BI->isUnconditional()) {
399 Succs[0] = true;
400 } else {
401 InstVal &BCValue = getValueState(BI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000402 if (BCValue.isOverdefined() ||
403 (BCValue.isConstant() && !isa<ConstantBool>(BCValue.getConstant()))) {
404 // Overdefined condition variables, and branches on unfoldable constant
405 // conditions, mean the branch could go either way.
Chris Lattnerb9a66342002-05-02 21:44:00 +0000406 Succs[0] = Succs[1] = true;
407 } else if (BCValue.isConstant()) {
408 // Constant condition variables mean the branch can only go a single way
409 Succs[BCValue.getConstant() == ConstantBool::False] = true;
410 }
411 }
Chris Lattner7e708292002-06-25 16:13:24 +0000412 } else if (InvokeInst *II = dyn_cast<InvokeInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000413 // Invoke instructions successors are always executable.
414 Succs[0] = Succs[1] = true;
Chris Lattner7e708292002-06-25 16:13:24 +0000415 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000416 InstVal &SCValue = getValueState(SI->getCondition());
Chris Lattner84831642004-01-12 17:40:36 +0000417 if (SCValue.isOverdefined() || // Overdefined condition?
418 (SCValue.isConstant() && !isa<ConstantInt>(SCValue.getConstant()))) {
Chris Lattnerb9a66342002-05-02 21:44:00 +0000419 // All destinations are executable!
Chris Lattner7e708292002-06-25 16:13:24 +0000420 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000421 } else if (SCValue.isConstant()) {
422 Constant *CPV = SCValue.getConstant();
423 // Make sure to skip the "default value" which isn't a value
424 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i) {
425 if (SI->getSuccessorValue(i) == CPV) {// Found the right branch...
426 Succs[i] = true;
427 return;
428 }
429 }
430
431 // Constant value not equal to any of the branches... must execute
432 // default branch then...
433 Succs[0] = true;
434 }
435 } else {
Chris Lattner9de28282003-04-25 02:50:03 +0000436 std::cerr << "SCCP: Don't know how to handle: " << TI;
Chris Lattner7e708292002-06-25 16:13:24 +0000437 Succs.assign(TI.getNumSuccessors(), true);
Chris Lattnerb9a66342002-05-02 21:44:00 +0000438 }
439}
440
441
Chris Lattner59f0ce22002-05-02 21:18:01 +0000442// isEdgeFeasible - Return true if the control flow edge from the 'From' basic
443// block to the 'To' basic block is currently feasible...
444//
445bool SCCP::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
446 assert(BBExecutable.count(To) && "Dest should always be alive!");
447
448 // Make sure the source basic block is executable!!
449 if (!BBExecutable.count(From)) return false;
450
Chris Lattnerb9a66342002-05-02 21:44:00 +0000451 // Check to make sure this edge itself is actually feasible now...
Chris Lattner7d275f42003-10-08 15:47:41 +0000452 TerminatorInst *TI = From->getTerminator();
453 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
454 if (BI->isUnconditional())
Chris Lattnerb9a66342002-05-02 21:44:00 +0000455 return true;
Chris Lattner7d275f42003-10-08 15:47:41 +0000456 else {
457 InstVal &BCValue = getValueState(BI->getCondition());
458 if (BCValue.isOverdefined()) {
459 // Overdefined condition variables mean the branch could go either way.
460 return true;
461 } else if (BCValue.isConstant()) {
Chris Lattner84831642004-01-12 17:40:36 +0000462 // Not branching on an evaluatable constant?
463 if (!isa<ConstantBool>(BCValue.getConstant())) return true;
464
Chris Lattner7d275f42003-10-08 15:47:41 +0000465 // Constant condition variables mean the branch can only go a single way
466 return BI->getSuccessor(BCValue.getConstant() ==
467 ConstantBool::False) == To;
468 }
469 return false;
470 }
471 } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
472 // Invoke instructions successors are always executable.
473 return true;
474 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
475 InstVal &SCValue = getValueState(SI->getCondition());
476 if (SCValue.isOverdefined()) { // Overdefined condition?
477 // All destinations are executable!
478 return true;
479 } else if (SCValue.isConstant()) {
480 Constant *CPV = SCValue.getConstant();
Chris Lattner84831642004-01-12 17:40:36 +0000481 if (!isa<ConstantInt>(CPV))
482 return true; // not a foldable constant?
483
Chris Lattner7d275f42003-10-08 15:47:41 +0000484 // Make sure to skip the "default value" which isn't a value
485 for (unsigned i = 1, E = SI->getNumSuccessors(); i != E; ++i)
486 if (SI->getSuccessorValue(i) == CPV) // Found the taken branch...
487 return SI->getSuccessor(i) == To;
488
489 // Constant value not equal to any of the branches... must execute
490 // default branch then...
491 return SI->getDefaultDest() == To;
492 }
493 return false;
494 } else {
495 std::cerr << "Unknown terminator instruction: " << *TI;
496 abort();
497 }
Chris Lattner59f0ce22002-05-02 21:18:01 +0000498}
Chris Lattner138a1242001-06-27 23:38:11 +0000499
Chris Lattner2a632552002-04-18 15:13:15 +0000500// visit Implementations - Something changed in this instruction... Either an
Chris Lattner138a1242001-06-27 23:38:11 +0000501// operand made a transition, or the instruction is newly executable. Change
502// the value type of I to reflect these changes if appropriate. This method
503// makes sure to do the following actions:
504//
505// 1. If a phi node merges two constants in, and has conflicting value coming
506// from different branches, or if the PHI node merges in an overdefined
507// value, then the PHI node becomes overdefined.
508// 2. If a phi node merges only constants in, and they all agree on value, the
509// PHI node becomes a constant value equal to that.
510// 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
511// 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
512// 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
513// 6. If a conditional branch has a value that is constant, make the selected
514// destination executable
515// 7. If a conditional branch has a value that is overdefined, make all
516// successors executable.
517//
Chris Lattner7e708292002-06-25 16:13:24 +0000518void SCCP::visitPHINode(PHINode &PN) {
Chris Lattner3d405b02003-10-08 16:21:03 +0000519 InstVal &PNIV = getValueState(&PN);
Chris Lattner1daee8b2004-01-12 03:57:30 +0000520 if (PNIV.isOverdefined()) {
521 // There may be instructions using this PHI node that are not overdefined
522 // themselves. If so, make sure that they know that the PHI node operand
523 // changed.
524 std::multimap<PHINode*, Instruction*>::iterator I, E;
525 tie(I, E) = UsersOfOverdefinedPHIs.equal_range(&PN);
526 if (I != E) {
527 std::vector<Instruction*> Users;
528 Users.reserve(std::distance(I, E));
529 for (; I != E; ++I) Users.push_back(I->second);
530 while (!Users.empty()) {
531 visit(Users.back());
532 Users.pop_back();
533 }
534 }
535 return; // Quick exit
536 }
Chris Lattner138a1242001-06-27 23:38:11 +0000537
Chris Lattnera2f652d2004-03-16 19:49:59 +0000538 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
539 // and slow us down a lot. Just mark them overdefined.
540 if (PN.getNumIncomingValues() > 64) {
541 markOverdefined(PNIV, &PN);
542 return;
543 }
544
Chris Lattner2a632552002-04-18 15:13:15 +0000545 // Look at all of the executable operands of the PHI node. If any of them
546 // are overdefined, the PHI becomes overdefined as well. If they are all
547 // constant, and they agree with each other, the PHI becomes the identical
548 // constant. If they are constant and don't agree, the PHI is overdefined.
549 // If there are no executable operands, the PHI remains undefined.
550 //
Chris Lattner9de28282003-04-25 02:50:03 +0000551 Constant *OperandVal = 0;
552 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
553 InstVal &IV = getValueState(PN.getIncomingValue(i));
554 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
Chris Lattner9de28282003-04-25 02:50:03 +0000555
Chris Lattner7e708292002-06-25 16:13:24 +0000556 if (isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent())) {
Chris Lattner38b5ae42003-06-24 20:29:52 +0000557 if (IV.isOverdefined()) { // PHI node becomes overdefined!
Chris Lattner3d405b02003-10-08 16:21:03 +0000558 markOverdefined(PNIV, &PN);
Chris Lattner38b5ae42003-06-24 20:29:52 +0000559 return;
560 }
561
Chris Lattner9de28282003-04-25 02:50:03 +0000562 if (OperandVal == 0) { // Grab the first value...
563 OperandVal = IV.getConstant();
Chris Lattner2a632552002-04-18 15:13:15 +0000564 } else { // Another value is being merged in!
565 // There is already a reachable operand. If we conflict with it,
566 // then the PHI node becomes overdefined. If we agree with it, we
567 // can continue on.
Chris Lattner9de28282003-04-25 02:50:03 +0000568
Chris Lattner2a632552002-04-18 15:13:15 +0000569 // Check to see if there are two different constants merging...
Chris Lattner9de28282003-04-25 02:50:03 +0000570 if (IV.getConstant() != OperandVal) {
Chris Lattner2a632552002-04-18 15:13:15 +0000571 // Yes there is. This means the PHI node is not constant.
572 // You must be overdefined poor PHI.
573 //
Chris Lattner3d405b02003-10-08 16:21:03 +0000574 markOverdefined(PNIV, &PN); // The PHI node now becomes overdefined
Chris Lattner2a632552002-04-18 15:13:15 +0000575 return; // I'm done analyzing you
Chris Lattner5b7d42b2001-11-26 18:57:38 +0000576 }
Chris Lattner138a1242001-06-27 23:38:11 +0000577 }
578 }
Chris Lattner138a1242001-06-27 23:38:11 +0000579 }
580
Chris Lattner2a632552002-04-18 15:13:15 +0000581 // If we exited the loop, this means that the PHI node only has constant
Chris Lattner9de28282003-04-25 02:50:03 +0000582 // arguments that agree with each other(and OperandVal is the constant) or
583 // OperandVal is null because there are no defined incoming arguments. If
584 // this is the case, the PHI remains undefined.
Chris Lattner138a1242001-06-27 23:38:11 +0000585 //
Chris Lattner9de28282003-04-25 02:50:03 +0000586 if (OperandVal)
Misha Brukmancf00c4a2003-10-10 17:57:28 +0000587 markConstant(PNIV, &PN, OperandVal); // Acquire operand value
Chris Lattner138a1242001-06-27 23:38:11 +0000588}
589
Chris Lattner7e708292002-06-25 16:13:24 +0000590void SCCP::visitTerminatorInst(TerminatorInst &TI) {
Chris Lattner9de28282003-04-25 02:50:03 +0000591 std::vector<bool> SuccFeasible;
Chris Lattnerb9a66342002-05-02 21:44:00 +0000592 getFeasibleSuccessors(TI, SuccFeasible);
Chris Lattner138a1242001-06-27 23:38:11 +0000593
Chris Lattner16b18fd2003-10-08 16:55:34 +0000594 BasicBlock *BB = TI.getParent();
595
Chris Lattnerb9a66342002-05-02 21:44:00 +0000596 // Mark all feasible successors executable...
597 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
Chris Lattner16b18fd2003-10-08 16:55:34 +0000598 if (SuccFeasible[i])
599 markEdgeExecutable(BB, TI.getSuccessor(i));
Chris Lattner2a632552002-04-18 15:13:15 +0000600}
601
Chris Lattnerb8047602002-08-14 17:53:45 +0000602void SCCP::visitCastInst(CastInst &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000603 Value *V = I.getOperand(0);
Chris Lattner2a632552002-04-18 15:13:15 +0000604 InstVal &VState = getValueState(V);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000605 if (VState.isOverdefined()) // Inherit overdefinedness of operand
Chris Lattner7e708292002-06-25 16:13:24 +0000606 markOverdefined(&I);
Chris Lattnerb7a5d3e2004-01-12 17:43:40 +0000607 else if (VState.isConstant()) // Propagate constant value
608 markConstant(&I, ConstantExpr::getCast(VState.getConstant(), I.getType()));
Chris Lattner2a632552002-04-18 15:13:15 +0000609}
610
Chris Lattner6e323722004-03-12 05:52:44 +0000611void SCCP::visitSelectInst(SelectInst &I) {
612 InstVal &CondValue = getValueState(I.getCondition());
613 if (CondValue.isOverdefined())
614 markOverdefined(&I);
615 else if (CondValue.isConstant()) {
616 if (CondValue.getConstant() == ConstantBool::True) {
617 InstVal &Val = getValueState(I.getTrueValue());
618 if (Val.isOverdefined())
619 markOverdefined(&I);
620 else if (Val.isConstant())
621 markConstant(&I, Val.getConstant());
622 } else if (CondValue.getConstant() == ConstantBool::False) {
623 InstVal &Val = getValueState(I.getFalseValue());
624 if (Val.isOverdefined())
625 markOverdefined(&I);
626 else if (Val.isConstant())
627 markConstant(&I, Val.getConstant());
628 } else
629 markOverdefined(&I);
630 }
631}
632
Chris Lattner2a632552002-04-18 15:13:15 +0000633// Handle BinaryOperators and Shift Instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000634void SCCP::visitBinaryOperator(Instruction &I) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000635 InstVal &IV = ValueState[&I];
636 if (IV.isOverdefined()) return;
637
Chris Lattner7e708292002-06-25 16:13:24 +0000638 InstVal &V1State = getValueState(I.getOperand(0));
639 InstVal &V2State = getValueState(I.getOperand(1));
Chris Lattner1daee8b2004-01-12 03:57:30 +0000640
Chris Lattner2a632552002-04-18 15:13:15 +0000641 if (V1State.isOverdefined() || V2State.isOverdefined()) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000642 // If both operands are PHI nodes, it is possible that this instruction has
643 // a constant value, despite the fact that the PHI node doesn't. Check for
644 // this condition now.
645 if (PHINode *PN1 = dyn_cast<PHINode>(I.getOperand(0)))
646 if (PHINode *PN2 = dyn_cast<PHINode>(I.getOperand(1)))
647 if (PN1->getParent() == PN2->getParent()) {
648 // Since the two PHI nodes are in the same basic block, they must have
649 // entries for the same predecessors. Walk the predecessor list, and
650 // if all of the incoming values are constants, and the result of
651 // evaluating this expression with all incoming value pairs is the
652 // same, then this expression is a constant even though the PHI node
653 // is not a constant!
654 InstVal Result;
655 for (unsigned i = 0, e = PN1->getNumIncomingValues(); i != e; ++i) {
656 InstVal &In1 = getValueState(PN1->getIncomingValue(i));
657 BasicBlock *InBlock = PN1->getIncomingBlock(i);
658 InstVal &In2 =getValueState(PN2->getIncomingValueForBlock(InBlock));
659
660 if (In1.isOverdefined() || In2.isOverdefined()) {
661 Result.markOverdefined();
662 break; // Cannot fold this operation over the PHI nodes!
663 } else if (In1.isConstant() && In2.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000664 Constant *V = ConstantExpr::get(I.getOpcode(), In1.getConstant(),
665 In2.getConstant());
Chris Lattner1daee8b2004-01-12 03:57:30 +0000666 if (Result.isUndefined())
Chris Lattnerb16689b2004-01-12 19:08:43 +0000667 Result.markConstant(V);
668 else if (Result.isConstant() && Result.getConstant() != V) {
Chris Lattner1daee8b2004-01-12 03:57:30 +0000669 Result.markOverdefined();
670 break;
671 }
672 }
673 }
674
675 // If we found a constant value here, then we know the instruction is
676 // constant despite the fact that the PHI nodes are overdefined.
677 if (Result.isConstant()) {
678 markConstant(IV, &I, Result.getConstant());
679 // Remember that this instruction is virtually using the PHI node
680 // operands.
681 UsersOfOverdefinedPHIs.insert(std::make_pair(PN1, &I));
682 UsersOfOverdefinedPHIs.insert(std::make_pair(PN2, &I));
683 return;
684 } else if (Result.isUndefined()) {
685 return;
686 }
687
688 // Okay, this really is overdefined now. Since we might have
689 // speculatively thought that this was not overdefined before, and
690 // added ourselves to the UsersOfOverdefinedPHIs list for the PHIs,
691 // make sure to clean out any entries that we put there, for
692 // efficiency.
693 std::multimap<PHINode*, Instruction*>::iterator It, E;
694 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN1);
695 while (It != E) {
696 if (It->second == &I) {
697 UsersOfOverdefinedPHIs.erase(It++);
698 } else
699 ++It;
700 }
701 tie(It, E) = UsersOfOverdefinedPHIs.equal_range(PN2);
702 while (It != E) {
703 if (It->second == &I) {
704 UsersOfOverdefinedPHIs.erase(It++);
705 } else
706 ++It;
707 }
708 }
709
710 markOverdefined(IV, &I);
Chris Lattner2a632552002-04-18 15:13:15 +0000711 } else if (V1State.isConstant() && V2State.isConstant()) {
Chris Lattnerb16689b2004-01-12 19:08:43 +0000712 markConstant(IV, &I, ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
713 V2State.getConstant()));
Chris Lattner2a632552002-04-18 15:13:15 +0000714 }
715}
Chris Lattner2a88bb72002-08-30 23:39:00 +0000716
717// Handle getelementptr instructions... if all operands are constants then we
718// can turn this into a getelementptr ConstantExpr.
719//
720void SCCP::visitGetElementPtrInst(GetElementPtrInst &I) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000721 InstVal &IV = ValueState[&I];
722 if (IV.isOverdefined()) return;
723
Chris Lattner2a88bb72002-08-30 23:39:00 +0000724 std::vector<Constant*> Operands;
725 Operands.reserve(I.getNumOperands());
726
727 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
728 InstVal &State = getValueState(I.getOperand(i));
729 if (State.isUndefined())
730 return; // Operands are not resolved yet...
731 else if (State.isOverdefined()) {
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000732 markOverdefined(IV, &I);
Chris Lattner2a88bb72002-08-30 23:39:00 +0000733 return;
734 }
735 assert(State.isConstant() && "Unknown state!");
736 Operands.push_back(State.getConstant());
737 }
738
739 Constant *Ptr = Operands[0];
740 Operands.erase(Operands.begin()); // Erase the pointer from idx list...
741
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000742 markConstant(IV, &I, ConstantExpr::getGetElementPtr(Ptr, Operands));
Chris Lattner2a88bb72002-08-30 23:39:00 +0000743}
Brian Gaeked0fde302003-11-11 22:41:34 +0000744
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000745/// GetGEPGlobalInitializer - Given a constant and a getelementptr constantexpr,
746/// return the constant value being addressed by the constant expression, or
747/// null if something is funny.
748///
749static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
Chris Lattner28977af2004-04-05 01:30:19 +0000750 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000751 return 0; // Do not allow stepping over the value!
752
753 // Loop over all of the operands, tracking down which value we are
754 // addressing...
755 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
756 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000757 ConstantStruct *CS = dyn_cast<ConstantStruct>(C);
758 if (CS == 0) return 0;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000759 if (CU->getValue() >= CS->getValues().size()) return 0;
760 C = cast<Constant>(CS->getValues()[CU->getValue()]);
761 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
Chris Lattnerde512b52004-02-15 05:55:15 +0000762 ConstantArray *CA = dyn_cast<ConstantArray>(C);
763 if (CA == 0) return 0;
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000764 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
765 C = cast<Constant>(CA->getValues()[CS->getValue()]);
Chris Lattnerde512b52004-02-15 05:55:15 +0000766 } else
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000767 return 0;
768 return C;
769}
770
771// Handle load instructions. If the operand is a constant pointer to a constant
772// global, we can replace the load with the loaded constant value!
773void SCCP::visitLoadInst(LoadInst &I) {
774 InstVal &IV = ValueState[&I];
775 if (IV.isOverdefined()) return;
776
777 InstVal &PtrVal = getValueState(I.getOperand(0));
778 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
779 if (PtrVal.isConstant() && !I.isVolatile()) {
780 Value *Ptr = PtrVal.getConstant();
Chris Lattnerc76d8032004-03-07 22:16:24 +0000781 if (isa<ConstantPointerNull>(Ptr)) {
782 // load null -> null
783 markConstant(IV, &I, Constant::getNullValue(I.getType()));
784 return;
785 }
786
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000787 // Transform load (constant global) into the value loaded.
788 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr))
789 if (GV->isConstant() && !GV->isExternal()) {
790 markConstant(IV, &I, GV->getInitializer());
791 return;
792 }
793
794 // Transform load (constantexpr_GEP global, 0, ...) into the value loaded.
795 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
796 if (CE->getOpcode() == Instruction::GetElementPtr)
Reid Spencer21cb67e2004-07-18 00:31:05 +0000797 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
798 if (GV->isConstant() && !GV->isExternal())
799 if (Constant *V =
800 GetGEPGlobalInitializer(GV->getInitializer(), CE)) {
801 markConstant(IV, &I, V);
802 return;
803 }
Chris Lattnerc6a4d6a2004-01-12 04:29:41 +0000804 }
805
806 // Otherwise we cannot say for certain what value this load will produce.
807 // Bail out.
808 markOverdefined(IV, &I);
809}
Chris Lattner58b7b082004-04-13 19:43:54 +0000810
811void SCCP::visitCallInst(CallInst &I) {
812 InstVal &IV = ValueState[&I];
813 if (IV.isOverdefined()) return;
814
815 Function *F = I.getCalledFunction();
816 if (F == 0 || !canConstantFoldCallTo(F)) {
817 markOverdefined(IV, &I);
818 return;
819 }
820
821 std::vector<Constant*> Operands;
822 Operands.reserve(I.getNumOperands()-1);
823
824 for (unsigned i = 1, e = I.getNumOperands(); i != e; ++i) {
825 InstVal &State = getValueState(I.getOperand(i));
826 if (State.isUndefined())
827 return; // Operands are not resolved yet...
828 else if (State.isOverdefined()) {
829 markOverdefined(IV, &I);
830 return;
831 }
832 assert(State.isConstant() && "Unknown state!");
833 Operands.push_back(State.getConstant());
834 }
835
836 if (Constant *C = ConstantFoldCall(F, Operands))
837 markConstant(IV, &I, C);
838 else
839 markOverdefined(IV, &I);
840}