blob: 821d1e13ebc5ba4d5c413e29e7f9b794f83293c9 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
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 Lattner4d1e46e2002-05-07 18:07:59 +00009//
10// This family of functions perform various local transformations to the
11// program.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Transforms/Utils/Local.h"
Chris Lattner81ebc302004-01-12 18:35:03 +000016#include "llvm/Constants.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000017#include "llvm/Instructions.h"
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000018using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000019
Chris Lattner4d1e46e2002-05-07 18:07:59 +000020//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000021// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000022//
23
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000024/// doConstantPropagation - If an instruction references constants, try to fold
25/// them together...
26///
27bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattner18961502002-06-25 16:12:52 +000028 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000029 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000030 II->replaceAllUsesWith(C);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000031
32 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000033 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000034 return true;
35 }
36
37 return false;
38}
39
Chris Lattner8f90b002004-01-12 18:25:22 +000040/// 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.
44///
45Constant *llvm::ConstantFoldInstruction(Instruction *I) {
46 if (PHINode *PN = dyn_cast<PHINode>(I)) {
47 if (PN->getNumIncomingValues() == 0)
48 return Constant::getNullValue(PN->getType());
49
50 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
51 if (Result == 0) return 0;
52
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...
57
58 // If we reach here, all incoming values are the same constant.
59 return Result;
60 }
61
62 Constant *Op0 = 0, *Op1 = 0;
63 switch (I->getNumOperands()) {
64 default:
65 case 2:
66 Op1 = dyn_cast<Constant>(I->getOperand(1));
67 if (Op1 == 0) return 0; // Not a constant?, can't fold
68 case 1:
69 Op0 = dyn_cast<Constant>(I->getOperand(0));
70 if (Op0 == 0) return 0; // Not a constant?, can't fold
71 break;
72 case 0: return 0;
73 }
74
Chris Lattnerc6646eb2004-01-12 19:10:58 +000075 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
Chris Lattner8f90b002004-01-12 18:25:22 +000076 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
77
78 switch (I->getOpcode()) {
79 default: return 0;
80 case Instruction::Cast:
81 return ConstantExpr::getCast(Op0, I->getType());
Chris Lattner8f90b002004-01-12 18:25:22 +000082 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)))
88 IdxList.push_back(C);
89 else
90 return 0; // Non-constant operand
91 return ConstantExpr::getGetElementPtr(Op0, IdxList);
92 }
93}
94
Chris Lattner4d1e46e2002-05-07 18:07:59 +000095// ConstantFoldTerminator - If a terminator instruction is predicated on a
96// constant value, convert it into an unconditional branch to the constant
97// destination.
98//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000099bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000100 TerminatorInst *T = BB->getTerminator();
101
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000102 // 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));
107
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;
113
114 //cerr << "Function: " << T->getParent()->getParent()
115 // << "\nRemoving branch from " << T->getParent()
116 // << "\n\nTo: " << OldDest << endl;
117
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());
122
123 // Set the unconditional destination, and change the insn to be an
124 // unconditional branch.
125 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000126 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000127 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000128 // This branch matches something like this:
129 // br bool %cond, label %Dest, label %Dest
130 // and changes it into: br label %Dest
131
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());
135
136 // Change a conditional branch to unconditional.
137 BI->setUnconditionalDest(Dest1);
138 return true;
139 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000140 } 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
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000145 BasicBlock *DefaultDest = TheOnlyDest;
146 assert(TheOnlyDest == SI->getDefaultDest() &&
147 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000148
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000149 // 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);
154 break;
155 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000156
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000157 // 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());
162 SI->removeCase(i);
163 --i; --e; // Don't skip an entry...
164 continue;
165 }
166
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000167 // 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
169 // destinations.
170 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000171 }
172
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000173 if (CI && !TheOnlyDest) {
174 // Branching on a constant, but not any of the cases, go to the default
175 // successor.
176 TheOnlyDest = SI->getDefaultDest();
177 }
178
179 // If we found a single destination that we can fold the switch into, do so
180 // now.
181 if (TheOnlyDest) {
182 // Insert the new branch..
183 new BranchInst(TheOnlyDest, SI);
184 BasicBlock *BB = SI->getParent();
185
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
192 else
193 Succ->removePredecessor(BB);
194 }
195
196 // Delete the old switch...
197 BB->getInstList().erase(SI);
198 return true;
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);
206
207 // Delete the old switch...
208 SI->getParent()->getInstList().erase(SI);
209 return true;
210 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000211 }
212 return false;
213}
214
215
216
217//===----------------------------------------------------------------------===//
218// Local dead code elimination...
219//
220
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000221bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerf0a93ed2003-02-24 20:48:32 +0000222 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000223}
224
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
228// instruction.
229//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000230bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000231 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000232 if (isInstructionTriviallyDead(BBI)) {
233 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000234 return true;
235 }
236 return false;
237}
Brian Gaeked0fde302003-11-11 22:41:34 +0000238
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000239//===----------------------------------------------------------------------===//
240// PHI Instruction Simplification
241//
242
243/// hasConstantValue - If the specified PHI node always merges together the same
244/// value, return the value, otherwise return null.
245///
246Value *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);
250
251 // Otherwise if all of the incoming values are the same for the PHI, replace
252 // the PHI node with the incoming value.
253 //
254 Value *InVal = 0;
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.
259 else
260 InVal = PN->getIncomingValue(i);
261
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.
265 //
266 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
267
268 // All of the incoming values are the same, return the value now.
269 return InVal;
270}