blob: b1dd58331b6092e319f145fed5756b9ecba9c07e [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()) {
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000243 case Intrinsic::isunordered: return true;
Chris Lattnercf110352004-06-11 06:16:23 +0000244 default: break;
245 }
246
Reid Spencer1d3b7182005-04-28 23:01:59 +0000247 switch (Name[0])
248 {
249 case 'a':
Jeff Cohen00b168892005-07-27 06:12:32 +0000250 return Name == "acos" || Name == "asin" || Name == "atan" ||
Reid Spencer1d3b7182005-04-28 23:01:59 +0000251 Name == "atan2";
252 case 'c':
Jeff Cohen00b168892005-07-27 06:12:32 +0000253 return Name == "ceil" || Name == "cos" || Name == "cosf" ||
Reid Spencer1d3b7182005-04-28 23:01:59 +0000254 Name == "cosh";
255 case 'e':
256 return Name == "exp";
257 case 'f':
258 return Name == "fabs" || Name == "fmod" || Name == "floor";
259 case 'l':
260 return Name == "log" || Name == "log10";
261 case 'p':
262 return Name == "pow";
263 case 's':
264 return Name == "sin" || Name == "sinh" || Name == "sqrt";
265 case 't':
266 return Name == "tan" || Name == "tanh";
267 default:
268 return false;
269 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000270}
271
272static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
273 const Type *Ty) {
274 errno = 0;
275 V = NativeFP(V);
276 if (errno == 0)
277 return ConstantFP::get(Ty, V);
278 return 0;
Chris Lattner25b83902004-04-13 19:28:52 +0000279}
280
281/// ConstantFoldCall - Attempt to constant fold a call to the specified function
282/// with the specified arguments, returning null if unsuccessful.
283Constant *llvm::ConstantFoldCall(Function *F,
284 const std::vector<Constant*> &Operands) {
285 const std::string &Name = F->getName();
286 const Type *Ty = F->getReturnType();
287
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000288 if (Operands.size() == 1) {
289 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
290 double V = Op->getValue();
Reid Spencer1d3b7182005-04-28 23:01:59 +0000291 switch (Name[0])
292 {
293 case 'a':
294 if (Name == "acos")
295 return ConstantFoldFP(acos, V, Ty);
296 else if (Name == "asin")
297 return ConstantFoldFP(asin, V, Ty);
298 else if (Name == "atan")
299 return ConstantFP::get(Ty, atan(V));
300 break;
301 case 'c':
302 if (Name == "ceil")
303 return ConstantFoldFP(ceil, V, Ty);
304 else if (Name == "cos")
305 return ConstantFP::get(Ty, cos(V));
306 else if (Name == "cosh")
307 return ConstantFP::get(Ty, cosh(V));
308 break;
309 case 'e':
310 if (Name == "exp")
311 return ConstantFP::get(Ty, exp(V));
312 break;
313 case 'f':
314 if (Name == "fabs")
315 return ConstantFP::get(Ty, fabs(V));
316 else if (Name == "floor")
317 return ConstantFoldFP(floor, V, Ty);
318 break;
319 case 'l':
320 if (Name == "log" && V > 0)
321 return ConstantFP::get(Ty, log(V));
322 else if (Name == "log10" && V > 0)
323 return ConstantFoldFP(log10, V, Ty);
324 break;
325 case 's':
326 if (Name == "sin")
327 return ConstantFP::get(Ty, sin(V));
328 else if (Name == "sinh")
329 return ConstantFP::get(Ty, sinh(V));
330 else if (Name == "sqrt" && V >= 0)
331 return ConstantFP::get(Ty, sqrt(V));
332 break;
333 case 't':
334 if (Name == "tan")
335 return ConstantFP::get(Ty, tan(V));
336 else if (Name == "tanh")
337 return ConstantFP::get(Ty, tanh(V));
338 break;
339 default:
340 break;
341 }
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000342 }
343 } else if (Operands.size() == 2) {
Reid Spencer1d3b7182005-04-28 23:01:59 +0000344 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
345 double Op1V = Op1->getValue();
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000346 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Reid Spencer1d3b7182005-04-28 23:01:59 +0000347 double Op2V = Op2->getValue();
Chris Lattner8dfe5702004-05-27 07:25:00 +0000348
Alkis Evlogimenosdf497312004-06-13 01:23:56 +0000349 if (Name == "llvm.isunordered")
Brian Gaeke1f2b8922004-06-23 00:25:35 +0000350 return ConstantBool::get(IsNAN(Op1V) || IsNAN(Op2V));
Misha Brukmanfd939082005-04-21 23:48:37 +0000351 else
Chris Lattner30c02f72004-06-21 06:17:21 +0000352 if (Name == "pow") {
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000353 errno = 0;
Chris Lattner8dfe5702004-05-27 07:25:00 +0000354 double V = pow(Op1V, Op2V);
355 if (errno == 0)
356 return ConstantFP::get(Ty, V);
357 } else if (Name == "fmod") {
358 errno = 0;
359 double V = fmod(Op1V, Op2V);
Chris Lattnerf5b9eb32004-04-16 22:35:33 +0000360 if (errno == 0)
361 return ConstantFP::get(Ty, V);
Reid Spencer1d3b7182005-04-28 23:01:59 +0000362 } else if (Name == "atan2")
363 return ConstantFP::get(Ty, atan2(Op1V,Op2V));
Chris Lattnerb18b9d72004-05-27 06:26:28 +0000364 }
Reid Spencer1d3b7182005-04-28 23:01:59 +0000365 }
Chris Lattner25b83902004-04-13 19:28:52 +0000366 }
367 return 0;
368}
369
370
Chris Lattnerc5f52e62005-09-26 05:27:10 +0000371/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
372/// getelementptr constantexpr, return the constant value being addressed by the
373/// constant expression, or null if something is funny and we can't decide.
374Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
375 ConstantExpr *CE) {
376 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
377 return 0; // Do not allow stepping over the value!
378
379 // Loop over all of the operands, tracking down which value we are
380 // addressing...
381 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
382 for (++I; I != E; ++I)
383 if (const StructType *STy = dyn_cast<StructType>(*I)) {
384 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
385 assert(CU->getValue() < STy->getNumElements() &&
386 "Struct index out of range!");
387 unsigned El = (unsigned)CU->getValue();
388 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
389 C = CS->getOperand(El);
390 } else if (isa<ConstantAggregateZero>(C)) {
391 C = Constant::getNullValue(STy->getElementType(El));
392 } else if (isa<UndefValue>(C)) {
393 C = UndefValue::get(STy->getElementType(El));
394 } else {
395 return 0;
396 }
397 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
398 const ArrayType *ATy = cast<ArrayType>(*I);
399 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
400 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
401 C = CA->getOperand((unsigned)CI->getRawValue());
402 else if (isa<ConstantAggregateZero>(C))
403 C = Constant::getNullValue(ATy->getElementType());
404 else if (isa<UndefValue>(C))
405 C = UndefValue::get(ATy->getElementType());
406 else
407 return 0;
408 } else {
409 return 0;
410 }
411 return C;
412}
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000413
414
415//===----------------------------------------------------------------------===//
416// Local dead code elimination...
417//
418
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000419bool llvm::isInstructionTriviallyDead(Instruction *I) {
Chris Lattnerec710c52005-05-06 05:27:34 +0000420 if (!I->use_empty() || isa<TerminatorInst>(I)) return false;
Jeff Cohen00b168892005-07-27 06:12:32 +0000421
Chris Lattnerec710c52005-05-06 05:27:34 +0000422 if (!I->mayWriteToMemory()) return true;
423
424 if (CallInst *CI = dyn_cast<CallInst>(I))
425 if (Function *F = CI->getCalledFunction())
426 switch (F->getIntrinsicID()) {
427 default: break;
Chris Lattnerec710c52005-05-06 05:27:34 +0000428 case Intrinsic::returnaddress:
429 case Intrinsic::frameaddress:
430 case Intrinsic::isunordered:
431 case Intrinsic::ctpop:
432 case Intrinsic::ctlz:
433 case Intrinsic::cttz:
434 case Intrinsic::sqrt:
435 return true; // These intrinsics have no side effects.
436 }
437 return false;
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000438}
439
440// dceInstruction - Inspect the instruction at *BBI and figure out if it's
441// [trivially] dead. If so, remove the instruction and update the iterator
442// to point to the instruction that immediately succeeded the original
443// instruction.
444//
Chris Lattnerabbc2dd2003-12-19 05:56:28 +0000445bool llvm::dceInstruction(BasicBlock::iterator &BBI) {
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000446 // Look for un"used" definitions...
Chris Lattner18961502002-06-25 16:12:52 +0000447 if (isInstructionTriviallyDead(BBI)) {
448 BBI = BBI->getParent()->getInstList().erase(BBI); // Bye bye
Chris Lattner4d1e46e2002-05-07 18:07:59 +0000449 return true;
450 }
451 return false;
452}