1 //===-- Local.cpp - Functions to perform local transformations ------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This family of functions perform various local transformations to the
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/Local.h"
16 #include "llvm/Constants.h"
17 #include "llvm/Instructions.h"
20 //===----------------------------------------------------------------------===//
21 // Local constant propagation...
24 /// doConstantPropagation - If an instruction references constants, try to fold
27 bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
28 if (Constant *C = ConstantFoldInstruction(II)) {
29 // Replaces all of the uses of a variable with uses of the constant.
30 II->replaceAllUsesWith(C);
32 // Remove the instruction from the basic block...
33 II = II->getParent()->getInstList().erase(II);
40 /// ConstantFoldInstruction - Attempt to constant fold the specified
41 /// instruction. If successful, the constant result is returned, if not, null
42 /// is returned. Note that this function can only fail when attempting to fold
43 /// instructions like loads and stores, which have no constant expression form.
45 Constant *llvm::ConstantFoldInstruction(Instruction *I) {
46 if (PHINode *PN = dyn_cast<PHINode>(I)) {
47 if (PN->getNumIncomingValues() == 0)
48 return Constant::getNullValue(PN->getType());
50 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
51 if (Result == 0) return 0;
53 // Handle PHI nodes specially here...
54 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
55 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
56 return 0; // Not all the same incoming constants...
58 // If we reach here, all incoming values are the same constant.
62 Constant *Op0 = 0, *Op1 = 0;
63 switch (I->getNumOperands()) {
66 Op1 = dyn_cast<Constant>(I->getOperand(1));
67 if (Op1 == 0) return 0; // Not a constant?, can't fold
69 Op0 = dyn_cast<Constant>(I->getOperand(0));
70 if (Op0 == 0) return 0; // Not a constant?, can't fold
75 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
76 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
78 switch (I->getOpcode()) {
80 case Instruction::Cast:
81 return ConstantExpr::getCast(Op0, I->getType());
82 case Instruction::GetElementPtr:
83 std::vector<Constant*> IdxList;
84 IdxList.reserve(I->getNumOperands()-1);
85 if (Op1) IdxList.push_back(Op1);
86 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
87 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
90 return 0; // Non-constant operand
91 return ConstantExpr::getGetElementPtr(Op0, IdxList);
95 // ConstantFoldTerminator - If a terminator instruction is predicated on a
96 // constant value, convert it into an unconditional branch to the constant
99 bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
100 TerminatorInst *T = BB->getTerminator();
102 // Branch - See if we are conditional jumping on constant
103 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
104 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
105 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
106 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
108 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
109 // Are we branching on constant?
110 // YES. Change to unconditional branch...
111 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
112 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
114 //cerr << "Function: " << T->getParent()->getParent()
115 // << "\nRemoving branch from " << T->getParent()
116 // << "\n\nTo: " << OldDest << endl;
118 // Let the basic block know that we are letting go of it. Based on this,
119 // it will adjust it's PHI nodes.
120 assert(BI->getParent() && "Terminator not inserted in block!");
121 OldDest->removePredecessor(BI->getParent());
123 // Set the unconditional destination, and change the insn to be an
124 // unconditional branch.
125 BI->setUnconditionalDest(Destination);
127 } else if (Dest2 == Dest1) { // Conditional branch to same location?
128 // This branch matches something like this:
129 // br bool %cond, label %Dest, label %Dest
130 // and changes it into: br label %Dest
132 // Let the basic block know that we are letting go of one copy of it.
133 assert(BI->getParent() && "Terminator not inserted in block!");
134 Dest1->removePredecessor(BI->getParent());
136 // Change a conditional branch to unconditional.
137 BI->setUnconditionalDest(Dest1);
140 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
141 // If we are switching on a constant, we can convert the switch into a
142 // single branch instruction!
143 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
144 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
145 BasicBlock *DefaultDest = TheOnlyDest;
146 assert(TheOnlyDest == SI->getDefaultDest() &&
147 "Default destination is not successor #0?");
149 // Figure out which case it goes to...
150 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
151 // Found case matching a constant operand?
152 if (SI->getSuccessorValue(i) == CI) {
153 TheOnlyDest = SI->getSuccessor(i);
157 // Check to see if this branch is going to the same place as the default
158 // dest. If so, eliminate it as an explicit compare.
159 if (SI->getSuccessor(i) == DefaultDest) {
160 // Remove this entry...
161 DefaultDest->removePredecessor(SI->getParent());
163 --i; --e; // Don't skip an entry...
167 // Otherwise, check to see if the switch only branches to one destination.
168 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
170 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
173 if (CI && !TheOnlyDest) {
174 // Branching on a constant, but not any of the cases, go to the default
176 TheOnlyDest = SI->getDefaultDest();
179 // If we found a single destination that we can fold the switch into, do so
182 // Insert the new branch..
183 new BranchInst(TheOnlyDest, SI);
184 BasicBlock *BB = SI->getParent();
186 // Remove entries from PHI nodes which we no longer branch to...
187 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
188 // Found case matching a constant operand?
189 BasicBlock *Succ = SI->getSuccessor(i);
190 if (Succ == TheOnlyDest)
191 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
193 Succ->removePredecessor(BB);
196 // Delete the old switch...
197 BB->getInstList().erase(SI);
199 } else if (SI->getNumSuccessors() == 2) {
200 // Otherwise, we can fold this switch into a conditional branch
201 // instruction if it has only one non-default destination.
202 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
203 SI->getSuccessorValue(1), "cond", SI);
204 // Insert the new branch...
205 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
207 // Delete the old switch...
208 SI->getParent()->getInstList().erase(SI);
217 //===----------------------------------------------------------------------===//
218 // Local dead code elimination...
221 bool llvm::isInstructionTriviallyDead(Instruction *I) {
222 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
225 // dceInstruction - Inspect the instruction at *BBI and figure out if it's
226 // [trivially] dead. If so, remove the instruction and update the iterator
227 // to point to the instruction that immediately succeeded the original
230 bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
231 // Look for un"used" definitions...
232 if (isInstructionTriviallyDead(BBI)) {
233 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
239 //===----------------------------------------------------------------------===//
240 // PHI Instruction Simplification
243 /// hasConstantValue - If the specified PHI node always merges together the same
244 /// value, return the value, otherwise return null.
246 Value *llvm::hasConstantValue(PHINode *PN) {
247 // If the PHI node only has one incoming value, eliminate the PHI node...
248 if (PN->getNumIncomingValues() == 1)
249 return PN->getIncomingValue(0);
251 // Otherwise if all of the incoming values are the same for the PHI, replace
252 // the PHI node with the incoming value.
255 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
256 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
257 if (InVal && PN->getIncomingValue(i) != InVal)
258 return 0; // Not the same, bail out.
260 InVal = PN->getIncomingValue(i);
262 // The only case that could cause InVal to be null is if we have a PHI node
263 // that only has entries for itself. In this case, there is no entry into the
264 // loop, so kill the PHI.
266 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
268 // All of the incoming values are the same, return the value now.