blob: 1675f71610921065e7f998ac677ce793280fd651 [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"
Alkis Evlogimenos09233fb2004-04-21 16:11:40 +000018#include <cerrno>
Brian Gaekec5985172004-04-16 15:57:32 +000019#include <cmath>
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000020using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000021
Chris Lattner4d1e46e2002-05-07 18:07:59 +000022//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000023// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000024//
25
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000026/// doConstantPropagation - If an instruction references constants, try to fold
27/// them together...
28///
29bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattner18961502002-06-25 16:12:52 +000030 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000031 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000032 II->replaceAllUsesWith(C);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000033
34 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000035 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000036 return true;
37 }
38
39 return false;
40}
41
Chris Lattner8f90b002004-01-12 18:25:22 +000042/// ConstantFoldInstruction - Attempt to constant fold the specified
43/// instruction. If successful, the constant result is returned, if not, null
44/// is returned. Note that this function can only fail when attempting to fold
45/// instructions like loads and stores, which have no constant expression form.
46///
47Constant *llvm::ConstantFoldInstruction(Instruction *I) {
48 if (PHINode *PN = dyn_cast<PHINode>(I)) {
49 if (PN->getNumIncomingValues() == 0)
50 return Constant::getNullValue(PN->getType());
51
52 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
53 if (Result == 0) return 0;
54
55 // Handle PHI nodes specially here...
56 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
57 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
58 return 0; // Not all the same incoming constants...
59
60 // If we reach here, all incoming values are the same constant.
61 return Result;
Chris Lattner25b83902004-04-13 19:28:52 +000062 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
63 if (Function *F = CI->getCalledFunction())
64 if (canConstantFoldCallTo(F)) {
65 std::vector<Constant*> Args;
66 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
67 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
68 Args.push_back(Op);
69 else
70 return 0;
71 return ConstantFoldCall(F, Args);
72 }
73 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +000074 }
75
76 Constant *Op0 = 0, *Op1 = 0;
77 switch (I->getNumOperands()) {
78 default:
79 case 2:
80 Op1 = dyn_cast<Constant>(I->getOperand(1));
81 if (Op1 == 0) return 0; // Not a constant?, can't fold
82 case 1:
83 Op0 = dyn_cast<Constant>(I->getOperand(0));
84 if (Op0 == 0) return 0; // Not a constant?, can't fold
85 break;
86 case 0: return 0;
87 }
88
Chris Lattnerc6646eb2004-01-12 19:10:58 +000089 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
Chris Lattner8f90b002004-01-12 18:25:22 +000090 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
91
92 switch (I->getOpcode()) {
93 default: return 0;
94 case Instruction::Cast:
95 return ConstantExpr::getCast(Op0, I->getType());
Chris Lattner17fd2732004-03-12 05:53:03 +000096 case Instruction::Select:
97 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
98 return ConstantExpr::getSelect(Op0, Op1, Op2);
99 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +0000100 case Instruction::GetElementPtr:
101 std::vector<Constant*> IdxList;
102 IdxList.reserve(I->getNumOperands()-1);
103 if (Op1) IdxList.push_back(Op1);
104 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
105 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
106 IdxList.push_back(C);
107 else
108 return 0; // Non-constant operand
109 return ConstantExpr::getGetElementPtr(Op0, IdxList);
110 }
111}
112
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000113// ConstantFoldTerminator - If a terminator instruction is predicated on a
114// constant value, convert it into an unconditional branch to the constant
115// destination.
116//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000117bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000118 TerminatorInst *T = BB->getTerminator();
119
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000120 // Branch - See if we are conditional jumping on constant
121 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
122 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
123 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
124 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
125
126 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
127 // Are we branching on constant?
128 // YES. Change to unconditional branch...
129 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
130 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
131
132 //cerr << "Function: " << T->getParent()->getParent()
133 // << "\nRemoving branch from " << T->getParent()
134 // << "\n\nTo: " << OldDest << endl;
135
136 // Let the basic block know that we are letting go of it. Based on this,
137 // it will adjust it's PHI nodes.
138 assert(BI->getParent() && "Terminator not inserted in block!");
139 OldDest->removePredecessor(BI->getParent());
140
141 // Set the unconditional destination, and change the insn to be an
142 // unconditional branch.
143 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000144 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000145 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000146 // This branch matches something like this:
147 // br bool %cond, label %Dest, label %Dest
148 // and changes it into: br label %Dest
149
150 // Let the basic block know that we are letting go of one copy of it.
151 assert(BI->getParent() && "Terminator not inserted in block!");
152 Dest1->removePredecessor(BI->getParent());
153
154 // Change a conditional branch to unconditional.
155 BI->setUnconditionalDest(Dest1);
156 return true;
157 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000158 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
159 // If we are switching on a constant, we can convert the switch into a
160 // single branch instruction!
161 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
162 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000163 BasicBlock *DefaultDest = TheOnlyDest;
164 assert(TheOnlyDest == SI->getDefaultDest() &&
165 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000166
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000167 // Figure out which case it goes to...
168 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
169 // Found case matching a constant operand?
170 if (SI->getSuccessorValue(i) == CI) {
171 TheOnlyDest = SI->getSuccessor(i);
172 break;
173 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000174
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000175 // Check to see if this branch is going to the same place as the default
176 // dest. If so, eliminate it as an explicit compare.
177 if (SI->getSuccessor(i) == DefaultDest) {
178 // Remove this entry...
179 DefaultDest->removePredecessor(SI->getParent());
180 SI->removeCase(i);
181 --i; --e; // Don't skip an entry...
182 continue;
183 }
184
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000185 // Otherwise, check to see if the switch only branches to one destination.
186 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
187 // destinations.
188 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000189 }
190
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000191 if (CI && !TheOnlyDest) {
192 // Branching on a constant, but not any of the cases, go to the default
193 // successor.
194 TheOnlyDest = SI->getDefaultDest();
195 }
196
197 // If we found a single destination that we can fold the switch into, do so
198 // now.
199 if (TheOnlyDest) {
200 // Insert the new branch..
201 new BranchInst(TheOnlyDest, SI);
202 BasicBlock *BB = SI->getParent();
203
204 // Remove entries from PHI nodes which we no longer branch to...
205 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
206 // Found case matching a constant operand?
207 BasicBlock *Succ = SI->getSuccessor(i);
208 if (Succ == TheOnlyDest)
209 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
210 else
211 Succ->removePredecessor(BB);
212 }
213
214 // Delete the old switch...
215 BB->getInstList().erase(SI);
216 return true;
217 } else if (SI->getNumSuccessors() == 2) {
218 // Otherwise, we can fold this switch into a conditional branch
219 // instruction if it has only one non-default destination.
220 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
221 SI->getSuccessorValue(1), "cond", SI);
222 // Insert the new branch...
223 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
224
225 // Delete the old switch...
226 SI->getParent()->getInstList().erase(SI);
227 return true;
228 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000229 }
230 return false;
231}
232
Chris Lattner25b83902004-04-13 19:28:52 +0000233/// canConstantFoldCallTo - Return true if its even possible to fold a call to
234/// the specified function.
235bool llvm::canConstantFoldCallTo(Function *F) {
236 const std::string &Name = F->getName();
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000237 return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000238 Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
239 Name == "acos" || Name == "asin";
240}
241
242static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
243 const Type *Ty) {
244 errno = 0;
245 V = NativeFP(V);
246 if (errno == 0)
247 return ConstantFP::get(Ty, V);
248 return 0;
Chris Lattner25b83902004-04-13 19:28:52 +0000249}
250
251/// ConstantFoldCall - Attempt to constant fold a call to the specified function
252/// with the specified arguments, returning null if unsuccessful.
253Constant *llvm::ConstantFoldCall(Function *F,
254 const std::vector<Constant*> &Operands) {
255 const std::string &Name = F->getName();
256 const Type *Ty = F->getReturnType();
257
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000258 if (Operands.size() == 1) {
259 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
260 double V = Op->getValue();
261 if (Name == "sin")
262 return ConstantFP::get(Ty, sin(V));
263 else if (Name == "cos")
264 return ConstantFP::get(Ty, cos(V));
265 else if (Name == "tan")
266 return ConstantFP::get(Ty, tan(V));
267 else if (Name == "sqrt" && V >= 0)
268 return ConstantFP::get(Ty, sqrt(V));
269 else if (Name == "exp")
270 return ConstantFP::get(Ty, exp(V));
271 else if (Name == "log" && V > 0)
272 return ConstantFP::get(Ty, log(V));
273 else if (Name == "log10")
274 return ConstantFoldFP(log10, V, Ty);
275 else if (Name == "acos")
276 return ConstantFoldFP(acos, V, Ty);
277 else if (Name == "asin")
278 return ConstantFoldFP(asin, V, Ty);
279 else if (Name == "atan")
280 return ConstantFP::get(Ty, atan(V));
281 }
282 } else if (Operands.size() == 2) {
283 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
284 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
285 if (Name == "pow") {
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000286 errno = 0;
287 double V = pow(Op1->getValue(), Op2->getValue());
288 if (errno == 0)
289 return ConstantFP::get(Ty, V);
290 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000291 }
Chris Lattner25b83902004-04-13 19:28:52 +0000292 }
293 return 0;
294}
295
296
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000297
298
299//===----------------------------------------------------------------------===//
300// Local dead code elimination...
301//
302
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000303bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerf0a93ed2003-02-24 20:48:32 +0000304 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000305}
306
307// dceInstruction - Inspect the instruction at *BBI and figure out if it's
308// [trivially] dead. If so, remove the instruction and update the iterator
309// to point to the instruction that immediately succeeded the original
310// instruction.
311//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000312bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000313 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000314 if (isInstructionTriviallyDead(BBI)) {
315 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000316 return true;
317 }
318 return false;
319}
Brian Gaeked0fde302003-11-11 22:41:34 +0000320
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000321//===----------------------------------------------------------------------===//
322// PHI Instruction Simplification
323//
324
325/// hasConstantValue - If the specified PHI node always merges together the same
326/// value, return the value, otherwise return null.
327///
328Value *llvm::hasConstantValue(PHINode *PN) {
329 // If the PHI node only has one incoming value, eliminate the PHI node...
330 if (PN->getNumIncomingValues() == 1)
331 return PN->getIncomingValue(0);
332
333 // Otherwise if all of the incoming values are the same for the PHI, replace
334 // the PHI node with the incoming value.
335 //
336 Value *InVal = 0;
337 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
338 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
339 if (InVal && PN->getIncomingValue(i) != InVal)
340 return 0; // Not the same, bail out.
341 else
342 InVal = PN->getIncomingValue(i);
343
344 // The only case that could cause InVal to be null is if we have a PHI node
345 // that only has entries for itself. In this case, there is no entry into the
346 // loop, so kill the PHI.
347 //
348 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
349
350 // All of the incoming values are the same, return the value now.
351 return InVal;
352}