blob: a9cfcc0a9209d4cc18c11d0a22b3424e08d39905 [file] [log] [blame]
Chris Lattner4d1e46e2002-05-07 18:07:59 +00001//===-- Local.cpp - Functions to perform local transformations ------------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// 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.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
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 Lattnerc5f52e62005-09-26 05:27:10 +000017#include "llvm/DerivedTypes.h"
Chris Lattner7822c2a2004-01-12 19:56:36 +000018#include "llvm/Instructions.h"
Chris Lattnercf110352004-06-11 06:16:23 +000019#include "llvm/Intrinsics.h"
Chris Lattnerc5f52e62005-09-26 05:27:10 +000020#include "llvm/Support/GetElementPtrTypeIterator.h"
21#include "llvm/Support/MathExtras.h"
Alkis Evlogimenos09233fb2004-04-21 16:11:40 +000022#include <cerrno>
Brian Gaekec5985172004-04-16 15:57:32 +000023#include <cmath>
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000024using namespace llvm;
Brian Gaeked0fde302003-11-11 22:41:34 +000025
Chris Lattner4d1e46e2002-05-07 18:07:59 +000026//===----------------------------------------------------------------------===//
Misha Brukman82c89b92003-05-20 21:01:22 +000027// Local constant propagation...
Chris Lattner4d1e46e2002-05-07 18:07:59 +000028//
29
Chris Lattnerabbc2dd2003-12-19 05:56:28 +000030/// doConstantPropagation - If an instruction references constants, try to fold
31/// them together...
32///
33bool llvm::doConstantPropagation(BasicBlock::iterator &II) {
Chris Lattner18961502002-06-25 16:12:52 +000034 if (Constant *C = ConstantFoldInstruction(II)) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +000035 // Replaces all of the uses of a variable with uses of the constant.
Chris Lattner18961502002-06-25 16:12:52 +000036 II->replaceAllUsesWith(C);
Misha Brukmanfd939082005-04-21 23:48:37 +000037
Chris Lattner4d1e46e2002-05-07 18:07:59 +000038 // Remove the instruction from the basic block...
Chris Lattner18961502002-06-25 16:12:52 +000039 II = II->getParent()->getInstList().erase(II);
Chris Lattner4d1e46e2002-05-07 18:07:59 +000040 return true;
41 }
42
43 return false;
44}
45
Chris Lattner8f90b002004-01-12 18:25:22 +000046/// ConstantFoldInstruction - Attempt to constant fold the specified
47/// instruction. If successful, the constant result is returned, if not, null
48/// is returned. Note that this function can only fail when attempting to fold
49/// instructions like loads and stores, which have no constant expression form.
50///
51Constant *llvm::ConstantFoldInstruction(Instruction *I) {
52 if (PHINode *PN = dyn_cast<PHINode>(I)) {
53 if (PN->getNumIncomingValues() == 0)
54 return Constant::getNullValue(PN->getType());
Misha Brukmanfd939082005-04-21 23:48:37 +000055
Chris Lattner8f90b002004-01-12 18:25:22 +000056 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
57 if (Result == 0) return 0;
58
59 // Handle PHI nodes specially here...
60 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
61 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
62 return 0; // Not all the same incoming constants...
Misha Brukmanfd939082005-04-21 23:48:37 +000063
Chris Lattner8f90b002004-01-12 18:25:22 +000064 // If we reach here, all incoming values are the same constant.
65 return Result;
Chris Lattner25b83902004-04-13 19:28:52 +000066 } else if (CallInst *CI = dyn_cast<CallInst>(I)) {
67 if (Function *F = CI->getCalledFunction())
68 if (canConstantFoldCallTo(F)) {
69 std::vector<Constant*> Args;
70 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
71 if (Constant *Op = dyn_cast<Constant>(CI->getOperand(i)))
72 Args.push_back(Op);
73 else
74 return 0;
75 return ConstantFoldCall(F, Args);
76 }
77 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +000078 }
79
80 Constant *Op0 = 0, *Op1 = 0;
81 switch (I->getNumOperands()) {
82 default:
83 case 2:
84 Op1 = dyn_cast<Constant>(I->getOperand(1));
85 if (Op1 == 0) return 0; // Not a constant?, can't fold
86 case 1:
87 Op0 = dyn_cast<Constant>(I->getOperand(0));
88 if (Op0 == 0) return 0; // Not a constant?, can't fold
89 break;
90 case 0: return 0;
91 }
92
Chris Lattnerc6646eb2004-01-12 19:10:58 +000093 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
Misha Brukmanfd939082005-04-21 23:48:37 +000094 return ConstantExpr::get(I->getOpcode(), Op0, Op1);
Chris Lattner8f90b002004-01-12 18:25:22 +000095
96 switch (I->getOpcode()) {
97 default: return 0;
98 case Instruction::Cast:
99 return ConstantExpr::getCast(Op0, I->getType());
Chris Lattner17fd2732004-03-12 05:53:03 +0000100 case Instruction::Select:
101 if (Constant *Op2 = dyn_cast<Constant>(I->getOperand(2)))
102 return ConstantExpr::getSelect(Op0, Op1, Op2);
103 return 0;
Chris Lattner8f90b002004-01-12 18:25:22 +0000104 case Instruction::GetElementPtr:
105 std::vector<Constant*> IdxList;
106 IdxList.reserve(I->getNumOperands()-1);
107 if (Op1) IdxList.push_back(Op1);
108 for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)
109 if (Constant *C = dyn_cast<Constant>(I->getOperand(i)))
110 IdxList.push_back(C);
111 else
112 return 0; // Non-constant operand
113 return ConstantExpr::getGetElementPtr(Op0, IdxList);
114 }
115}
116
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000117// ConstantFoldTerminator - If a terminator instruction is predicated on a
118// constant value, convert it into an unconditional branch to the constant
119// destination.
120//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000121bool llvm::ConstantFoldTerminator(BasicBlock *BB) {
Chris Lattner76ae3442002-05-21 20:04:50 +0000122 TerminatorInst *T = BB->getTerminator();
Misha Brukmanfd939082005-04-21 23:48:37 +0000123
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000124 // Branch - See if we are conditional jumping on constant
125 if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
126 if (BI->isUnconditional()) return false; // Can't optimize uncond branch
127 BasicBlock *Dest1 = cast<BasicBlock>(BI->getOperand(0));
128 BasicBlock *Dest2 = cast<BasicBlock>(BI->getOperand(1));
129
130 if (ConstantBool *Cond = dyn_cast<ConstantBool>(BI->getCondition())) {
131 // Are we branching on constant?
132 // YES. Change to unconditional branch...
133 BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;
134 BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;
135
Misha Brukmanfd939082005-04-21 23:48:37 +0000136 //cerr << "Function: " << T->getParent()->getParent()
137 // << "\nRemoving branch from " << T->getParent()
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000138 // << "\n\nTo: " << OldDest << endl;
139
140 // Let the basic block know that we are letting go of it. Based on this,
141 // it will adjust it's PHI nodes.
142 assert(BI->getParent() && "Terminator not inserted in block!");
143 OldDest->removePredecessor(BI->getParent());
144
145 // Set the unconditional destination, and change the insn to be an
146 // unconditional branch.
147 BI->setUnconditionalDest(Destination);
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000148 return true;
Chris Lattner342a9d12003-08-17 19:34:55 +0000149 } else if (Dest2 == Dest1) { // Conditional branch to same location?
Misha Brukmanfd939082005-04-21 23:48:37 +0000150 // This branch matches something like this:
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000151 // br bool %cond, label %Dest, label %Dest
152 // and changes it into: br label %Dest
153
154 // Let the basic block know that we are letting go of one copy of it.
155 assert(BI->getParent() && "Terminator not inserted in block!");
156 Dest1->removePredecessor(BI->getParent());
157
158 // Change a conditional branch to unconditional.
159 BI->setUnconditionalDest(Dest1);
160 return true;
161 }
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000162 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(T)) {
163 // If we are switching on a constant, we can convert the switch into a
164 // single branch instruction!
165 ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition());
166 BasicBlock *TheOnlyDest = SI->getSuccessor(0); // The default dest
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000167 BasicBlock *DefaultDest = TheOnlyDest;
168 assert(TheOnlyDest == SI->getDefaultDest() &&
169 "Default destination is not successor #0?");
Chris Lattner694e37f2003-08-17 19:41:53 +0000170
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000171 // Figure out which case it goes to...
172 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {
173 // Found case matching a constant operand?
174 if (SI->getSuccessorValue(i) == CI) {
175 TheOnlyDest = SI->getSuccessor(i);
176 break;
177 }
Chris Lattner694e37f2003-08-17 19:41:53 +0000178
Chris Lattner7d6c24c2003-08-23 23:18:19 +0000179 // Check to see if this branch is going to the same place as the default
180 // dest. If so, eliminate it as an explicit compare.
181 if (SI->getSuccessor(i) == DefaultDest) {
182 // Remove this entry...
183 DefaultDest->removePredecessor(SI->getParent());
184 SI->removeCase(i);
185 --i; --e; // Don't skip an entry...
186 continue;
187 }
188
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000189 // Otherwise, check to see if the switch only branches to one destination.
190 // We do this by reseting "TheOnlyDest" to null when we find two non-equal
191 // destinations.
192 if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;
Chris Lattner694e37f2003-08-17 19:41:53 +0000193 }
194
Chris Lattner10b1f5a2003-08-17 20:21:14 +0000195 if (CI && !TheOnlyDest) {
196 // Branching on a constant, but not any of the cases, go to the default
197 // successor.
198 TheOnlyDest = SI->getDefaultDest();
199 }
200
201 // If we found a single destination that we can fold the switch into, do so
202 // now.
203 if (TheOnlyDest) {
204 // Insert the new branch..
205 new BranchInst(TheOnlyDest, SI);
206 BasicBlock *BB = SI->getParent();
207
208 // Remove entries from PHI nodes which we no longer branch to...
209 for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
210 // Found case matching a constant operand?
211 BasicBlock *Succ = SI->getSuccessor(i);
212 if (Succ == TheOnlyDest)
213 TheOnlyDest = 0; // Don't modify the first branch to TheOnlyDest
214 else
215 Succ->removePredecessor(BB);
216 }
217
218 // Delete the old switch...
219 BB->getInstList().erase(SI);
220 return true;
221 } else if (SI->getNumSuccessors() == 2) {
222 // Otherwise, we can fold this switch into a conditional branch
223 // instruction if it has only one non-default destination.
224 Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),
225 SI->getSuccessorValue(1), "cond", SI);
226 // Insert the new branch...
227 new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);
228
229 // Delete the old switch...
230 SI->getParent()->getInstList().erase(SI);
231 return true;
232 }
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000233 }
234 return false;
235}
236
Chris Lattner25b83902004-04-13 19:28:52 +0000237/// canConstantFoldCallTo - Return true if its even possible to fold a call to
238/// the specified function.
239bool llvm::canConstantFoldCallTo(Function *F) {
240 const std::string &Name = F->getName();
Chris Lattnercf110352004-06-11 06:16:23 +0000241
242 switch (F->getIntrinsicID()) {
Chris Lattner32643d82005-09-28 01:34:32 +0000243 case Intrinsic::isunordered:
244 case Intrinsic::sqrt:
245 return true;
Chris Lattnercf110352004-06-11 06:16:23 +0000246 default: break;
247 }
248
Reid Spencer1d3b7182005-04-28 23:01:59 +0000249 switch (Name[0])
250 {
251 case 'a':
Jeff Cohen00b168892005-07-27 06:12:32 +0000252 return Name == "acos" || Name == "asin" || Name == "atan" ||
Reid Spencer1d3b7182005-04-28 23:01:59 +0000253 Name == "atan2";
254 case 'c':
Jeff Cohen00b168892005-07-27 06:12:32 +0000255 return Name == "ceil" || Name == "cos" || Name == "cosf" ||
Reid Spencer1d3b7182005-04-28 23:01:59 +0000256 Name == "cosh";
257 case 'e':
258 return Name == "exp";
259 case 'f':
260 return Name == "fabs" || Name == "fmod" || Name == "floor";
261 case 'l':
262 return Name == "log" || Name == "log10";
263 case 'p':
264 return Name == "pow";
265 case 's':
266 return Name == "sin" || Name == "sinh" || Name == "sqrt";
267 case 't':
268 return Name == "tan" || Name == "tanh";
269 default:
270 return false;
271 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000272}
273
274static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
275 const Type *Ty) {
276 errno = 0;
277 V = NativeFP(V);
278 if (errno == 0)
279 return ConstantFP::get(Ty, V);
280 return 0;
Chris Lattner25b83902004-04-13 19:28:52 +0000281}
282
283/// ConstantFoldCall - Attempt to constant fold a call to the specified function
284/// with the specified arguments, returning null if unsuccessful.
285Constant *llvm::ConstantFoldCall(Function *F,
286 const std::vector<Constant*> &Operands) {
287 const std::string &Name = F->getName();
288 const Type *Ty = F->getReturnType();
289
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000290 if (Operands.size() == 1) {
291 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
292 double V = Op->getValue();
Reid Spencer1d3b7182005-04-28 23:01:59 +0000293 switch (Name[0])
294 {
295 case 'a':
296 if (Name == "acos")
297 return ConstantFoldFP(acos, V, Ty);
298 else if (Name == "asin")
299 return ConstantFoldFP(asin, V, Ty);
300 else if (Name == "atan")
301 return ConstantFP::get(Ty, atan(V));
302 break;
303 case 'c':
304 if (Name == "ceil")
305 return ConstantFoldFP(ceil, V, Ty);
306 else if (Name == "cos")
307 return ConstantFP::get(Ty, cos(V));
308 else if (Name == "cosh")
309 return ConstantFP::get(Ty, cosh(V));
310 break;
311 case 'e':
312 if (Name == "exp")
313 return ConstantFP::get(Ty, exp(V));
314 break;
315 case 'f':
316 if (Name == "fabs")
317 return ConstantFP::get(Ty, fabs(V));
318 else if (Name == "floor")
319 return ConstantFoldFP(floor, V, Ty);
320 break;
321 case 'l':
322 if (Name == "log" && V > 0)
323 return ConstantFP::get(Ty, log(V));
324 else if (Name == "log10" && V > 0)
325 return ConstantFoldFP(log10, V, Ty);
Chris Lattner32643d82005-09-28 01:34:32 +0000326 else if (Name == "llvm.sqrt") {
327 if (V >= -0.0)
328 return ConstantFP::get(Ty, sqrt(V));
329 else // Undefined
330 return ConstantFP::get(Ty, 0.0);
331 }
Reid Spencer1d3b7182005-04-28 23:01:59 +0000332 break;
333 case 's':
334 if (Name == "sin")
335 return ConstantFP::get(Ty, sin(V));
336 else if (Name == "sinh")
337 return ConstantFP::get(Ty, sinh(V));
338 else if (Name == "sqrt" && V >= 0)
339 return ConstantFP::get(Ty, sqrt(V));
340 break;
341 case 't':
342 if (Name == "tan")
343 return ConstantFP::get(Ty, tan(V));
344 else if (Name == "tanh")
345 return ConstantFP::get(Ty, tanh(V));
346 break;
347 default:
348 break;
349 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000350 }
351 } else if (Operands.size() == 2) {
Reid Spencer1d3b7182005-04-28 23:01:59 +0000352 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
353 double Op1V = Op1->getValue();
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000354 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Reid Spencer1d3b7182005-04-28 23:01:59 +0000355 double Op2V = Op2->getValue();
Chris Lattner8dfe5702004-05-27 07:25:00 +0000356
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000357 if (Name == "llvm.isunordered")
Brian Gaeke1f2b8922004-06-23 00:25:35 +0000358 return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V));
Misha Brukmanfd939082005-04-21 23:48:37 +0000359 else
Chris Lattner30c02f72004-06-21 06:17:21 +0000360 if (Name == "pow") {
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000361 errno = 0;
Chris Lattner8dfe5702004-05-27 07:25:00 +0000362 double V = pow(Op1V, Op2V);
363 if (errno == 0)
364 return ConstantFP::get(Ty, V);
365 } else if (Name == "fmod") {
366 errno = 0;
367 double V = fmod(Op1V, Op2V);
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000368 if (errno == 0)
369 return ConstantFP::get(Ty, V);
Reid Spencer1d3b7182005-04-28 23:01:59 +0000370 } else if (Name == "atan2")
371 return ConstantFP::get(Ty, atan2(Op1V,Op2V));
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000372 }
Reid Spencer1d3b7182005-04-28 23:01:59 +0000373 }
Chris Lattner25b83902004-04-13 19:28:52 +0000374 }
375 return 0;
376}
377
378
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000379/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
380/// getelementptr constantexpr, return the constant value being addressed by the
381/// constant expression, or null if something is funny and we can't decide.
382Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
383 ConstantExpr *CE) {
384 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
385 return 0; // Do not allow stepping over the value!
386
387 // Loop over all of the operands, tracking down which value we are
388 // addressing...
389 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
390 for (++I; I != E; ++I)
391 if (const StructType *STy = dyn_cast<StructType>(*I)) {
392 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
393 assert(CU->getValue() < STy->getNumElements() &&
394 "Struct index out of range!");
395 unsigned El = (unsigned)CU->getValue();
396 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
397 C = CS->getOperand(El);
398 } else if (isa<ConstantAggregateZero>(C)) {
399 C = Constant::getNullValue(STy->getElementType(El));
400 } else if (isa<UndefValue>(C)) {
401 C = UndefValue::get(STy->getElementType(El));
402 } else {
403 return 0;
404 }
405 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
406 const ArrayType *ATy = cast<ArrayType>(*I);
407 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
408 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
409 C = CA->getOperand((unsigned)CI->getRawValue());
410 else if (isa<ConstantAggregateZero>(C))
411 C = Constant::getNullValue(ATy->getElementType());
412 else if (isa<UndefValue>(C))
413 C = UndefValue::get(ATy->getElementType());
414 else
415 return 0;
416 } else {
417 return 0;
418 }
419 return C;
420}
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000421
422
423//===----------------------------------------------------------------------===//
424// Local dead code elimination...
425//
426
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000427bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000428 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000429
Chris Lattnerec710c52005-05-06 05:27:34 +0000430 if (!I->mayWriteToMemory()) return true;
431
432 if (CallInst *CI = dyn_cast<CallInst>(I))
433 if (Function *F = CI->getCalledFunction())
434 switch (F->getIntrinsicID()) {
435 default: break;
Chris Lattnerec710c52005-05-06 05:27:34 +0000436 case Intrinsic::returnaddress:
437 case Intrinsic::frameaddress:
438 case Intrinsic::isunordered:
439 case Intrinsic::ctpop:
440 case Intrinsic::ctlz:
441 case Intrinsic::cttz:
442 case Intrinsic::sqrt:
443 return true; // These intrinsics have no side effects.
444 }
445 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000446}
447
448// dceInstruction - Inspect the instruction at *BBI and figure out if it's
449// [trivially] dead. If so, remove the instruction and update the iterator
450// to point to the instruction that immediately succeeded the original
451// instruction.
452//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000453bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000454 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000455 if (isInstructionTriviallyDead(BBI)) {
456 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000457 return true;
458 }
459 return false;
460}