blob: 8dc325f427fa4e9bcabde274681fb5c9a4bc2011 [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);
29#endif
30
Chris Lattner4d1e46e2002-05-07 18:07:59 +000031//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000032// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000033//
34
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000035/// doConstantPropagation - If an instruction references constants, try to fold
36/// them together...
37///
38bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattner18961502002-06-25 16:12:52 +000039 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000040 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000041 II->replaceAllUsesWith(C);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000042
43 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000044 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000045 return true;
46 }
47
48 return false;
49}
50
Chris Lattner8f90b002004-01-12 18:25:22 +000051/// ConstantFoldInstruction - Attempt to constant fold the specified
52/// instruction. If successful, the constant result is returned, if not, null
53/// is returned. Note that this function can only fail when attempting to fold
54/// instructions like loads and stores, which have no constant expression form.
55///
56Constant *llvm::ConstantFoldInstruction(Instruction *I) {
57 if (PHINode *PN = dyn_cast<PHINode>(I)) {
58 if (PN->getNumIncomingValues() == 0)
59 return Constant::getNullValue(PN->getType());
60
61 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
62 if (Result == 0) return 0;
63
64 // Handle PHI nodes specially here...
65 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
66 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
67 return 0; // Not all the same incoming constants...
68
69 // If we reach here, all incoming values are the same constant.
70 return Result;
Chris Lattner25b83902004-04-13 19:28:52 +000071 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
72 if (Function *F = CI->getCalledFunction())
73 if (canConstantFoldCallTo(F)) {
74 std::vector<Constant*> Args;
75 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
76 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
77 Args.push_back(Op);
78 else
79 return 0;
80 return ConstantFoldCall(F, Args);
81 }
82 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +000083 }
84
85 Constant *Op0 = 0, *Op1 = 0;
86 switch (I->getNumOperands()) {
87 default:
88 case 2:
89 Op1 = dyn_cast<Constant>(I->getOperand(1));
90 if (Op1 == 0) return 0; // Not a constant?, can't fold
91 case 1:
92 Op0 = dyn_cast<Constant>(I->getOperand(0));
93 if (Op0 == 0) return 0; // Not a constant?, can't fold
94 break;
95 case 0: return 0;
96 }
97
Chris Lattnerc6646eb2004-01-12 19:10:58 +000098 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
Chris Lattner8f90b002004-01-12 18:25:22 +000099 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
100
101 switch (I->getOpcode()) {
102 default: return 0;
103 case Instruction::Cast:
104 return ConstantExpr::getCast(Op0, I->getType());
Chris Lattner17fd2732004-03-12 05:53:03 +0000105 case Instruction::Select:
106 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
107 return ConstantExpr::getSelect(Op0, Op1, Op2);
108 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +0000109 case Instruction::GetElementPtr:
110 std::vector<Constant*> IdxList;
111 IdxList.reserve(I->getNumOperands()-1);
112 if (Op1) IdxList.push_back(Op1);
113 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
114 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
115 IdxList.push_back(C);
116 else
117 return 0; // Non-constant operand
118 return ConstantExpr::getGetElementPtr(Op0, IdxList);
119 }
120}
121
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000122// ConstantFoldTerminator - If a terminator instruction is predicated on a
123// constant value, convert it into an unconditional branch to the constant
124// destination.
125//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000126bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000127 TerminatorInst *T = BB->getTerminator();
128
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000129 // Branch - See if we are conditional jumping on constant
130 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
131 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
132 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
133 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
134
135 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
136 // Are we branching on constant?
137 // YES. Change to unconditional branch...
138 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
139 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
140
141 //cerr << "Function: " << T->getParent()->getParent()
142 // << "\nRemoving branch from " << T->getParent()
143 // << "\n\nTo: " << OldDest << endl;
144
145 // Let the basic block know that we are letting go of it. Based on this,
146 // it will adjust it's PHI nodes.
147 assert(BI->getParent() && "Terminator not inserted in block!");
148 OldDest->removePredecessor(BI->getParent());
149
150 // Set the unconditional destination, and change the insn to be an
151 // unconditional branch.
152 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000153 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000154 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000155 // This branch matches something like this:
156 // br bool %cond, label %Dest, label %Dest
157 // and changes it into: br label %Dest
158
159 // Let the basic block know that we are letting go of one copy of it.
160 assert(BI->getParent() && "Terminator not inserted in block!");
161 Dest1->removePredecessor(BI->getParent());
162
163 // Change a conditional branch to unconditional.
164 BI->setUnconditionalDest(Dest1);
165 return true;
166 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000167 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
168 // If we are switching on a constant, we can convert the switch into a
169 // single branch instruction!
170 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
171 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000172 BasicBlock *DefaultDest = TheOnlyDest;
173 assert(TheOnlyDest == SI->getDefaultDest() &&
174 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000175
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000176 // Figure out which case it goes to...
177 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
178 // Found case matching a constant operand?
179 if (SI->getSuccessorValue(i) == CI) {
180 TheOnlyDest = SI->getSuccessor(i);
181 break;
182 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000183
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000184 // Check to see if this branch is going to the same place as the default
185 // dest. If so, eliminate it as an explicit compare.
186 if (SI->getSuccessor(i) == DefaultDest) {
187 // Remove this entry...
188 DefaultDest->removePredecessor(SI->getParent());
189 SI->removeCase(i);
190 --i; --e; // Don't skip an entry...
191 continue;
192 }
193
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000194 // Otherwise, check to see if the switch only branches to one destination.
195 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
196 // destinations.
197 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000198 }
199
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000200 if (CI && !TheOnlyDest) {
201 // Branching on a constant, but not any of the cases, go to the default
202 // successor.
203 TheOnlyDest = SI->getDefaultDest();
204 }
205
206 // If we found a single destination that we can fold the switch into, do so
207 // now.
208 if (TheOnlyDest) {
209 // Insert the new branch..
210 new BranchInst(TheOnlyDest, SI);
211 BasicBlock *BB = SI->getParent();
212
213 // Remove entries from PHI nodes which we no longer branch to...
214 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
215 // Found case matching a constant operand?
216 BasicBlock *Succ = SI->getSuccessor(i);
217 if (Succ == TheOnlyDest)
218 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
219 else
220 Succ->removePredecessor(BB);
221 }
222
223 // Delete the old switch...
224 BB->getInstList().erase(SI);
225 return true;
226 } else if (SI->getNumSuccessors() == 2) {
227 // Otherwise, we can fold this switch into a conditional branch
228 // instruction if it has only one non-default destination.
229 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
230 SI->getSuccessorValue(1), "cond", SI);
231 // Insert the new branch...
232 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
233
234 // Delete the old switch...
235 SI->getParent()->getInstList().erase(SI);
236 return true;
237 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000238 }
239 return false;
240}
241
Chris Lattner25b83902004-04-13 19:28:52 +0000242/// canConstantFoldCallTo - Return true if its even possible to fold a call to
243/// the specified function.
244bool llvm::canConstantFoldCallTo(Function *F) {
245 const std::string &Name = F->getName();
Chris Lattnercf110352004-06-11 06:16:23 +0000246
247 switch (F->getIntrinsicID()) {
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000248 case Intrinsic::isunordered: return true;
Chris Lattnercf110352004-06-11 06:16:23 +0000249 default: break;
250 }
251
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000252 return Name == "sin" || Name == "cos" || Name == "tan" || Name == "sqrt" ||
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000253 Name == "log" || Name == "log10" || Name == "exp" || Name == "pow" ||
Chris Lattner8dfe5702004-05-27 07:25:00 +0000254 Name == "acos" || Name == "asin" || Name == "atan" || Name == "fmod";
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000255}
256
257static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
258 const Type *Ty) {
259 errno = 0;
260 V = NativeFP(V);
261 if (errno == 0)
262 return ConstantFP::get(Ty, V);
263 return 0;
Chris Lattner25b83902004-04-13 19:28:52 +0000264}
265
266/// ConstantFoldCall - Attempt to constant fold a call to the specified function
267/// with the specified arguments, returning null if unsuccessful.
268Constant *llvm::ConstantFoldCall(Function *F,
269 const std::vector<Constant*> &Operands) {
270 const std::string &Name = F->getName();
271 const Type *Ty = F->getReturnType();
272
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000273 if (Operands.size() == 1) {
274 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
275 double V = Op->getValue();
Brian Gaeke83a70492004-06-15 23:09:50 +0000276 if (Name == "sin")
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000277 return ConstantFP::get(Ty, sin(V));
278 else if (Name == "cos")
279 return ConstantFP::get(Ty, cos(V));
280 else if (Name == "tan")
281 return ConstantFP::get(Ty, tan(V));
282 else if (Name == "sqrt" && V >= 0)
283 return ConstantFP::get(Ty, sqrt(V));
284 else if (Name == "exp")
285 return ConstantFP::get(Ty, exp(V));
286 else if (Name == "log" && V > 0)
287 return ConstantFP::get(Ty, log(V));
288 else if (Name == "log10")
289 return ConstantFoldFP(log10, V, Ty);
290 else if (Name == "acos")
291 return ConstantFoldFP(acos, V, Ty);
292 else if (Name == "asin")
293 return ConstantFoldFP(asin, V, Ty);
294 else if (Name == "atan")
295 return ConstantFP::get(Ty, atan(V));
296 }
297 } else if (Operands.size() == 2) {
298 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0]))
299 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner8dfe5702004-05-27 07:25:00 +0000300 double Op1V = Op1->getValue(), Op2V = Op2->getValue();
301
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000302 if (Name == "llvm.isunordered")
303 return ConstantBool::get(isnan(Op1V) | isnan(Op2V));
304 else if (Name == "pow") {
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000305 errno = 0;
Chris Lattner8dfe5702004-05-27 07:25:00 +0000306 double V = pow(Op1V, Op2V);
307 if (errno == 0)
308 return ConstantFP::get(Ty, V);
309 } else if (Name == "fmod") {
310 errno = 0;
311 double V = fmod(Op1V, Op2V);
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000312 if (errno == 0)
313 return ConstantFP::get(Ty, V);
314 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000315 }
Chris Lattner25b83902004-04-13 19:28:52 +0000316 }
317 return 0;
318}
319
320
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000321
322
323//===----------------------------------------------------------------------===//
324// Local dead code elimination...
325//
326
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000327bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerf0a93ed2003-02-24 20:48:32 +0000328 return I->use_empty() && !I->mayWriteToMemory() && !isa<TerminatorInst>(I);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000329}
330
331// dceInstruction - Inspect the instruction at *BBI and figure out if it's
332// [trivially] dead. If so, remove the instruction and update the iterator
333// to point to the instruction that immediately succeeded the original
334// instruction.
335//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000336bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000337 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000338 if (isInstructionTriviallyDead(BBI)) {
339 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000340 return true;
341 }
342 return false;
343}
Brian Gaeked0fde302003-11-11 22:41:34 +0000344
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000345//===----------------------------------------------------------------------===//
346// PHI Instruction Simplification
347//
348
349/// hasConstantValue - If the specified PHI node always merges together the same
350/// value, return the value, otherwise return null.
351///
352Value *llvm::hasConstantValue(PHINode *PN) {
353 // If the PHI node only has one incoming value, eliminate the PHI node...
354 if (PN->getNumIncomingValues() == 1)
355 return PN->getIncomingValue(0);
356
357 // Otherwise if all of the incoming values are the same for the PHI, replace
358 // the PHI node with the incoming value.
359 //
360 Value *InVal = 0;
361 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
362 if (PN->getIncomingValue(i) != PN) // Not the PHI node itself...
363 if (InVal && PN->getIncomingValue(i) != InVal)
364 return 0; // Not the same, bail out.
365 else
366 InVal = PN->getIncomingValue(i);
367
368 // The only case that could cause InVal to be null is if we have a PHI node
369 // that only has entries for itself. In this case, there is no entry into the
370 // loop, so kill the PHI.
371 //
372 if (InVal == 0) InVal = Constant::getNullValue(PN->getType());
373
374 // All of the incoming values are the same, return the value now.
375 return InVal;
376}