blob: df831c78a42f8e1311d4699e2588fb3865689051 [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 Lattnercf110352004-06-11 06:16:23 +000018#include "llvm/Intrinsics.h"
Alkis Evlogimenos09233fb2004-04-21 16:11:40 +000019#include <cerrno>
Brian Gaekec5985172004-04-16 15:57:32 +000020#include <cmath>
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000021using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000022
Brian Gaekefda2cce2004-06-14 06:33:19 +000023#if defined(__POWERPC__) && defined(__APPLE_CC__)
24// FIXME: Currently it seems that isnan didn't make its way into the Apple
25// C++ headers, although it IS in the C headers (which confuses autoconf
26// in a big way). This is a quick fix to get things compiling, until one of
27// us has time to write a more complicated autoconf test.
28extern "C" int isnan (double d);
Brian Gaekeafe16e12004-06-17 22:27:04 +000029namespace std { int isnan (double d) { return ::isnan (d); } }
Brian Gaekefda2cce2004-06-14 06:33:19 +000030#endif
31
Chris Lattner4d1e46e2002-05-07 18:07:59 +000032//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000033// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000034//
35
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000036/// doConstantPropagation - If an instruction references constants, try to fold
37/// them together...
38///
39bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattner18961502002-06-25 16:12:52 +000040 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000041 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000042 II->replaceAllUsesWith(C);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000043
44 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000045 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000046 return true;
47 }
48
49 return false;
50}
51
Chris Lattner8f90b002004-01-12 18:25:22 +000052/// ConstantFoldInstruction - Attempt to constant fold the specified
53/// instruction. If successful, the constant result is returned, if not, null
54/// is returned. Note that this function can only fail when attempting to fold
55/// instructions like loads and stores, which have no constant expression form.
56///
57Constant *llvm::ConstantFoldInstruction(Instruction *I) {
58 if (PHINode *PN = dyn_cast<PHINode>(I)) {
59 if (PN->getNumIncomingValues() == 0)
60 return Constant::getNullValue(PN->getType());
61
62 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
63 if (Result == 0) return 0;
64
65 // Handle PHI nodes specially here...
66 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
67 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
68 return 0; // Not all the same incoming constants...
69
70 // If we reach here, all incoming values are the same constant.
71 return Result;
Chris Lattner25b83902004-04-13 19:28:52 +000072 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
73 if (Function *F = CI->getCalledFunction())
74 if (canConstantFoldCallTo(F)) {
75 std::vector<Constant*> Args;
76 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
77 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
78 Args.push_back(Op);
79 else
80 return 0;
81 return ConstantFoldCall(F, Args);
82 }
83 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +000084 }
85
86 Constant *Op0 = 0, *Op1 = 0;
87 switch (I->getNumOperands()) {
88 default:
89 case 2:
90 Op1 = dyn_cast<Constant>(I->getOperand(1));
91 if (Op1 == 0) return 0; // Not a constant?, can't fold
92 case 1:
93 Op0 = dyn_cast<Constant>(I->getOperand(0));
94 if (Op0 == 0) return 0; // Not a constant?, can't fold
95 break;
96 case 0: return 0;
97 }
98
Chris Lattnerc6646eb2004-01-12 19:10:58 +000099 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
Chris Lattner8f90b002004-01-12 18:25:22 +0000100 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
101
102 switch (I->getOpcode()) {
103 default: return 0;
104 case Instruction::Cast:
105 return ConstantExpr::getCast(Op0, I->getType());
Chris Lattner17fd2732004-03-12 05:53:03 +0000106 case Instruction::Select:
107 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
108 return ConstantExpr::getSelect(Op0, Op1, Op2);
109 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +0000110 case Instruction::GetElementPtr:
111 std::vector<Constant*> IdxList;
112 IdxList.reserve(I->getNumOperands()-1);
113 if (Op1) IdxList.push_back(Op1);
114 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
115 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
116 IdxList.push_back(C);
117 else
118 return 0; // Non-constant operand
119 return ConstantExpr::getGetElementPtr(Op0, IdxList);
120 }
121}
122
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000123// ConstantFoldTerminator - If a terminator instruction is predicated on a
124// constant value, convert it into an unconditional branch to the constant
125// destination.
126//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000127bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000128 TerminatorInst *T = BB->getTerminator();
129
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000130 // Branch - See if we are conditional jumping on constant
131 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
132 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
133 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
134 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
135
136 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
137 // Are we branching on constant?
138 // YES. Change to unconditional branch...
139 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
140 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
141
142 //cerr << "Function: " << T->getParent()->getParent()
143 // << "\nRemoving branch from " << T->getParent()
144 // << "\n\nTo: " << OldDest << endl;
145
146 // Let the basic block know that we are letting go of it. Based on this,
147 // it will adjust it's PHI nodes.
148 assert(BI->getParent() && "Terminator not inserted in block!");
149 OldDest->removePredecessor(BI->getParent());
150
151 // Set the unconditional destination, and change the insn to be an
152 // unconditional branch.
153 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000154 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000155 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000156 // This branch matches something like this:
157 // br bool %cond, label %Dest, label %Dest
158 // and changes it into: br label %Dest
159
160 // Let the basic block know that we are letting go of one copy of it.
161 assert(BI->getParent() && "Terminator not inserted in block!");
162 Dest1->removePredecessor(BI->getParent());
163
164 // Change a conditional branch to unconditional.
165 BI->setUnconditionalDest(Dest1);
166 return true;
167 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000168 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
169 // If we are switching on a constant, we can convert the switch into a
170 // single branch instruction!
171 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
172 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000173 BasicBlock *DefaultDest = TheOnlyDest;
174 assert(TheOnlyDest == SI->getDefaultDest() &&
175 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000176
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000177 // Figure out which case it goes to...
178 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
179 // Found case matching a constant operand?
180 if (SI->getSuccessorValue(i) == CI) {
181 TheOnlyDest = SI->getSuccessor(i);
182 break;
183 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000184
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000185 // Check to see if this branch is going to the same place as the default
186 // dest. If so, eliminate it as an explicit compare.
187 if (SI->getSuccessor(i) == DefaultDest) {
188 // Remove this entry...
189 DefaultDest->removePredecessor(SI->getParent());
190 SI->removeCase(i);
191 --i; --e; // Don't skip an entry...
192 continue;
193 }
194
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000195 // Otherwise, check to see if the switch only branches to one destination.
196 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
197 // destinations.
198 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000199 }
200
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000201 if (CI && !TheOnlyDest) {
202 // Branching on a constant, but not any of the cases, go to the default
203 // successor.
204 TheOnlyDest = SI->getDefaultDest();
205 }
206
207 // If we found a single destination that we can fold the switch into, do so
208 // now.
209 if (TheOnlyDest) {
210 // Insert the new branch..
211 new BranchInst(TheOnlyDest, SI);
212 BasicBlock *BB = SI->getParent();
213
214 // Remove entries from PHI nodes which we no longer branch to...
215 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
216 // Found case matching a constant operand?
217 BasicBlock *Succ = SI->getSuccessor(i);
218 if (Succ == TheOnlyDest)
219 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
220 else
221 Succ->removePredecessor(BB);
222 }
223
224 // Delete the old switch...
225 BB->getInstList().erase(SI);
226 return true;
227 } else if (SI->getNumSuccessors() == 2) {
228 // Otherwise, we can fold this switch into a conditional branch
229 // instruction if it has only one non-default destination.
230 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
231 SI->getSuccessorValue(1), "cond", SI);
232 // Insert the new branch...
233 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
234
235 // Delete the old switch...
236 SI->getParent()->getInstList().erase(SI);
237 return true;
238 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000239 }
240 return false;
241}
242
Chris Lattner25b83902004-04-13 19:28:52 +0000243/// canConstantFoldCallTo - Return true if its even possible to fold a call to
244/// the specified function.
245bool llvm::canConstantFoldCallTo(Function *F) {
246 const std::string &Name = F->getName();
Chris Lattnercf110352004-06-11 06:16:23 +0000247
248 switch (F->getIntrinsicID()) {
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000249 case Intrinsic::isunordered: return true;
Chris Lattnercf110352004-06-11 06:16:23 +0000250 default: break;
251 }
252
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000253 return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000254 Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
Chris Lattner8dfe5702004-05-27 07:25:00 +0000255 Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000256}
257
258static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
259 const Type *Ty) {
260 errno = 0;
261 V = NativeFP(V);
262 if (errno == 0)
263 return ConstantFP::get(Ty, V);
264 return 0;
Chris Lattner25b83902004-04-13 19:28:52 +0000265}
266
267/// ConstantFoldCall - Attempt to constant fold a call to the specified function
268/// with the specified arguments, returning null if unsuccessful.
269Constant *llvm::ConstantFoldCall(Function *F,
270 const std::vector<Constant*> &Operands) {
271 const std::string &Name = F->getName();
272 const Type *Ty = F->getReturnType();
273
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000274 if (Operands.size() == 1) {
275 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
276 double V = Op->getValue();
Brian Gaeke83a70492004-06-15 23:09:50 +0000277 if (Name == "sin")
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000278 return ConstantFP::get(Ty, sin(V));
279 else if (Name == "cos")
280 return ConstantFP::get(Ty, cos(V));
281 else if (Name == "tan")
282 return ConstantFP::get(Ty, tan(V));
283 else if (Name == "sqrt" && V >= 0)
284 return ConstantFP::get(Ty, sqrt(V));
285 else if (Name == "exp")
286 return ConstantFP::get(Ty, exp(V));
287 else if (Name == "log" && V > 0)
288 return ConstantFP::get(Ty, log(V));
289 else if (Name == "log10")
290 return ConstantFoldFP(log10, V, Ty);
291 else if (Name == "acos")
292 return ConstantFoldFP(acos, V, Ty);
293 else if (Name == "asin")
294 return ConstantFoldFP(asin, V, Ty);
295 else if (Name == "atan")
296 return ConstantFP::get(Ty, atan(V));
297 }
298 } else if (Operands.size() == 2) {
299 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
300 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner8dfe5702004-05-27 07:25:00 +0000301 double Op1V = Op1->getValue(), Op2V = Op2->getValue();
302
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000303 if (Name == "llvm.isunordered")
Chris Lattner5253f052004-06-17 21:20:52 +0000304 return ConstantBool::get(std::isnan(Op1V) | std::isnan(Op2V));
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000305 else if (Name == "pow") {
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000306 errno = 0;
Chris Lattner8dfe5702004-05-27 07:25:00 +0000307 double V = pow(Op1V, Op2V);
308 if (errno == 0)
309 return ConstantFP::get(Ty, V);
310 } else if (Name == "fmod") {
311 errno = 0;
312 double V = fmod(Op1V, Op2V);
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000313 if (errno == 0)
314 return ConstantFP::get(Ty, V);
315 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000316 }
Chris Lattner25b83902004-04-13 19:28:52 +0000317 }
318 return 0;
319}
320
321
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000322
323
324//===----------------------------------------------------------------------===//
325// Local dead code elimination...
326//
327
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000328bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerf0a93ed2003-02-24 20:48:32 +0000329 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000330}
331
332// dceInstruction - Inspect the instruction at *BBI and figure out if it's
333// [trivially] dead. If so, remove the instruction and update the iterator
334// to point to the instruction that immediately succeeded the original
335// instruction.
336//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000337bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000338 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000339 if (isInstructionTriviallyDead(BBI)) {
340 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000341 return true;
342 }
343 return false;
344}
Brian Gaeked0fde302003-11-11 22:41:34 +0000345
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000346//===----------------------------------------------------------------------===//
347// PHI Instruction Simplification
348//
349
350/// hasConstantValue - If the specified PHI node always merges together the same
351/// value, return the value, otherwise return null.
352///
353Value *llvm::hasConstantValue(PHINode *PN) {
354 // If the PHI node only has one incoming value, eliminate the PHI node...
355 if (PN->getNumIncomingValues() == 1)
356 return PN->getIncomingValue(0);
357
358 // Otherwise if all of the incoming values are the same for the PHI, replace
359 // the PHI node with the incoming value.
360 //
361 Value *InVal = 0;
362 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
363 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
364 if (InVal && PN->getIncomingValue(i) != InVal)
365 return 0; // Not the same, bail out.
366 else
367 InVal = PN->getIncomingValue(i);
368
369 // The only case that could cause InVal to be null is if we have a PHI node
370 // that only has entries for itself. In this case, there is no entry into the
371 // loop, so kill the PHI.
372 //
373 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
374
375 // All of the incoming values are the same, return the value now.
376 return InVal;
377}