1 //===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements sparse conditional constant propagation and merging:
11 //
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
16 // * Proves conditional branches to be unconditional
17 //
18 //===----------------------------------------------------------------------===//
19
20 #define DEBUG_TYPE "sccp"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Transforms/IPO.h"
23 #include "llvm/Constants.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Pass.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetLibraryInfo.h"
31 #include "llvm/Support/CallSite.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/InstVisitor.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DenseSet.h"
38 #include "llvm/ADT/PointerIntPair.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallVector.h"
41 #include "llvm/ADT/Statistic.h"
42 #include <algorithm>
43 using namespace llvm;
44
45 STATISTIC(NumInstRemoved, "Number of instructions removed");
46 STATISTIC(NumDeadBlocks , "Number of basic blocks unreachable");
47
48 STATISTIC(IPNumInstRemoved, "Number of instructions removed by IPSCCP");
49 STATISTIC(IPNumArgsElimed ,"Number of arguments constant propagated by IPSCCP");
50 STATISTIC(IPNumGlobalConst, "Number of globals found to be constant by IPSCCP");
51
52 namespace {
53 /// LatticeVal class - This class represents the different lattice values that
54 /// an LLVM value may occupy. It is a simple class with value semantics.
55 ///
56 class LatticeVal {
57 enum LatticeValueTy {
58 /// undefined - This LLVM Value has no known value yet.
59 undefined,
60
61 /// constant - This LLVM Value has a specific constant value.
62 constant,
63
64 /// forcedconstant - This LLVM Value was thought to be undef until
65 /// ResolvedUndefsIn. This is treated just like 'constant', but if merged
66 /// with another (different) constant, it goes to overdefined, instead of
67 /// asserting.
68 forcedconstant,
69
70 /// overdefined - This instruction is not known to be constant, and we know
71 /// it has a value.
72 overdefined
73 };
74
75 /// Val: This stores the current lattice value along with the Constant* for
76 /// the constant if this is a 'constant' or 'forcedconstant' value.
77 PointerIntPair<Constant *, 2, LatticeValueTy> Val;
78
getLatticeValue() const79 LatticeValueTy getLatticeValue() const {
80 return Val.getInt();
81 }
82
83 public:
LatticeVal()84 LatticeVal() : Val(0, undefined) {}
85
isUndefined() const86 bool isUndefined() const { return getLatticeValue() == undefined; }
isConstant() const87 bool isConstant() const {
88 return getLatticeValue() == constant || getLatticeValue() == forcedconstant;
89 }
isOverdefined() const90 bool isOverdefined() const { return getLatticeValue() == overdefined; }
91
getConstant() const92 Constant *getConstant() const {
93 assert(isConstant() && "Cannot get the constant of a non-constant!");
94 return Val.getPointer();
95 }
96
97 /// markOverdefined - Return true if this is a change in status.
markOverdefined()98 bool markOverdefined() {
99 if (isOverdefined())
100 return false;
101
102 Val.setInt(overdefined);
103 return true;
104 }
105
106 /// markConstant - Return true if this is a change in status.
markConstant(Constant * V)107 bool markConstant(Constant *V) {
108 if (getLatticeValue() == constant) { // Constant but not forcedconstant.
109 assert(getConstant() == V && "Marking constant with different value");
110 return false;
111 }
112
113 if (isUndefined()) {
114 Val.setInt(constant);
115 assert(V && "Marking constant with NULL");
116 Val.setPointer(V);
117 } else {
118 assert(getLatticeValue() == forcedconstant &&
119 "Cannot move from overdefined to constant!");
120 // Stay at forcedconstant if the constant is the same.
121 if (V == getConstant()) return false;
122
123 // Otherwise, we go to overdefined. Assumptions made based on the
124 // forced value are possibly wrong. Assuming this is another constant
125 // could expose a contradiction.
126 Val.setInt(overdefined);
127 }
128 return true;
129 }
130
131 /// getConstantInt - If this is a constant with a ConstantInt value, return it
132 /// otherwise return null.
getConstantInt() const133 ConstantInt *getConstantInt() const {
134 if (isConstant())
135 return dyn_cast<ConstantInt>(getConstant());
136 return 0;
137 }
138
markForcedConstant(Constant * V)139 void markForcedConstant(Constant *V) {
140 assert(isUndefined() && "Can't force a defined value!");
141 Val.setInt(forcedconstant);
142 Val.setPointer(V);
143 }
144 };
145 } // end anonymous namespace.
146
147
148 namespace {
149
150 //===----------------------------------------------------------------------===//
151 //
152 /// SCCPSolver - This class is a general purpose solver for Sparse Conditional
153 /// Constant Propagation.
154 ///
155 class SCCPSolver : public InstVisitor<SCCPSolver> {
156 const TargetData *TD;
157 const TargetLibraryInfo *TLI;
158 SmallPtrSet<BasicBlock*, 8> BBExecutable; // The BBs that are executable.
159 DenseMap<Value*, LatticeVal> ValueState; // The state each value is in.
160
161 /// StructValueState - This maintains ValueState for values that have
162 /// StructType, for example for formal arguments, calls, insertelement, etc.
163 ///
164 DenseMap<std::pair<Value*, unsigned>, LatticeVal> StructValueState;
165
166 /// GlobalValue - If we are tracking any values for the contents of a global
167 /// variable, we keep a mapping from the constant accessor to the element of
168 /// the global, to the currently known value. If the value becomes
169 /// overdefined, it's entry is simply removed from this map.
170 DenseMap<GlobalVariable*, LatticeVal> TrackedGlobals;
171
172 /// TrackedRetVals - If we are tracking arguments into and the return
173 /// value out of a function, it will have an entry in this map, indicating
174 /// what the known return value for the function is.
175 DenseMap<Function*, LatticeVal> TrackedRetVals;
176
177 /// TrackedMultipleRetVals - Same as TrackedRetVals, but used for functions
178 /// that return multiple values.
179 DenseMap<std::pair<Function*, unsigned>, LatticeVal> TrackedMultipleRetVals;
180
181 /// MRVFunctionsTracked - Each function in TrackedMultipleRetVals is
182 /// represented here for efficient lookup.
183 SmallPtrSet<Function*, 16> MRVFunctionsTracked;
184
185 /// TrackingIncomingArguments - This is the set of functions for whose
186 /// arguments we make optimistic assumptions about and try to prove as
187 /// constants.
188 SmallPtrSet<Function*, 16> TrackingIncomingArguments;
189
190 /// The reason for two worklists is that overdefined is the lowest state
191 /// on the lattice, and moving things to overdefined as fast as possible
192 /// makes SCCP converge much faster.
193 ///
194 /// By having a separate worklist, we accomplish this because everything
195 /// possibly overdefined will become overdefined at the soonest possible
196 /// point.
197 SmallVector<Value*, 64> OverdefinedInstWorkList;
198 SmallVector<Value*, 64> InstWorkList;
199
200
201 SmallVector<BasicBlock*, 64> BBWorkList; // The BasicBlock work list
202
203 /// KnownFeasibleEdges - Entries in this set are edges which have already had
204 /// PHI nodes retriggered.
205 typedef std::pair<BasicBlock*, BasicBlock*> Edge;
206 DenseSet<Edge> KnownFeasibleEdges;
207 public:
SCCPSolver(const TargetData * td,const TargetLibraryInfo * tli)208 SCCPSolver(const TargetData *td, const TargetLibraryInfo *tli)
209 : TD(td), TLI(tli) {}
210
211 /// MarkBlockExecutable - This method can be used by clients to mark all of
212 /// the blocks that are known to be intrinsically live in the processed unit.
213 ///
214 /// This returns true if the block was not considered live before.
MarkBlockExecutable(BasicBlock * BB)215 bool MarkBlockExecutable(BasicBlock *BB) {
216 if (!BBExecutable.insert(BB)) return false;
217 DEBUG(dbgs() << "Marking Block Executable: " << BB->getName() << "\n");
218 BBWorkList.push_back(BB); // Add the block to the work list!
219 return true;
220 }
221
222 /// TrackValueOfGlobalVariable - Clients can use this method to
223 /// inform the SCCPSolver that it should track loads and stores to the
224 /// specified global variable if it can. This is only legal to call if
225 /// performing Interprocedural SCCP.
TrackValueOfGlobalVariable(GlobalVariable * GV)226 void TrackValueOfGlobalVariable(GlobalVariable *GV) {
227 // We only track the contents of scalar globals.
228 if (GV->getType()->getElementType()->isSingleValueType()) {
229 LatticeVal &IV = TrackedGlobals[GV];
230 if (!isa<UndefValue>(GV->getInitializer()))
231 IV.markConstant(GV->getInitializer());
232 }
233 }
234
235 /// AddTrackedFunction - If the SCCP solver is supposed to track calls into
236 /// and out of the specified function (which cannot have its address taken),
237 /// this method must be called.
AddTrackedFunction(Function * F)238 void AddTrackedFunction(Function *F) {
239 // Add an entry, F -> undef.
240 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
241 MRVFunctionsTracked.insert(F);
242 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
243 TrackedMultipleRetVals.insert(std::make_pair(std::make_pair(F, i),
244 LatticeVal()));
245 } else
246 TrackedRetVals.insert(std::make_pair(F, LatticeVal()));
247 }
248
AddArgumentTrackedFunction(Function * F)249 void AddArgumentTrackedFunction(Function *F) {
250 TrackingIncomingArguments.insert(F);
251 }
252
253 /// Solve - Solve for constants and executable blocks.
254 ///
255 void Solve();
256
257 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
258 /// that branches on undef values cannot reach any of their successors.
259 /// However, this is not a safe assumption. After we solve dataflow, this
260 /// method should be use to handle this. If this returns true, the solver
261 /// should be rerun.
262 bool ResolvedUndefsIn(Function &F);
263
isBlockExecutable(BasicBlock * BB) const264 bool isBlockExecutable(BasicBlock *BB) const {
265 return BBExecutable.count(BB);
266 }
267
getLatticeValueFor(Value * V) const268 LatticeVal getLatticeValueFor(Value *V) const {
269 DenseMap<Value*, LatticeVal>::const_iterator I = ValueState.find(V);
270 assert(I != ValueState.end() && "V is not in valuemap!");
271 return I->second;
272 }
273
274 /*LatticeVal getStructLatticeValueFor(Value *V, unsigned i) const {
275 DenseMap<std::pair<Value*, unsigned>, LatticeVal>::const_iterator I =
276 StructValueState.find(std::make_pair(V, i));
277 assert(I != StructValueState.end() && "V is not in valuemap!");
278 return I->second;
279 }*/
280
281 /// getTrackedRetVals - Get the inferred return value map.
282 ///
getTrackedRetVals()283 const DenseMap<Function*, LatticeVal> &getTrackedRetVals() {
284 return TrackedRetVals;
285 }
286
287 /// getTrackedGlobals - Get and return the set of inferred initializers for
288 /// global variables.
getTrackedGlobals()289 const DenseMap<GlobalVariable*, LatticeVal> &getTrackedGlobals() {
290 return TrackedGlobals;
291 }
292
markOverdefined(Value * V)293 void markOverdefined(Value *V) {
294 assert(!V->getType()->isStructTy() && "Should use other method");
295 markOverdefined(ValueState[V], V);
296 }
297
298 /// markAnythingOverdefined - Mark the specified value overdefined. This
299 /// works with both scalars and structs.
markAnythingOverdefined(Value * V)300 void markAnythingOverdefined(Value *V) {
301 if (StructType *STy = dyn_cast<StructType>(V->getType()))
302 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
303 markOverdefined(getStructValueState(V, i), V);
304 else
305 markOverdefined(V);
306 }
307
308 private:
309 // markConstant - Make a value be marked as "constant". If the value
310 // is not already a constant, add it to the instruction work list so that
311 // the users of the instruction are updated later.
312 //
markConstant(LatticeVal & IV,Value * V,Constant * C)313 void markConstant(LatticeVal &IV, Value *V, Constant *C) {
314 if (!IV.markConstant(C)) return;
315 DEBUG(dbgs() << "markConstant: " << *C << ": " << *V << '\n');
316 if (IV.isOverdefined())
317 OverdefinedInstWorkList.push_back(V);
318 else
319 InstWorkList.push_back(V);
320 }
321
markConstant(Value * V,Constant * C)322 void markConstant(Value *V, Constant *C) {
323 assert(!V->getType()->isStructTy() && "Should use other method");
324 markConstant(ValueState[V], V, C);
325 }
326
markForcedConstant(Value * V,Constant * C)327 void markForcedConstant(Value *V, Constant *C) {
328 assert(!V->getType()->isStructTy() && "Should use other method");
329 LatticeVal &IV = ValueState[V];
330 IV.markForcedConstant(C);
331 DEBUG(dbgs() << "markForcedConstant: " << *C << ": " << *V << '\n');
332 if (IV.isOverdefined())
333 OverdefinedInstWorkList.push_back(V);
334 else
335 InstWorkList.push_back(V);
336 }
337
338
339 // markOverdefined - Make a value be marked as "overdefined". If the
340 // value is not already overdefined, add it to the overdefined instruction
341 // work list so that the users of the instruction are updated later.
markOverdefined(LatticeVal & IV,Value * V)342 void markOverdefined(LatticeVal &IV, Value *V) {
343 if (!IV.markOverdefined()) return;
344
345 DEBUG(dbgs() << "markOverdefined: ";
346 if (Function *F = dyn_cast<Function>(V))
347 dbgs() << "Function '" << F->getName() << "'\n";
348 else
349 dbgs() << *V << '\n');
350 // Only instructions go on the work list
351 OverdefinedInstWorkList.push_back(V);
352 }
353
mergeInValue(LatticeVal & IV,Value * V,LatticeVal MergeWithV)354 void mergeInValue(LatticeVal &IV, Value *V, LatticeVal MergeWithV) {
355 if (IV.isOverdefined() || MergeWithV.isUndefined())
356 return; // Noop.
357 if (MergeWithV.isOverdefined())
358 markOverdefined(IV, V);
359 else if (IV.isUndefined())
360 markConstant(IV, V, MergeWithV.getConstant());
361 else if (IV.getConstant() != MergeWithV.getConstant())
362 markOverdefined(IV, V);
363 }
364
mergeInValue(Value * V,LatticeVal MergeWithV)365 void mergeInValue(Value *V, LatticeVal MergeWithV) {
366 assert(!V->getType()->isStructTy() && "Should use other method");
367 mergeInValue(ValueState[V], V, MergeWithV);
368 }
369
370
371 /// getValueState - Return the LatticeVal object that corresponds to the
372 /// value. This function handles the case when the value hasn't been seen yet
373 /// by properly seeding constants etc.
getValueState(Value * V)374 LatticeVal &getValueState(Value *V) {
375 assert(!V->getType()->isStructTy() && "Should use getStructValueState");
376
377 std::pair<DenseMap<Value*, LatticeVal>::iterator, bool> I =
378 ValueState.insert(std::make_pair(V, LatticeVal()));
379 LatticeVal &LV = I.first->second;
380
381 if (!I.second)
382 return LV; // Common case, already in the map.
383
384 if (Constant *C = dyn_cast<Constant>(V)) {
385 // Undef values remain undefined.
386 if (!isa<UndefValue>(V))
387 LV.markConstant(C); // Constants are constant
388 }
389
390 // All others are underdefined by default.
391 return LV;
392 }
393
394 /// getStructValueState - Return the LatticeVal object that corresponds to the
395 /// value/field pair. This function handles the case when the value hasn't
396 /// been seen yet by properly seeding constants etc.
getStructValueState(Value * V,unsigned i)397 LatticeVal &getStructValueState(Value *V, unsigned i) {
398 assert(V->getType()->isStructTy() && "Should use getValueState");
399 assert(i < cast<StructType>(V->getType())->getNumElements() &&
400 "Invalid element #");
401
402 std::pair<DenseMap<std::pair<Value*, unsigned>, LatticeVal>::iterator,
403 bool> I = StructValueState.insert(
404 std::make_pair(std::make_pair(V, i), LatticeVal()));
405 LatticeVal &LV = I.first->second;
406
407 if (!I.second)
408 return LV; // Common case, already in the map.
409
410 if (Constant *C = dyn_cast<Constant>(V)) {
411 Constant *Elt = C->getAggregateElement(i);
412
413 if (Elt == 0)
414 LV.markOverdefined(); // Unknown sort of constant.
415 else if (isa<UndefValue>(Elt))
416 ; // Undef values remain undefined.
417 else
418 LV.markConstant(Elt); // Constants are constant.
419 }
420
421 // All others are underdefined by default.
422 return LV;
423 }
424
425
426 /// markEdgeExecutable - Mark a basic block as executable, adding it to the BB
427 /// work list if it is not already executable.
markEdgeExecutable(BasicBlock * Source,BasicBlock * Dest)428 void markEdgeExecutable(BasicBlock *Source, BasicBlock *Dest) {
429 if (!KnownFeasibleEdges.insert(Edge(Source, Dest)).second)
430 return; // This edge is already known to be executable!
431
432 if (!MarkBlockExecutable(Dest)) {
433 // If the destination is already executable, we just made an *edge*
434 // feasible that wasn't before. Revisit the PHI nodes in the block
435 // because they have potentially new operands.
436 DEBUG(dbgs() << "Marking Edge Executable: " << Source->getName()
437 << " -> " << Dest->getName() << "\n");
438
439 PHINode *PN;
440 for (BasicBlock::iterator I = Dest->begin();
441 (PN = dyn_cast<PHINode>(I)); ++I)
442 visitPHINode(*PN);
443 }
444 }
445
446 // getFeasibleSuccessors - Return a vector of booleans to indicate which
447 // successors are reachable from a given terminator instruction.
448 //
449 void getFeasibleSuccessors(TerminatorInst &TI, SmallVector<bool, 16> &Succs);
450
451 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
452 // block to the 'To' basic block is currently feasible.
453 //
454 bool isEdgeFeasible(BasicBlock *From, BasicBlock *To);
455
456 // OperandChangedState - This method is invoked on all of the users of an
457 // instruction that was just changed state somehow. Based on this
458 // information, we need to update the specified user of this instruction.
459 //
OperandChangedState(Instruction * I)460 void OperandChangedState(Instruction *I) {
461 if (BBExecutable.count(I->getParent())) // Inst is executable?
462 visit(*I);
463 }
464
465 private:
466 friend class InstVisitor<SCCPSolver>;
467
468 // visit implementations - Something changed in this instruction. Either an
469 // operand made a transition, or the instruction is newly executable. Change
470 // the value type of I to reflect these changes if appropriate.
471 void visitPHINode(PHINode &I);
472
473 // Terminators
474 void visitReturnInst(ReturnInst &I);
475 void visitTerminatorInst(TerminatorInst &TI);
476
477 void visitCastInst(CastInst &I);
478 void visitSelectInst(SelectInst &I);
479 void visitBinaryOperator(Instruction &I);
480 void visitCmpInst(CmpInst &I);
481 void visitExtractElementInst(ExtractElementInst &I);
482 void visitInsertElementInst(InsertElementInst &I);
483 void visitShuffleVectorInst(ShuffleVectorInst &I);
484 void visitExtractValueInst(ExtractValueInst &EVI);
485 void visitInsertValueInst(InsertValueInst &IVI);
visitLandingPadInst(LandingPadInst & I)486 void visitLandingPadInst(LandingPadInst &I) { markAnythingOverdefined(&I); }
487
488 // Instructions that cannot be folded away.
489 void visitStoreInst (StoreInst &I);
490 void visitLoadInst (LoadInst &I);
491 void visitGetElementPtrInst(GetElementPtrInst &I);
visitCallInst(CallInst & I)492 void visitCallInst (CallInst &I) {
493 visitCallSite(&I);
494 }
visitInvokeInst(InvokeInst & II)495 void visitInvokeInst (InvokeInst &II) {
496 visitCallSite(&II);
497 visitTerminatorInst(II);
498 }
499 void visitCallSite (CallSite CS);
visitResumeInst(TerminatorInst & I)500 void visitResumeInst (TerminatorInst &I) { /*returns void*/ }
visitUnwindInst(TerminatorInst & I)501 void visitUnwindInst (TerminatorInst &I) { /*returns void*/ }
visitUnreachableInst(TerminatorInst & I)502 void visitUnreachableInst(TerminatorInst &I) { /*returns void*/ }
visitFenceInst(FenceInst & I)503 void visitFenceInst (FenceInst &I) { /*returns void*/ }
visitAtomicCmpXchgInst(AtomicCmpXchgInst & I)504 void visitAtomicCmpXchgInst (AtomicCmpXchgInst &I) { markOverdefined(&I); }
visitAtomicRMWInst(AtomicRMWInst & I)505 void visitAtomicRMWInst (AtomicRMWInst &I) { markOverdefined(&I); }
visitAllocaInst(Instruction & I)506 void visitAllocaInst (Instruction &I) { markOverdefined(&I); }
visitVAArgInst(Instruction & I)507 void visitVAArgInst (Instruction &I) { markAnythingOverdefined(&I); }
508
visitInstruction(Instruction & I)509 void visitInstruction(Instruction &I) {
510 // If a new instruction is added to LLVM that we don't handle.
511 dbgs() << "SCCP: Don't know how to handle: " << I;
512 markAnythingOverdefined(&I); // Just in case
513 }
514 };
515
516 } // end anonymous namespace
517
518
519 // getFeasibleSuccessors - Return a vector of booleans to indicate which
520 // successors are reachable from a given terminator instruction.
521 //
getFeasibleSuccessors(TerminatorInst & TI,SmallVector<bool,16> & Succs)522 void SCCPSolver::getFeasibleSuccessors(TerminatorInst &TI,
523 SmallVector<bool, 16> &Succs) {
524 Succs.resize(TI.getNumSuccessors());
525 if (BranchInst *BI = dyn_cast<BranchInst>(&TI)) {
526 if (BI->isUnconditional()) {
527 Succs[0] = true;
528 return;
529 }
530
531 LatticeVal BCValue = getValueState(BI->getCondition());
532 ConstantInt *CI = BCValue.getConstantInt();
533 if (CI == 0) {
534 // Overdefined condition variables, and branches on unfoldable constant
535 // conditions, mean the branch could go either way.
536 if (!BCValue.isUndefined())
537 Succs[0] = Succs[1] = true;
538 return;
539 }
540
541 // Constant condition variables mean the branch can only go a single way.
542 Succs[CI->isZero()] = true;
543 return;
544 }
545
546 if (isa<InvokeInst>(TI)) {
547 // Invoke instructions successors are always executable.
548 Succs[0] = Succs[1] = true;
549 return;
550 }
551
552 if (SwitchInst *SI = dyn_cast<SwitchInst>(&TI)) {
553 if (!SI->getNumCases()) {
554 Succs[0] = true;
555 return;
556 }
557 LatticeVal SCValue = getValueState(SI->getCondition());
558 ConstantInt *CI = SCValue.getConstantInt();
559
560 if (CI == 0) { // Overdefined or undefined condition?
561 // All destinations are executable!
562 if (!SCValue.isUndefined())
563 Succs.assign(TI.getNumSuccessors(), true);
564 return;
565 }
566
567 Succs[SI->findCaseValue(CI).getSuccessorIndex()] = true;
568 return;
569 }
570
571 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
572 if (isa<IndirectBrInst>(&TI)) {
573 // Just mark all destinations executable!
574 Succs.assign(TI.getNumSuccessors(), true);
575 return;
576 }
577
578 #ifndef NDEBUG
579 dbgs() << "Unknown terminator instruction: " << TI << '\n';
580 #endif
581 llvm_unreachable("SCCP: Don't know how to handle this terminator!");
582 }
583
584
585 // isEdgeFeasible - Return true if the control flow edge from the 'From' basic
586 // block to the 'To' basic block is currently feasible.
587 //
isEdgeFeasible(BasicBlock * From,BasicBlock * To)588 bool SCCPSolver::isEdgeFeasible(BasicBlock *From, BasicBlock *To) {
589 assert(BBExecutable.count(To) && "Dest should always be alive!");
590
591 // Make sure the source basic block is executable!!
592 if (!BBExecutable.count(From)) return false;
593
594 // Check to make sure this edge itself is actually feasible now.
595 TerminatorInst *TI = From->getTerminator();
596 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
597 if (BI->isUnconditional())
598 return true;
599
600 LatticeVal BCValue = getValueState(BI->getCondition());
601
602 // Overdefined condition variables mean the branch could go either way,
603 // undef conditions mean that neither edge is feasible yet.
604 ConstantInt *CI = BCValue.getConstantInt();
605 if (CI == 0)
606 return !BCValue.isUndefined();
607
608 // Constant condition variables mean the branch can only go a single way.
609 return BI->getSuccessor(CI->isZero()) == To;
610 }
611
612 // Invoke instructions successors are always executable.
613 if (isa<InvokeInst>(TI))
614 return true;
615
616 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
617 if (SI->getNumCases() < 1)
618 return true;
619
620 LatticeVal SCValue = getValueState(SI->getCondition());
621 ConstantInt *CI = SCValue.getConstantInt();
622
623 if (CI == 0)
624 return !SCValue.isUndefined();
625
626 return SI->findCaseValue(CI).getCaseSuccessor() == To;
627 }
628
629 // Just mark all destinations executable!
630 // TODO: This could be improved if the operand is a [cast of a] BlockAddress.
631 if (isa<IndirectBrInst>(TI))
632 return true;
633
634 #ifndef NDEBUG
635 dbgs() << "Unknown terminator instruction: " << *TI << '\n';
636 #endif
637 llvm_unreachable(0);
638 }
639
640 // visit Implementations - Something changed in this instruction, either an
641 // operand made a transition, or the instruction is newly executable. Change
642 // the value type of I to reflect these changes if appropriate. This method
643 // makes sure to do the following actions:
644 //
645 // 1. If a phi node merges two constants in, and has conflicting value coming
646 // from different branches, or if the PHI node merges in an overdefined
647 // value, then the PHI node becomes overdefined.
648 // 2. If a phi node merges only constants in, and they all agree on value, the
649 // PHI node becomes a constant value equal to that.
650 // 3. If V <- x (op) y && isConstant(x) && isConstant(y) V = Constant
651 // 4. If V <- x (op) y && (isOverdefined(x) || isOverdefined(y)) V = Overdefined
652 // 5. If V <- MEM or V <- CALL or V <- (unknown) then V = Overdefined
653 // 6. If a conditional branch has a value that is constant, make the selected
654 // destination executable
655 // 7. If a conditional branch has a value that is overdefined, make all
656 // successors executable.
657 //
visitPHINode(PHINode & PN)658 void SCCPSolver::visitPHINode(PHINode &PN) {
659 // If this PN returns a struct, just mark the result overdefined.
660 // TODO: We could do a lot better than this if code actually uses this.
661 if (PN.getType()->isStructTy())
662 return markAnythingOverdefined(&PN);
663
664 if (getValueState(&PN).isOverdefined())
665 return; // Quick exit
666
667 // Super-extra-high-degree PHI nodes are unlikely to ever be marked constant,
668 // and slow us down a lot. Just mark them overdefined.
669 if (PN.getNumIncomingValues() > 64)
670 return markOverdefined(&PN);
671
672 // Look at all of the executable operands of the PHI node. If any of them
673 // are overdefined, the PHI becomes overdefined as well. If they are all
674 // constant, and they agree with each other, the PHI becomes the identical
675 // constant. If they are constant and don't agree, the PHI is overdefined.
676 // If there are no executable operands, the PHI remains undefined.
677 //
678 Constant *OperandVal = 0;
679 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
680 LatticeVal IV = getValueState(PN.getIncomingValue(i));
681 if (IV.isUndefined()) continue; // Doesn't influence PHI node.
682
683 if (!isEdgeFeasible(PN.getIncomingBlock(i), PN.getParent()))
684 continue;
685
686 if (IV.isOverdefined()) // PHI node becomes overdefined!
687 return markOverdefined(&PN);
688
689 if (OperandVal == 0) { // Grab the first value.
690 OperandVal = IV.getConstant();
691 continue;
692 }
693
694 // There is already a reachable operand. If we conflict with it,
695 // then the PHI node becomes overdefined. If we agree with it, we
696 // can continue on.
697
698 // Check to see if there are two different constants merging, if so, the PHI
699 // node is overdefined.
700 if (IV.getConstant() != OperandVal)
701 return markOverdefined(&PN);
702 }
703
704 // If we exited the loop, this means that the PHI node only has constant
705 // arguments that agree with each other(and OperandVal is the constant) or
706 // OperandVal is null because there are no defined incoming arguments. If
707 // this is the case, the PHI remains undefined.
708 //
709 if (OperandVal)
710 markConstant(&PN, OperandVal); // Acquire operand value
711 }
712
713
714
715
visitReturnInst(ReturnInst & I)716 void SCCPSolver::visitReturnInst(ReturnInst &I) {
717 if (I.getNumOperands() == 0) return; // ret void
718
719 Function *F = I.getParent()->getParent();
720 Value *ResultOp = I.getOperand(0);
721
722 // If we are tracking the return value of this function, merge it in.
723 if (!TrackedRetVals.empty() && !ResultOp->getType()->isStructTy()) {
724 DenseMap<Function*, LatticeVal>::iterator TFRVI =
725 TrackedRetVals.find(F);
726 if (TFRVI != TrackedRetVals.end()) {
727 mergeInValue(TFRVI->second, F, getValueState(ResultOp));
728 return;
729 }
730 }
731
732 // Handle functions that return multiple values.
733 if (!TrackedMultipleRetVals.empty()) {
734 if (StructType *STy = dyn_cast<StructType>(ResultOp->getType()))
735 if (MRVFunctionsTracked.count(F))
736 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
737 mergeInValue(TrackedMultipleRetVals[std::make_pair(F, i)], F,
738 getStructValueState(ResultOp, i));
739
740 }
741 }
742
visitTerminatorInst(TerminatorInst & TI)743 void SCCPSolver::visitTerminatorInst(TerminatorInst &TI) {
744 SmallVector<bool, 16> SuccFeasible;
745 getFeasibleSuccessors(TI, SuccFeasible);
746
747 BasicBlock *BB = TI.getParent();
748
749 // Mark all feasible successors executable.
750 for (unsigned i = 0, e = SuccFeasible.size(); i != e; ++i)
751 if (SuccFeasible[i])
752 markEdgeExecutable(BB, TI.getSuccessor(i));
753 }
754
visitCastInst(CastInst & I)755 void SCCPSolver::visitCastInst(CastInst &I) {
756 LatticeVal OpSt = getValueState(I.getOperand(0));
757 if (OpSt.isOverdefined()) // Inherit overdefinedness of operand
758 markOverdefined(&I);
759 else if (OpSt.isConstant()) // Propagate constant value
760 markConstant(&I, ConstantExpr::getCast(I.getOpcode(),
761 OpSt.getConstant(), I.getType()));
762 }
763
764
visitExtractValueInst(ExtractValueInst & EVI)765 void SCCPSolver::visitExtractValueInst(ExtractValueInst &EVI) {
766 // If this returns a struct, mark all elements over defined, we don't track
767 // structs in structs.
768 if (EVI.getType()->isStructTy())
769 return markAnythingOverdefined(&EVI);
770
771 // If this is extracting from more than one level of struct, we don't know.
772 if (EVI.getNumIndices() != 1)
773 return markOverdefined(&EVI);
774
775 Value *AggVal = EVI.getAggregateOperand();
776 if (AggVal->getType()->isStructTy()) {
777 unsigned i = *EVI.idx_begin();
778 LatticeVal EltVal = getStructValueState(AggVal, i);
779 mergeInValue(getValueState(&EVI), &EVI, EltVal);
780 } else {
781 // Otherwise, must be extracting from an array.
782 return markOverdefined(&EVI);
783 }
784 }
785
visitInsertValueInst(InsertValueInst & IVI)786 void SCCPSolver::visitInsertValueInst(InsertValueInst &IVI) {
787 StructType *STy = dyn_cast<StructType>(IVI.getType());
788 if (STy == 0)
789 return markOverdefined(&IVI);
790
791 // If this has more than one index, we can't handle it, drive all results to
792 // undef.
793 if (IVI.getNumIndices() != 1)
794 return markAnythingOverdefined(&IVI);
795
796 Value *Aggr = IVI.getAggregateOperand();
797 unsigned Idx = *IVI.idx_begin();
798
799 // Compute the result based on what we're inserting.
800 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
801 // This passes through all values that aren't the inserted element.
802 if (i != Idx) {
803 LatticeVal EltVal = getStructValueState(Aggr, i);
804 mergeInValue(getStructValueState(&IVI, i), &IVI, EltVal);
805 continue;
806 }
807
808 Value *Val = IVI.getInsertedValueOperand();
809 if (Val->getType()->isStructTy())
810 // We don't track structs in structs.
811 markOverdefined(getStructValueState(&IVI, i), &IVI);
812 else {
813 LatticeVal InVal = getValueState(Val);
814 mergeInValue(getStructValueState(&IVI, i), &IVI, InVal);
815 }
816 }
817 }
818
visitSelectInst(SelectInst & I)819 void SCCPSolver::visitSelectInst(SelectInst &I) {
820 // If this select returns a struct, just mark the result overdefined.
821 // TODO: We could do a lot better than this if code actually uses this.
822 if (I.getType()->isStructTy())
823 return markAnythingOverdefined(&I);
824
825 LatticeVal CondValue = getValueState(I.getCondition());
826 if (CondValue.isUndefined())
827 return;
828
829 if (ConstantInt *CondCB = CondValue.getConstantInt()) {
830 Value *OpVal = CondCB->isZero() ? I.getFalseValue() : I.getTrueValue();
831 mergeInValue(&I, getValueState(OpVal));
832 return;
833 }
834
835 // Otherwise, the condition is overdefined or a constant we can't evaluate.
836 // See if we can produce something better than overdefined based on the T/F
837 // value.
838 LatticeVal TVal = getValueState(I.getTrueValue());
839 LatticeVal FVal = getValueState(I.getFalseValue());
840
841 // select ?, C, C -> C.
842 if (TVal.isConstant() && FVal.isConstant() &&
843 TVal.getConstant() == FVal.getConstant())
844 return markConstant(&I, FVal.getConstant());
845
846 if (TVal.isUndefined()) // select ?, undef, X -> X.
847 return mergeInValue(&I, FVal);
848 if (FVal.isUndefined()) // select ?, X, undef -> X.
849 return mergeInValue(&I, TVal);
850 markOverdefined(&I);
851 }
852
853 // Handle Binary Operators.
visitBinaryOperator(Instruction & I)854 void SCCPSolver::visitBinaryOperator(Instruction &I) {
855 LatticeVal V1State = getValueState(I.getOperand(0));
856 LatticeVal V2State = getValueState(I.getOperand(1));
857
858 LatticeVal &IV = ValueState[&I];
859 if (IV.isOverdefined()) return;
860
861 if (V1State.isConstant() && V2State.isConstant())
862 return markConstant(IV, &I,
863 ConstantExpr::get(I.getOpcode(), V1State.getConstant(),
864 V2State.getConstant()));
865
866 // If something is undef, wait for it to resolve.
867 if (!V1State.isOverdefined() && !V2State.isOverdefined())
868 return;
869
870 // Otherwise, one of our operands is overdefined. Try to produce something
871 // better than overdefined with some tricks.
872
873 // If this is an AND or OR with 0 or -1, it doesn't matter that the other
874 // operand is overdefined.
875 if (I.getOpcode() == Instruction::And || I.getOpcode() == Instruction::Or) {
876 LatticeVal *NonOverdefVal = 0;
877 if (!V1State.isOverdefined())
878 NonOverdefVal = &V1State;
879 else if (!V2State.isOverdefined())
880 NonOverdefVal = &V2State;
881
882 if (NonOverdefVal) {
883 if (NonOverdefVal->isUndefined()) {
884 // Could annihilate value.
885 if (I.getOpcode() == Instruction::And)
886 markConstant(IV, &I, Constant::getNullValue(I.getType()));
887 else if (VectorType *PT = dyn_cast<VectorType>(I.getType()))
888 markConstant(IV, &I, Constant::getAllOnesValue(PT));
889 else
890 markConstant(IV, &I,
891 Constant::getAllOnesValue(I.getType()));
892 return;
893 }
894
895 if (I.getOpcode() == Instruction::And) {
896 // X and 0 = 0
897 if (NonOverdefVal->getConstant()->isNullValue())
898 return markConstant(IV, &I, NonOverdefVal->getConstant());
899 } else {
900 if (ConstantInt *CI = NonOverdefVal->getConstantInt())
901 if (CI->isAllOnesValue()) // X or -1 = -1
902 return markConstant(IV, &I, NonOverdefVal->getConstant());
903 }
904 }
905 }
906
907
908 markOverdefined(&I);
909 }
910
911 // Handle ICmpInst instruction.
visitCmpInst(CmpInst & I)912 void SCCPSolver::visitCmpInst(CmpInst &I) {
913 LatticeVal V1State = getValueState(I.getOperand(0));
914 LatticeVal V2State = getValueState(I.getOperand(1));
915
916 LatticeVal &IV = ValueState[&I];
917 if (IV.isOverdefined()) return;
918
919 if (V1State.isConstant() && V2State.isConstant())
920 return markConstant(IV, &I, ConstantExpr::getCompare(I.getPredicate(),
921 V1State.getConstant(),
922 V2State.getConstant()));
923
924 // If operands are still undefined, wait for it to resolve.
925 if (!V1State.isOverdefined() && !V2State.isOverdefined())
926 return;
927
928 markOverdefined(&I);
929 }
930
visitExtractElementInst(ExtractElementInst & I)931 void SCCPSolver::visitExtractElementInst(ExtractElementInst &I) {
932 // TODO : SCCP does not handle vectors properly.
933 return markOverdefined(&I);
934
935 #if 0
936 LatticeVal &ValState = getValueState(I.getOperand(0));
937 LatticeVal &IdxState = getValueState(I.getOperand(1));
938
939 if (ValState.isOverdefined() || IdxState.isOverdefined())
940 markOverdefined(&I);
941 else if(ValState.isConstant() && IdxState.isConstant())
942 markConstant(&I, ConstantExpr::getExtractElement(ValState.getConstant(),
943 IdxState.getConstant()));
944 #endif
945 }
946
visitInsertElementInst(InsertElementInst & I)947 void SCCPSolver::visitInsertElementInst(InsertElementInst &I) {
948 // TODO : SCCP does not handle vectors properly.
949 return markOverdefined(&I);
950 #if 0
951 LatticeVal &ValState = getValueState(I.getOperand(0));
952 LatticeVal &EltState = getValueState(I.getOperand(1));
953 LatticeVal &IdxState = getValueState(I.getOperand(2));
954
955 if (ValState.isOverdefined() || EltState.isOverdefined() ||
956 IdxState.isOverdefined())
957 markOverdefined(&I);
958 else if(ValState.isConstant() && EltState.isConstant() &&
959 IdxState.isConstant())
960 markConstant(&I, ConstantExpr::getInsertElement(ValState.getConstant(),
961 EltState.getConstant(),
962 IdxState.getConstant()));
963 else if (ValState.isUndefined() && EltState.isConstant() &&
964 IdxState.isConstant())
965 markConstant(&I,ConstantExpr::getInsertElement(UndefValue::get(I.getType()),
966 EltState.getConstant(),
967 IdxState.getConstant()));
968 #endif
969 }
970
visitShuffleVectorInst(ShuffleVectorInst & I)971 void SCCPSolver::visitShuffleVectorInst(ShuffleVectorInst &I) {
972 // TODO : SCCP does not handle vectors properly.
973 return markOverdefined(&I);
974 #if 0
975 LatticeVal &V1State = getValueState(I.getOperand(0));
976 LatticeVal &V2State = getValueState(I.getOperand(1));
977 LatticeVal &MaskState = getValueState(I.getOperand(2));
978
979 if (MaskState.isUndefined() ||
980 (V1State.isUndefined() && V2State.isUndefined()))
981 return; // Undefined output if mask or both inputs undefined.
982
983 if (V1State.isOverdefined() || V2State.isOverdefined() ||
984 MaskState.isOverdefined()) {
985 markOverdefined(&I);
986 } else {
987 // A mix of constant/undef inputs.
988 Constant *V1 = V1State.isConstant() ?
989 V1State.getConstant() : UndefValue::get(I.getType());
990 Constant *V2 = V2State.isConstant() ?
991 V2State.getConstant() : UndefValue::get(I.getType());
992 Constant *Mask = MaskState.isConstant() ?
993 MaskState.getConstant() : UndefValue::get(I.getOperand(2)->getType());
994 markConstant(&I, ConstantExpr::getShuffleVector(V1, V2, Mask));
995 }
996 #endif
997 }
998
999 // Handle getelementptr instructions. If all operands are constants then we
1000 // can turn this into a getelementptr ConstantExpr.
1001 //
visitGetElementPtrInst(GetElementPtrInst & I)1002 void SCCPSolver::visitGetElementPtrInst(GetElementPtrInst &I) {
1003 if (ValueState[&I].isOverdefined()) return;
1004
1005 SmallVector<Constant*, 8> Operands;
1006 Operands.reserve(I.getNumOperands());
1007
1008 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i) {
1009 LatticeVal State = getValueState(I.getOperand(i));
1010 if (State.isUndefined())
1011 return; // Operands are not resolved yet.
1012
1013 if (State.isOverdefined())
1014 return markOverdefined(&I);
1015
1016 assert(State.isConstant() && "Unknown state!");
1017 Operands.push_back(State.getConstant());
1018 }
1019
1020 Constant *Ptr = Operands[0];
1021 ArrayRef<Constant *> Indices(Operands.begin() + 1, Operands.end());
1022 markConstant(&I, ConstantExpr::getGetElementPtr(Ptr, Indices));
1023 }
1024
visitStoreInst(StoreInst & SI)1025 void SCCPSolver::visitStoreInst(StoreInst &SI) {
1026 // If this store is of a struct, ignore it.
1027 if (SI.getOperand(0)->getType()->isStructTy())
1028 return;
1029
1030 if (TrackedGlobals.empty() || !isa<GlobalVariable>(SI.getOperand(1)))
1031 return;
1032
1033 GlobalVariable *GV = cast<GlobalVariable>(SI.getOperand(1));
1034 DenseMap<GlobalVariable*, LatticeVal>::iterator I = TrackedGlobals.find(GV);
1035 if (I == TrackedGlobals.end() || I->second.isOverdefined()) return;
1036
1037 // Get the value we are storing into the global, then merge it.
1038 mergeInValue(I->second, GV, getValueState(SI.getOperand(0)));
1039 if (I->second.isOverdefined())
1040 TrackedGlobals.erase(I); // No need to keep tracking this!
1041 }
1042
1043
1044 // Handle load instructions. If the operand is a constant pointer to a constant
1045 // global, we can replace the load with the loaded constant value!
visitLoadInst(LoadInst & I)1046 void SCCPSolver::visitLoadInst(LoadInst &I) {
1047 // If this load is of a struct, just mark the result overdefined.
1048 if (I.getType()->isStructTy())
1049 return markAnythingOverdefined(&I);
1050
1051 LatticeVal PtrVal = getValueState(I.getOperand(0));
1052 if (PtrVal.isUndefined()) return; // The pointer is not resolved yet!
1053
1054 LatticeVal &IV = ValueState[&I];
1055 if (IV.isOverdefined()) return;
1056
1057 if (!PtrVal.isConstant() || I.isVolatile())
1058 return markOverdefined(IV, &I);
1059
1060 Constant *Ptr = PtrVal.getConstant();
1061
1062 // load null -> null
1063 if (isa<ConstantPointerNull>(Ptr) && I.getPointerAddressSpace() == 0)
1064 return markConstant(IV, &I, Constant::getNullValue(I.getType()));
1065
1066 // Transform load (constant global) into the value loaded.
1067 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
1068 if (!TrackedGlobals.empty()) {
1069 // If we are tracking this global, merge in the known value for it.
1070 DenseMap<GlobalVariable*, LatticeVal>::iterator It =
1071 TrackedGlobals.find(GV);
1072 if (It != TrackedGlobals.end()) {
1073 mergeInValue(IV, &I, It->second);
1074 return;
1075 }
1076 }
1077 }
1078
1079 // Transform load from a constant into a constant if possible.
1080 if (Constant *C = ConstantFoldLoadFromConstPtr(Ptr, TD))
1081 return markConstant(IV, &I, C);
1082
1083 // Otherwise we cannot say for certain what value this load will produce.
1084 // Bail out.
1085 markOverdefined(IV, &I);
1086 }
1087
visitCallSite(CallSite CS)1088 void SCCPSolver::visitCallSite(CallSite CS) {
1089 Function *F = CS.getCalledFunction();
1090 Instruction *I = CS.getInstruction();
1091
1092 // The common case is that we aren't tracking the callee, either because we
1093 // are not doing interprocedural analysis or the callee is indirect, or is
1094 // external. Handle these cases first.
1095 if (F == 0 || F->isDeclaration()) {
1096 CallOverdefined:
1097 // Void return and not tracking callee, just bail.
1098 if (I->getType()->isVoidTy()) return;
1099
1100 // Otherwise, if we have a single return value case, and if the function is
1101 // a declaration, maybe we can constant fold it.
1102 if (F && F->isDeclaration() && !I->getType()->isStructTy() &&
1103 canConstantFoldCallTo(F)) {
1104
1105 SmallVector<Constant*, 8> Operands;
1106 for (CallSite::arg_iterator AI = CS.arg_begin(), E = CS.arg_end();
1107 AI != E; ++AI) {
1108 LatticeVal State = getValueState(*AI);
1109
1110 if (State.isUndefined())
1111 return; // Operands are not resolved yet.
1112 if (State.isOverdefined())
1113 return markOverdefined(I);
1114 assert(State.isConstant() && "Unknown state!");
1115 Operands.push_back(State.getConstant());
1116 }
1117
1118 // If we can constant fold this, mark the result of the call as a
1119 // constant.
1120 if (Constant *C = ConstantFoldCall(F, Operands, TLI))
1121 return markConstant(I, C);
1122 }
1123
1124 // Otherwise, we don't know anything about this call, mark it overdefined.
1125 return markAnythingOverdefined(I);
1126 }
1127
1128 // If this is a local function that doesn't have its address taken, mark its
1129 // entry block executable and merge in the actual arguments to the call into
1130 // the formal arguments of the function.
1131 if (!TrackingIncomingArguments.empty() && TrackingIncomingArguments.count(F)){
1132 MarkBlockExecutable(F->begin());
1133
1134 // Propagate information from this call site into the callee.
1135 CallSite::arg_iterator CAI = CS.arg_begin();
1136 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1137 AI != E; ++AI, ++CAI) {
1138 // If this argument is byval, and if the function is not readonly, there
1139 // will be an implicit copy formed of the input aggregate.
1140 if (AI->hasByValAttr() && !F->onlyReadsMemory()) {
1141 markOverdefined(AI);
1142 continue;
1143 }
1144
1145 if (StructType *STy = dyn_cast<StructType>(AI->getType())) {
1146 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1147 LatticeVal CallArg = getStructValueState(*CAI, i);
1148 mergeInValue(getStructValueState(AI, i), AI, CallArg);
1149 }
1150 } else {
1151 mergeInValue(AI, getValueState(*CAI));
1152 }
1153 }
1154 }
1155
1156 // If this is a single/zero retval case, see if we're tracking the function.
1157 if (StructType *STy = dyn_cast<StructType>(F->getReturnType())) {
1158 if (!MRVFunctionsTracked.count(F))
1159 goto CallOverdefined; // Not tracking this callee.
1160
1161 // If we are tracking this callee, propagate the result of the function
1162 // into this call site.
1163 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1164 mergeInValue(getStructValueState(I, i), I,
1165 TrackedMultipleRetVals[std::make_pair(F, i)]);
1166 } else {
1167 DenseMap<Function*, LatticeVal>::iterator TFRVI = TrackedRetVals.find(F);
1168 if (TFRVI == TrackedRetVals.end())
1169 goto CallOverdefined; // Not tracking this callee.
1170
1171 // If so, propagate the return value of the callee into this call result.
1172 mergeInValue(I, TFRVI->second);
1173 }
1174 }
1175
Solve()1176 void SCCPSolver::Solve() {
1177 // Process the work lists until they are empty!
1178 while (!BBWorkList.empty() || !InstWorkList.empty() ||
1179 !OverdefinedInstWorkList.empty()) {
1180 // Process the overdefined instruction's work list first, which drives other
1181 // things to overdefined more quickly.
1182 while (!OverdefinedInstWorkList.empty()) {
1183 Value *I = OverdefinedInstWorkList.pop_back_val();
1184
1185 DEBUG(dbgs() << "\nPopped off OI-WL: " << *I << '\n');
1186
1187 // "I" got into the work list because it either made the transition from
1188 // bottom to constant
1189 //
1190 // Anything on this worklist that is overdefined need not be visited
1191 // since all of its users will have already been marked as overdefined
1192 // Update all of the users of this instruction's value.
1193 //
1194 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1195 UI != E; ++UI)
1196 if (Instruction *I = dyn_cast<Instruction>(*UI))
1197 OperandChangedState(I);
1198 }
1199
1200 // Process the instruction work list.
1201 while (!InstWorkList.empty()) {
1202 Value *I = InstWorkList.pop_back_val();
1203
1204 DEBUG(dbgs() << "\nPopped off I-WL: " << *I << '\n');
1205
1206 // "I" got into the work list because it made the transition from undef to
1207 // constant.
1208 //
1209 // Anything on this worklist that is overdefined need not be visited
1210 // since all of its users will have already been marked as overdefined.
1211 // Update all of the users of this instruction's value.
1212 //
1213 if (I->getType()->isStructTy() || !getValueState(I).isOverdefined())
1214 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1215 UI != E; ++UI)
1216 if (Instruction *I = dyn_cast<Instruction>(*UI))
1217 OperandChangedState(I);
1218 }
1219
1220 // Process the basic block work list.
1221 while (!BBWorkList.empty()) {
1222 BasicBlock *BB = BBWorkList.back();
1223 BBWorkList.pop_back();
1224
1225 DEBUG(dbgs() << "\nPopped off BBWL: " << *BB << '\n');
1226
1227 // Notify all instructions in this basic block that they are newly
1228 // executable.
1229 visit(BB);
1230 }
1231 }
1232 }
1233
1234 /// ResolvedUndefsIn - While solving the dataflow for a function, we assume
1235 /// that branches on undef values cannot reach any of their successors.
1236 /// However, this is not a safe assumption. After we solve dataflow, this
1237 /// method should be use to handle this. If this returns true, the solver
1238 /// should be rerun.
1239 ///
1240 /// This method handles this by finding an unresolved branch and marking it one
1241 /// of the edges from the block as being feasible, even though the condition
1242 /// doesn't say it would otherwise be. This allows SCCP to find the rest of the
1243 /// CFG and only slightly pessimizes the analysis results (by marking one,
1244 /// potentially infeasible, edge feasible). This cannot usefully modify the
1245 /// constraints on the condition of the branch, as that would impact other users
1246 /// of the value.
1247 ///
1248 /// This scan also checks for values that use undefs, whose results are actually
1249 /// defined. For example, 'zext i8 undef to i32' should produce all zeros
1250 /// conservatively, as "(zext i8 X -> i32) & 0xFF00" must always return zero,
1251 /// even if X isn't defined.
ResolvedUndefsIn(Function & F)1252 bool SCCPSolver::ResolvedUndefsIn(Function &F) {
1253 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1254 if (!BBExecutable.count(BB))
1255 continue;
1256
1257 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
1258 // Look for instructions which produce undef values.
1259 if (I->getType()->isVoidTy()) continue;
1260
1261 if (StructType *STy = dyn_cast<StructType>(I->getType())) {
1262 // Only a few things that can be structs matter for undef.
1263
1264 // Tracked calls must never be marked overdefined in ResolvedUndefsIn.
1265 if (CallSite CS = CallSite(I))
1266 if (Function *F = CS.getCalledFunction())
1267 if (MRVFunctionsTracked.count(F))
1268 continue;
1269
1270 // extractvalue and insertvalue don't need to be marked; they are
1271 // tracked as precisely as their operands.
1272 if (isa<ExtractValueInst>(I) || isa<InsertValueInst>(I))
1273 continue;
1274
1275 // Send the results of everything else to overdefined. We could be
1276 // more precise than this but it isn't worth bothering.
1277 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1278 LatticeVal &LV = getStructValueState(I, i);
1279 if (LV.isUndefined())
1280 markOverdefined(LV, I);
1281 }
1282 continue;
1283 }
1284
1285 LatticeVal &LV = getValueState(I);
1286 if (!LV.isUndefined()) continue;
1287
1288 // extractvalue is safe; check here because the argument is a struct.
1289 if (isa<ExtractValueInst>(I))
1290 continue;
1291
1292 // Compute the operand LatticeVals, for convenience below.
1293 // Anything taking a struct is conservatively assumed to require
1294 // overdefined markings.
1295 if (I->getOperand(0)->getType()->isStructTy()) {
1296 markOverdefined(I);
1297 return true;
1298 }
1299 LatticeVal Op0LV = getValueState(I->getOperand(0));
1300 LatticeVal Op1LV;
1301 if (I->getNumOperands() == 2) {
1302 if (I->getOperand(1)->getType()->isStructTy()) {
1303 markOverdefined(I);
1304 return true;
1305 }
1306
1307 Op1LV = getValueState(I->getOperand(1));
1308 }
1309 // If this is an instructions whose result is defined even if the input is
1310 // not fully defined, propagate the information.
1311 Type *ITy = I->getType();
1312 switch (I->getOpcode()) {
1313 case Instruction::Add:
1314 case Instruction::Sub:
1315 case Instruction::Trunc:
1316 case Instruction::FPTrunc:
1317 case Instruction::BitCast:
1318 break; // Any undef -> undef
1319 case Instruction::FSub:
1320 case Instruction::FAdd:
1321 case Instruction::FMul:
1322 case Instruction::FDiv:
1323 case Instruction::FRem:
1324 // Floating-point binary operation: be conservative.
1325 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1326 markForcedConstant(I, Constant::getNullValue(ITy));
1327 else
1328 markOverdefined(I);
1329 return true;
1330 case Instruction::ZExt:
1331 case Instruction::SExt:
1332 case Instruction::FPToUI:
1333 case Instruction::FPToSI:
1334 case Instruction::FPExt:
1335 case Instruction::PtrToInt:
1336 case Instruction::IntToPtr:
1337 case Instruction::SIToFP:
1338 case Instruction::UIToFP:
1339 // undef -> 0; some outputs are impossible
1340 markForcedConstant(I, Constant::getNullValue(ITy));
1341 return true;
1342 case Instruction::Mul:
1343 case Instruction::And:
1344 // Both operands undef -> undef
1345 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1346 break;
1347 // undef * X -> 0. X could be zero.
1348 // undef & X -> 0. X could be zero.
1349 markForcedConstant(I, Constant::getNullValue(ITy));
1350 return true;
1351
1352 case Instruction::Or:
1353 // Both operands undef -> undef
1354 if (Op0LV.isUndefined() && Op1LV.isUndefined())
1355 break;
1356 // undef | X -> -1. X could be -1.
1357 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1358 return true;
1359
1360 case Instruction::Xor:
1361 // undef ^ undef -> 0; strictly speaking, this is not strictly
1362 // necessary, but we try to be nice to people who expect this
1363 // behavior in simple cases
1364 if (Op0LV.isUndefined() && Op1LV.isUndefined()) {
1365 markForcedConstant(I, Constant::getNullValue(ITy));
1366 return true;
1367 }
1368 // undef ^ X -> undef
1369 break;
1370
1371 case Instruction::SDiv:
1372 case Instruction::UDiv:
1373 case Instruction::SRem:
1374 case Instruction::URem:
1375 // X / undef -> undef. No change.
1376 // X % undef -> undef. No change.
1377 if (Op1LV.isUndefined()) break;
1378
1379 // undef / X -> 0. X could be maxint.
1380 // undef % X -> 0. X could be 1.
1381 markForcedConstant(I, Constant::getNullValue(ITy));
1382 return true;
1383
1384 case Instruction::AShr:
1385 // X >>a undef -> undef.
1386 if (Op1LV.isUndefined()) break;
1387
1388 // undef >>a X -> all ones
1389 markForcedConstant(I, Constant::getAllOnesValue(ITy));
1390 return true;
1391 case Instruction::LShr:
1392 case Instruction::Shl:
1393 // X << undef -> undef.
1394 // X >> undef -> undef.
1395 if (Op1LV.isUndefined()) break;
1396
1397 // undef << X -> 0
1398 // undef >> X -> 0
1399 markForcedConstant(I, Constant::getNullValue(ITy));
1400 return true;
1401 case Instruction::Select:
1402 Op1LV = getValueState(I->getOperand(1));
1403 // undef ? X : Y -> X or Y. There could be commonality between X/Y.
1404 if (Op0LV.isUndefined()) {
1405 if (!Op1LV.isConstant()) // Pick the constant one if there is any.
1406 Op1LV = getValueState(I->getOperand(2));
1407 } else if (Op1LV.isUndefined()) {
1408 // c ? undef : undef -> undef. No change.
1409 Op1LV = getValueState(I->getOperand(2));
1410 if (Op1LV.isUndefined())
1411 break;
1412 // Otherwise, c ? undef : x -> x.
1413 } else {
1414 // Leave Op1LV as Operand(1)'s LatticeValue.
1415 }
1416
1417 if (Op1LV.isConstant())
1418 markForcedConstant(I, Op1LV.getConstant());
1419 else
1420 markOverdefined(I);
1421 return true;
1422 case Instruction::Load:
1423 // A load here means one of two things: a load of undef from a global,
1424 // a load from an unknown pointer. Either way, having it return undef
1425 // is okay.
1426 break;
1427 case Instruction::ICmp:
1428 // X == undef -> undef. Other comparisons get more complicated.
1429 if (cast<ICmpInst>(I)->isEquality())
1430 break;
1431 markOverdefined(I);
1432 return true;
1433 case Instruction::Call:
1434 case Instruction::Invoke: {
1435 // There are two reasons a call can have an undef result
1436 // 1. It could be tracked.
1437 // 2. It could be constant-foldable.
1438 // Because of the way we solve return values, tracked calls must
1439 // never be marked overdefined in ResolvedUndefsIn.
1440 if (Function *F = CallSite(I).getCalledFunction())
1441 if (TrackedRetVals.count(F))
1442 break;
1443
1444 // If the call is constant-foldable, we mark it overdefined because
1445 // we do not know what return values are valid.
1446 markOverdefined(I);
1447 return true;
1448 }
1449 default:
1450 // If we don't know what should happen here, conservatively mark it
1451 // overdefined.
1452 markOverdefined(I);
1453 return true;
1454 }
1455 }
1456
1457 // Check to see if we have a branch or switch on an undefined value. If so
1458 // we force the branch to go one way or the other to make the successor
1459 // values live. It doesn't really matter which way we force it.
1460 TerminatorInst *TI = BB->getTerminator();
1461 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1462 if (!BI->isConditional()) continue;
1463 if (!getValueState(BI->getCondition()).isUndefined())
1464 continue;
1465
1466 // If the input to SCCP is actually branch on undef, fix the undef to
1467 // false.
1468 if (isa<UndefValue>(BI->getCondition())) {
1469 BI->setCondition(ConstantInt::getFalse(BI->getContext()));
1470 markEdgeExecutable(BB, TI->getSuccessor(1));
1471 return true;
1472 }
1473
1474 // Otherwise, it is a branch on a symbolic value which is currently
1475 // considered to be undef. Handle this by forcing the input value to the
1476 // branch to false.
1477 markForcedConstant(BI->getCondition(),
1478 ConstantInt::getFalse(TI->getContext()));
1479 return true;
1480 }
1481
1482 if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1483 if (!SI->getNumCases())
1484 continue;
1485 if (!getValueState(SI->getCondition()).isUndefined())
1486 continue;
1487
1488 // If the input to SCCP is actually switch on undef, fix the undef to
1489 // the first constant.
1490 if (isa<UndefValue>(SI->getCondition())) {
1491 SI->setCondition(SI->case_begin().getCaseValue());
1492 markEdgeExecutable(BB, SI->case_begin().getCaseSuccessor());
1493 return true;
1494 }
1495
1496 markForcedConstant(SI->getCondition(), SI->case_begin().getCaseValue());
1497 return true;
1498 }
1499 }
1500
1501 return false;
1502 }
1503
1504
1505 namespace {
1506 //===--------------------------------------------------------------------===//
1507 //
1508 /// SCCP Class - This class uses the SCCPSolver to implement a per-function
1509 /// Sparse Conditional Constant Propagator.
1510 ///
1511 struct SCCP : public FunctionPass {
getAnalysisUsage__anon42f54f640311::SCCP1512 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1513 AU.addRequired<TargetLibraryInfo>();
1514 }
1515 static char ID; // Pass identification, replacement for typeid
SCCP__anon42f54f640311::SCCP1516 SCCP() : FunctionPass(ID) {
1517 initializeSCCPPass(*PassRegistry::getPassRegistry());
1518 }
1519
1520 // runOnFunction - Run the Sparse Conditional Constant Propagation
1521 // algorithm, and return true if the function was modified.
1522 //
1523 bool runOnFunction(Function &F);
1524 };
1525 } // end anonymous namespace
1526
1527 char SCCP::ID = 0;
1528 INITIALIZE_PASS(SCCP, "sccp",
1529 "Sparse Conditional Constant Propagation", false, false)
1530
1531 // createSCCPPass - This is the public interface to this file.
createSCCPPass()1532 FunctionPass *llvm::createSCCPPass() {
1533 return new SCCP();
1534 }
1535
DeleteInstructionInBlock(BasicBlock * BB)1536 static void DeleteInstructionInBlock(BasicBlock *BB) {
1537 DEBUG(dbgs() << " BasicBlock Dead:" << *BB);
1538 ++NumDeadBlocks;
1539
1540 // Check to see if there are non-terminating instructions to delete.
1541 if (isa<TerminatorInst>(BB->begin()))
1542 return;
1543
1544 // Delete the instructions backwards, as it has a reduced likelihood of having
1545 // to update as many def-use and use-def chains.
1546 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1547 while (EndInst != BB->begin()) {
1548 // Delete the next to last instruction.
1549 BasicBlock::iterator I = EndInst;
1550 Instruction *Inst = --I;
1551 if (!Inst->use_empty())
1552 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1553 if (isa<LandingPadInst>(Inst)) {
1554 EndInst = Inst;
1555 continue;
1556 }
1557 BB->getInstList().erase(Inst);
1558 ++NumInstRemoved;
1559 }
1560 }
1561
1562 // runOnFunction() - Run the Sparse Conditional Constant Propagation algorithm,
1563 // and return true if the function was modified.
1564 //
runOnFunction(Function & F)1565 bool SCCP::runOnFunction(Function &F) {
1566 DEBUG(dbgs() << "SCCP on function '" << F.getName() << "'\n");
1567 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1568 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1569 SCCPSolver Solver(TD, TLI);
1570
1571 // Mark the first block of the function as being executable.
1572 Solver.MarkBlockExecutable(F.begin());
1573
1574 // Mark all arguments to the function as being overdefined.
1575 for (Function::arg_iterator AI = F.arg_begin(), E = F.arg_end(); AI != E;++AI)
1576 Solver.markAnythingOverdefined(AI);
1577
1578 // Solve for constants.
1579 bool ResolvedUndefs = true;
1580 while (ResolvedUndefs) {
1581 Solver.Solve();
1582 DEBUG(dbgs() << "RESOLVING UNDEFs\n");
1583 ResolvedUndefs = Solver.ResolvedUndefsIn(F);
1584 }
1585
1586 bool MadeChanges = false;
1587
1588 // If we decided that there are basic blocks that are dead in this function,
1589 // delete their contents now. Note that we cannot actually delete the blocks,
1590 // as we cannot modify the CFG of the function.
1591
1592 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1593 if (!Solver.isBlockExecutable(BB)) {
1594 DeleteInstructionInBlock(BB);
1595 MadeChanges = true;
1596 continue;
1597 }
1598
1599 // Iterate over all of the instructions in a function, replacing them with
1600 // constants if we have found them to be of constant values.
1601 //
1602 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1603 Instruction *Inst = BI++;
1604 if (Inst->getType()->isVoidTy() || isa<TerminatorInst>(Inst))
1605 continue;
1606
1607 // TODO: Reconstruct structs from their elements.
1608 if (Inst->getType()->isStructTy())
1609 continue;
1610
1611 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1612 if (IV.isOverdefined())
1613 continue;
1614
1615 Constant *Const = IV.isConstant()
1616 ? IV.getConstant() : UndefValue::get(Inst->getType());
1617 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1618
1619 // Replaces all of the uses of a variable with uses of the constant.
1620 Inst->replaceAllUsesWith(Const);
1621
1622 // Delete the instruction.
1623 Inst->eraseFromParent();
1624
1625 // Hey, we just changed something!
1626 MadeChanges = true;
1627 ++NumInstRemoved;
1628 }
1629 }
1630
1631 return MadeChanges;
1632 }
1633
1634 namespace {
1635 //===--------------------------------------------------------------------===//
1636 //
1637 /// IPSCCP Class - This class implements interprocedural Sparse Conditional
1638 /// Constant Propagation.
1639 ///
1640 struct IPSCCP : public ModulePass {
getAnalysisUsage__anon42f54f640411::IPSCCP1641 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1642 AU.addRequired<TargetLibraryInfo>();
1643 }
1644 static char ID;
IPSCCP__anon42f54f640411::IPSCCP1645 IPSCCP() : ModulePass(ID) {
1646 initializeIPSCCPPass(*PassRegistry::getPassRegistry());
1647 }
1648 bool runOnModule(Module &M);
1649 };
1650 } // end anonymous namespace
1651
1652 char IPSCCP::ID = 0;
1653 INITIALIZE_PASS_BEGIN(IPSCCP, "ipsccp",
1654 "Interprocedural Sparse Conditional Constant Propagation",
1655 false, false)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)1656 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
1657 INITIALIZE_PASS_END(IPSCCP, "ipsccp",
1658 "Interprocedural Sparse Conditional Constant Propagation",
1659 false, false)
1660
1661 // createIPSCCPPass - This is the public interface to this file.
1662 ModulePass *llvm::createIPSCCPPass() {
1663 return new IPSCCP();
1664 }
1665
1666
AddressIsTaken(const GlobalValue * GV)1667 static bool AddressIsTaken(const GlobalValue *GV) {
1668 // Delete any dead constantexpr klingons.
1669 GV->removeDeadConstantUsers();
1670
1671 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1672 UI != E; ++UI) {
1673 const User *U = *UI;
1674 if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
1675 if (SI->getOperand(0) == GV || SI->isVolatile())
1676 return true; // Storing addr of GV.
1677 } else if (isa<InvokeInst>(U) || isa<CallInst>(U)) {
1678 // Make sure we are calling the function, not passing the address.
1679 ImmutableCallSite CS(cast<Instruction>(U));
1680 if (!CS.isCallee(UI))
1681 return true;
1682 } else if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
1683 if (LI->isVolatile())
1684 return true;
1685 } else if (isa<BlockAddress>(U)) {
1686 // blockaddress doesn't take the address of the function, it takes addr
1687 // of label.
1688 } else {
1689 return true;
1690 }
1691 }
1692 return false;
1693 }
1694
runOnModule(Module & M)1695 bool IPSCCP::runOnModule(Module &M) {
1696 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1697 const TargetLibraryInfo *TLI = &getAnalysis<TargetLibraryInfo>();
1698 SCCPSolver Solver(TD, TLI);
1699
1700 // AddressTakenFunctions - This set keeps track of the address-taken functions
1701 // that are in the input. As IPSCCP runs through and simplifies code,
1702 // functions that were address taken can end up losing their
1703 // address-taken-ness. Because of this, we keep track of their addresses from
1704 // the first pass so we can use them for the later simplification pass.
1705 SmallPtrSet<Function*, 32> AddressTakenFunctions;
1706
1707 // Loop over all functions, marking arguments to those with their addresses
1708 // taken or that are external as overdefined.
1709 //
1710 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1711 if (F->isDeclaration())
1712 continue;
1713
1714 // If this is a strong or ODR definition of this function, then we can
1715 // propagate information about its result into callsites of it.
1716 if (!F->mayBeOverridden())
1717 Solver.AddTrackedFunction(F);
1718
1719 // If this function only has direct calls that we can see, we can track its
1720 // arguments and return value aggressively, and can assume it is not called
1721 // unless we see evidence to the contrary.
1722 if (F->hasLocalLinkage()) {
1723 if (AddressIsTaken(F))
1724 AddressTakenFunctions.insert(F);
1725 else {
1726 Solver.AddArgumentTrackedFunction(F);
1727 continue;
1728 }
1729 }
1730
1731 // Assume the function is called.
1732 Solver.MarkBlockExecutable(F->begin());
1733
1734 // Assume nothing about the incoming arguments.
1735 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1736 AI != E; ++AI)
1737 Solver.markAnythingOverdefined(AI);
1738 }
1739
1740 // Loop over global variables. We inform the solver about any internal global
1741 // variables that do not have their 'addresses taken'. If they don't have
1742 // their addresses taken, we can propagate constants through them.
1743 for (Module::global_iterator G = M.global_begin(), E = M.global_end();
1744 G != E; ++G)
1745 if (!G->isConstant() && G->hasLocalLinkage() && !AddressIsTaken(G))
1746 Solver.TrackValueOfGlobalVariable(G);
1747
1748 // Solve for constants.
1749 bool ResolvedUndefs = true;
1750 while (ResolvedUndefs) {
1751 Solver.Solve();
1752
1753 DEBUG(dbgs() << "RESOLVING UNDEFS\n");
1754 ResolvedUndefs = false;
1755 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F)
1756 ResolvedUndefs |= Solver.ResolvedUndefsIn(*F);
1757 }
1758
1759 bool MadeChanges = false;
1760
1761 // Iterate over all of the instructions in the module, replacing them with
1762 // constants if we have found them to be of constant values.
1763 //
1764 SmallVector<BasicBlock*, 512> BlocksToErase;
1765
1766 for (Module::iterator F = M.begin(), E = M.end(); F != E; ++F) {
1767 if (Solver.isBlockExecutable(F->begin())) {
1768 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end();
1769 AI != E; ++AI) {
1770 if (AI->use_empty() || AI->getType()->isStructTy()) continue;
1771
1772 // TODO: Could use getStructLatticeValueFor to find out if the entire
1773 // result is a constant and replace it entirely if so.
1774
1775 LatticeVal IV = Solver.getLatticeValueFor(AI);
1776 if (IV.isOverdefined()) continue;
1777
1778 Constant *CST = IV.isConstant() ?
1779 IV.getConstant() : UndefValue::get(AI->getType());
1780 DEBUG(dbgs() << "*** Arg " << *AI << " = " << *CST <<"\n");
1781
1782 // Replaces all of the uses of a variable with uses of the
1783 // constant.
1784 AI->replaceAllUsesWith(CST);
1785 ++IPNumArgsElimed;
1786 }
1787 }
1788
1789 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB) {
1790 if (!Solver.isBlockExecutable(BB)) {
1791 DeleteInstructionInBlock(BB);
1792 MadeChanges = true;
1793
1794 TerminatorInst *TI = BB->getTerminator();
1795 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i) {
1796 BasicBlock *Succ = TI->getSuccessor(i);
1797 if (!Succ->empty() && isa<PHINode>(Succ->begin()))
1798 TI->getSuccessor(i)->removePredecessor(BB);
1799 }
1800 if (!TI->use_empty())
1801 TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
1802 TI->eraseFromParent();
1803
1804 if (&*BB != &F->front())
1805 BlocksToErase.push_back(BB);
1806 else
1807 new UnreachableInst(M.getContext(), BB);
1808 continue;
1809 }
1810
1811 for (BasicBlock::iterator BI = BB->begin(), E = BB->end(); BI != E; ) {
1812 Instruction *Inst = BI++;
1813 if (Inst->getType()->isVoidTy() || Inst->getType()->isStructTy())
1814 continue;
1815
1816 // TODO: Could use getStructLatticeValueFor to find out if the entire
1817 // result is a constant and replace it entirely if so.
1818
1819 LatticeVal IV = Solver.getLatticeValueFor(Inst);
1820 if (IV.isOverdefined())
1821 continue;
1822
1823 Constant *Const = IV.isConstant()
1824 ? IV.getConstant() : UndefValue::get(Inst->getType());
1825 DEBUG(dbgs() << " Constant: " << *Const << " = " << *Inst);
1826
1827 // Replaces all of the uses of a variable with uses of the
1828 // constant.
1829 Inst->replaceAllUsesWith(Const);
1830
1831 // Delete the instruction.
1832 if (!isa<CallInst>(Inst) && !isa<TerminatorInst>(Inst))
1833 Inst->eraseFromParent();
1834
1835 // Hey, we just changed something!
1836 MadeChanges = true;
1837 ++IPNumInstRemoved;
1838 }
1839 }
1840
1841 // Now that all instructions in the function are constant folded, erase dead
1842 // blocks, because we can now use ConstantFoldTerminator to get rid of
1843 // in-edges.
1844 for (unsigned i = 0, e = BlocksToErase.size(); i != e; ++i) {
1845 // If there are any PHI nodes in this successor, drop entries for BB now.
1846 BasicBlock *DeadBB = BlocksToErase[i];
1847 for (Value::use_iterator UI = DeadBB->use_begin(), UE = DeadBB->use_end();
1848 UI != UE; ) {
1849 // Grab the user and then increment the iterator early, as the user
1850 // will be deleted. Step past all adjacent uses from the same user.
1851 Instruction *I = dyn_cast<Instruction>(*UI);
1852 do { ++UI; } while (UI != UE && *UI == I);
1853
1854 // Ignore blockaddress users; BasicBlock's dtor will handle them.
1855 if (!I) continue;
1856
1857 bool Folded = ConstantFoldTerminator(I->getParent());
1858 if (!Folded) {
1859 // The constant folder may not have been able to fold the terminator
1860 // if this is a branch or switch on undef. Fold it manually as a
1861 // branch to the first successor.
1862 #ifndef NDEBUG
1863 if (BranchInst *BI = dyn_cast<BranchInst>(I)) {
1864 assert(BI->isConditional() && isa<UndefValue>(BI->getCondition()) &&
1865 "Branch should be foldable!");
1866 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(I)) {
1867 assert(isa<UndefValue>(SI->getCondition()) && "Switch should fold");
1868 } else {
1869 llvm_unreachable("Didn't fold away reference to block!");
1870 }
1871 #endif
1872
1873 // Make this an uncond branch to the first successor.
1874 TerminatorInst *TI = I->getParent()->getTerminator();
1875 BranchInst::Create(TI->getSuccessor(0), TI);
1876
1877 // Remove entries in successor phi nodes to remove edges.
1878 for (unsigned i = 1, e = TI->getNumSuccessors(); i != e; ++i)
1879 TI->getSuccessor(i)->removePredecessor(TI->getParent());
1880
1881 // Remove the old terminator.
1882 TI->eraseFromParent();
1883 }
1884 }
1885
1886 // Finally, delete the basic block.
1887 F->getBasicBlockList().erase(DeadBB);
1888 }
1889 BlocksToErase.clear();
1890 }
1891
1892 // If we inferred constant or undef return values for a function, we replaced
1893 // all call uses with the inferred value. This means we don't need to bother
1894 // actually returning anything from the function. Replace all return
1895 // instructions with return undef.
1896 //
1897 // Do this in two stages: first identify the functions we should process, then
1898 // actually zap their returns. This is important because we can only do this
1899 // if the address of the function isn't taken. In cases where a return is the
1900 // last use of a function, the order of processing functions would affect
1901 // whether other functions are optimizable.
1902 SmallVector<ReturnInst*, 8> ReturnsToZap;
1903
1904 // TODO: Process multiple value ret instructions also.
1905 const DenseMap<Function*, LatticeVal> &RV = Solver.getTrackedRetVals();
1906 for (DenseMap<Function*, LatticeVal>::const_iterator I = RV.begin(),
1907 E = RV.end(); I != E; ++I) {
1908 Function *F = I->first;
1909 if (I->second.isOverdefined() || F->getReturnType()->isVoidTy())
1910 continue;
1911
1912 // We can only do this if we know that nothing else can call the function.
1913 if (!F->hasLocalLinkage() || AddressTakenFunctions.count(F))
1914 continue;
1915
1916 for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
1917 if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator()))
1918 if (!isa<UndefValue>(RI->getOperand(0)))
1919 ReturnsToZap.push_back(RI);
1920 }
1921
1922 // Zap all returns which we've identified as zap to change.
1923 for (unsigned i = 0, e = ReturnsToZap.size(); i != e; ++i) {
1924 Function *F = ReturnsToZap[i]->getParent()->getParent();
1925 ReturnsToZap[i]->setOperand(0, UndefValue::get(F->getReturnType()));
1926 }
1927
1928 // If we inferred constant or undef values for globals variables, we can
1929 // delete the global and any stores that remain to it.
1930 const DenseMap<GlobalVariable*, LatticeVal> &TG = Solver.getTrackedGlobals();
1931 for (DenseMap<GlobalVariable*, LatticeVal>::const_iterator I = TG.begin(),
1932 E = TG.end(); I != E; ++I) {
1933 GlobalVariable *GV = I->first;
1934 assert(!I->second.isOverdefined() &&
1935 "Overdefined values should have been taken out of the map!");
1936 DEBUG(dbgs() << "Found that GV '" << GV->getName() << "' is constant!\n");
1937 while (!GV->use_empty()) {
1938 StoreInst *SI = cast<StoreInst>(GV->use_back());
1939 SI->eraseFromParent();
1940 }
1941 M.getGlobalList().erase(GV);
1942 ++IPNumGlobalConst;
1943 }
1944
1945 return MadeChanges;
1946 }
1947