blob: 1515301a77a6f2dbe07d610bf4ccf22f6480f40e [file] [log] [blame]
John Criswellbd9d3702005-10-27 16:00:10 +00001//===-- ConstantFolding.cpp - Analyze constant folding possibilities ------===//
2//
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//===----------------------------------------------------------------------===//
9//
10// This family of functions determines the possibility of performing constant
11// folding.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Analysis/ConstantFolding.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
Chris Lattner55207322007-01-30 23:45:45 +000018#include "llvm/Function.h"
John Criswellbd9d3702005-10-27 16:00:10 +000019#include "llvm/Instructions.h"
20#include "llvm/Intrinsics.h"
Chris Lattner55207322007-01-30 23:45:45 +000021#include "llvm/ADT/SmallVector.h"
Chris Lattner03dd25c2007-01-31 00:51:48 +000022#include "llvm/Target/TargetData.h"
John Criswellbd9d3702005-10-27 16:00:10 +000023#include "llvm/Support/GetElementPtrTypeIterator.h"
24#include "llvm/Support/MathExtras.h"
25#include <cerrno>
Jeff Cohen97af7512006-12-02 02:22:01 +000026#include <cmath>
John Criswellbd9d3702005-10-27 16:00:10 +000027using namespace llvm;
28
Chris Lattner03dd25c2007-01-31 00:51:48 +000029//===----------------------------------------------------------------------===//
30// Constant Folding internal helper functions
31//===----------------------------------------------------------------------===//
32
33/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
34/// from a global, return the global and the constant. Because of
35/// constantexprs, this function is recursive.
36static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
37 int64_t &Offset, const TargetData &TD) {
38 // Trivial case, constant is the global.
39 if ((GV = dyn_cast<GlobalValue>(C))) {
40 Offset = 0;
41 return true;
42 }
43
44 // Otherwise, if this isn't a constant expr, bail out.
45 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
46 if (!CE) return false;
47
48 // Look through ptr->int and ptr->ptr casts.
49 if (CE->getOpcode() == Instruction::PtrToInt ||
50 CE->getOpcode() == Instruction::BitCast)
51 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
52
53 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
54 if (CE->getOpcode() == Instruction::GetElementPtr) {
55 // Cannot compute this if the element type of the pointer is missing size
56 // info.
57 if (!cast<PointerType>(CE->getOperand(0)->getType())->getElementType()->isSized())
58 return false;
59
60 // If the base isn't a global+constant, we aren't either.
61 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD))
62 return false;
63
64 // Otherwise, add any offset that our operands provide.
65 gep_type_iterator GTI = gep_type_begin(CE);
66 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i, ++GTI) {
67 ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(i));
68 if (!CI) return false; // Index isn't a simple constant?
69 if (CI->getZExtValue() == 0) continue; // Not adding anything.
70
71 if (const StructType *ST = dyn_cast<StructType>(*GTI)) {
72 // N = N + Offset
Chris Lattnerb1919e22007-02-10 19:55:17 +000073 Offset += TD.getStructLayout(ST)->getElementOffset(CI->getZExtValue());
Chris Lattner03dd25c2007-01-31 00:51:48 +000074 } else {
75 const SequentialType *ST = cast<SequentialType>(*GTI);
76 Offset += TD.getTypeSize(ST->getElementType())*CI->getSExtValue();
77 }
78 }
79 return true;
80 }
81
82 return false;
83}
84
85
86/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
87/// Attempt to symbolically evaluate the result of a binary operator merging
88/// these together. If target data info is available, it is provided as TD,
89/// otherwise TD is null.
90static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
91 Constant *Op1, const TargetData *TD){
92 // SROA
93
94 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
95 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
96 // bits.
97
98
99 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
100 // constant. This happens frequently when iterating over a global array.
101 if (Opc == Instruction::Sub && TD) {
102 GlobalValue *GV1, *GV2;
103 int64_t Offs1, Offs2;
104
105 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *TD))
106 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *TD) &&
107 GV1 == GV2) {
108 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
109 return ConstantInt::get(Op0->getType(), Offs1-Offs2);
110 }
111 }
112
113 // TODO: Fold icmp setne/seteq as well.
114 return 0;
115}
116
117/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
118/// constant expression, do so.
119static Constant *SymbolicallyEvaluateGEP(Constant** Ops, unsigned NumOps,
120 const Type *ResultTy,
121 const TargetData *TD) {
122 Constant *Ptr = Ops[0];
123 if (!cast<PointerType>(Ptr->getType())->getElementType()->isSized())
124 return 0;
125
126 if (TD && Ptr->isNullValue()) {
127 // If this is a constant expr gep that is effectively computing an
128 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
129 bool isFoldableGEP = true;
130 for (unsigned i = 1; i != NumOps; ++i)
131 if (!isa<ConstantInt>(Ops[i])) {
132 isFoldableGEP = false;
133 break;
134 }
135 if (isFoldableGEP) {
136 std::vector<Value*> NewOps(Ops+1, Ops+NumOps);
137 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), NewOps);
138 Constant *C = ConstantInt::get(TD->getIntPtrType(), Offset);
139 return ConstantExpr::getIntToPtr(C, ResultTy);
140 }
141 }
142
143 return 0;
144}
145
146
147//===----------------------------------------------------------------------===//
148// Constant Folding public APIs
149//===----------------------------------------------------------------------===//
150
151
Chris Lattner55207322007-01-30 23:45:45 +0000152/// ConstantFoldInstruction - Attempt to constant fold the specified
153/// instruction. If successful, the constant result is returned, if not, null
154/// is returned. Note that this function can only fail when attempting to fold
155/// instructions like loads and stores, which have no constant expression form.
156///
157Constant *llvm::ConstantFoldInstruction(Instruction *I, const TargetData *TD) {
158 if (PHINode *PN = dyn_cast<PHINode>(I)) {
159 if (PN->getNumIncomingValues() == 0)
160 return Constant::getNullValue(PN->getType());
John Criswellbd9d3702005-10-27 16:00:10 +0000161
Chris Lattner55207322007-01-30 23:45:45 +0000162 Constant *Result = dyn_cast<Constant>(PN->getIncomingValue(0));
163 if (Result == 0) return 0;
164
165 // Handle PHI nodes specially here...
166 for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)
167 if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)
168 return 0; // Not all the same incoming constants...
169
170 // If we reach here, all incoming values are the same constant.
171 return Result;
172 }
173
174 // Scan the operand list, checking to see if they are all constants, if so,
175 // hand off to ConstantFoldInstOperands.
176 SmallVector<Constant*, 8> Ops;
177 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
178 if (Constant *Op = dyn_cast<Constant>(I->getOperand(i)))
179 Ops.push_back(Op);
180 else
181 return 0; // All operands not constant!
182
Chris Lattner03dd25c2007-01-31 00:51:48 +0000183 return ConstantFoldInstOperands(I, &Ops[0], Ops.size(), TD);
Chris Lattner55207322007-01-30 23:45:45 +0000184}
185
186/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
187/// specified opcode and operands. If successful, the constant result is
188/// returned, if not, null is returned. Note that this function can fail when
189/// attempting to fold instructions like loads and stores, which have no
190/// constant expression form.
191///
192Constant *llvm::ConstantFoldInstOperands(const Instruction* I,
193 Constant** Ops, unsigned NumOps,
194 const TargetData *TD) {
195 unsigned Opc = I->getOpcode();
196 const Type *DestTy = I->getType();
197
Chris Lattner03dd25c2007-01-31 00:51:48 +0000198 // Handle easy binops first.
199 if (isa<BinaryOperator>(I)) {
200 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1]))
201 if (Constant *C = SymbolicallyEvaluateBinop(I->getOpcode(), Ops[0],
202 Ops[1], TD))
203 return C;
204
Chris Lattner55207322007-01-30 23:45:45 +0000205 return ConstantExpr::get(Opc, Ops[0], Ops[1]);
Chris Lattner03dd25c2007-01-31 00:51:48 +0000206 }
Chris Lattner55207322007-01-30 23:45:45 +0000207
208 switch (Opc) {
209 default: return 0;
210 case Instruction::Call:
211 if (Function *F = dyn_cast<Function>(Ops[0]))
212 if (canConstantFoldCallTo(F))
Chris Lattnerad58eb32007-01-31 18:04:55 +0000213 return ConstantFoldCall(F, Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000214 return 0;
215 case Instruction::ICmp:
216 case Instruction::FCmp:
217 return ConstantExpr::getCompare(cast<CmpInst>(I)->getPredicate(), Ops[0],
218 Ops[1]);
Chris Lattner55207322007-01-30 23:45:45 +0000219 case Instruction::Trunc:
220 case Instruction::ZExt:
221 case Instruction::SExt:
222 case Instruction::FPTrunc:
223 case Instruction::FPExt:
224 case Instruction::UIToFP:
225 case Instruction::SIToFP:
226 case Instruction::FPToUI:
227 case Instruction::FPToSI:
228 case Instruction::PtrToInt:
229 case Instruction::IntToPtr:
230 case Instruction::BitCast:
231 return ConstantExpr::getCast(Opc, Ops[0], DestTy);
232 case Instruction::Select:
233 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
234 case Instruction::ExtractElement:
235 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
236 case Instruction::InsertElement:
237 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
238 case Instruction::ShuffleVector:
239 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
240 case Instruction::GetElementPtr:
Chris Lattner03dd25c2007-01-31 00:51:48 +0000241 if (Constant *C = SymbolicallyEvaluateGEP(Ops, NumOps, I->getType(), TD))
242 return C;
243
Chris Lattnerd917fe52007-01-31 04:42:05 +0000244 return ConstantExpr::getGetElementPtr(Ops[0], Ops+1, NumOps-1);
Chris Lattner55207322007-01-30 23:45:45 +0000245 }
246}
247
248/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
249/// getelementptr constantexpr, return the constant value being addressed by the
250/// constant expression, or null if something is funny and we can't decide.
251Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
252 ConstantExpr *CE) {
253 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
254 return 0; // Do not allow stepping over the value!
255
256 // Loop over all of the operands, tracking down which value we are
257 // addressing...
258 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
259 for (++I; I != E; ++I)
260 if (const StructType *STy = dyn_cast<StructType>(*I)) {
261 ConstantInt *CU = cast<ConstantInt>(I.getOperand());
262 assert(CU->getZExtValue() < STy->getNumElements() &&
263 "Struct index out of range!");
264 unsigned El = (unsigned)CU->getZExtValue();
265 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
266 C = CS->getOperand(El);
267 } else if (isa<ConstantAggregateZero>(C)) {
268 C = Constant::getNullValue(STy->getElementType(El));
269 } else if (isa<UndefValue>(C)) {
270 C = UndefValue::get(STy->getElementType(El));
271 } else {
272 return 0;
273 }
274 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
275 if (const ArrayType *ATy = dyn_cast<ArrayType>(*I)) {
276 if (CI->getZExtValue() >= ATy->getNumElements())
277 return 0;
278 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
279 C = CA->getOperand(CI->getZExtValue());
280 else if (isa<ConstantAggregateZero>(C))
281 C = Constant::getNullValue(ATy->getElementType());
282 else if (isa<UndefValue>(C))
283 C = UndefValue::get(ATy->getElementType());
284 else
285 return 0;
286 } else if (const PackedType *PTy = dyn_cast<PackedType>(*I)) {
287 if (CI->getZExtValue() >= PTy->getNumElements())
288 return 0;
289 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(C))
290 C = CP->getOperand(CI->getZExtValue());
291 else if (isa<ConstantAggregateZero>(C))
292 C = Constant::getNullValue(PTy->getElementType());
293 else if (isa<UndefValue>(C))
294 C = UndefValue::get(PTy->getElementType());
295 else
296 return 0;
297 } else {
298 return 0;
299 }
300 } else {
301 return 0;
302 }
303 return C;
304}
305
306
307//===----------------------------------------------------------------------===//
308// Constant Folding for Calls
309//
John Criswellbd9d3702005-10-27 16:00:10 +0000310
311/// canConstantFoldCallTo - Return true if its even possible to fold a call to
312/// the specified function.
313bool
314llvm::canConstantFoldCallTo(Function *F) {
315 const std::string &Name = F->getName();
316
317 switch (F->getIntrinsicID()) {
Reid Spencer0b118202006-01-16 21:12:35 +0000318 case Intrinsic::sqrt_f32:
319 case Intrinsic::sqrt_f64:
Nate Begeman6fb3bd62006-01-14 01:25:24 +0000320 case Intrinsic::bswap_i16:
321 case Intrinsic::bswap_i32:
322 case Intrinsic::bswap_i64:
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000323 case Intrinsic::powi_f32:
324 case Intrinsic::powi_f64:
Nate Begeman6fb3bd62006-01-14 01:25:24 +0000325 // FIXME: these should be constant folded as well
Reid Spencer0b118202006-01-16 21:12:35 +0000326 //case Intrinsic::ctpop_i8:
327 //case Intrinsic::ctpop_i16:
328 //case Intrinsic::ctpop_i32:
329 //case Intrinsic::ctpop_i64:
330 //case Intrinsic::ctlz_i8:
331 //case Intrinsic::ctlz_i16:
332 //case Intrinsic::ctlz_i32:
333 //case Intrinsic::ctlz_i64:
334 //case Intrinsic::cttz_i8:
335 //case Intrinsic::cttz_i16:
336 //case Intrinsic::cttz_i32:
337 //case Intrinsic::cttz_i64:
John Criswellbd9d3702005-10-27 16:00:10 +0000338 return true;
339 default: break;
340 }
341
342 switch (Name[0])
343 {
344 case 'a':
345 return Name == "acos" || Name == "asin" || Name == "atan" ||
346 Name == "atan2";
347 case 'c':
348 return Name == "ceil" || Name == "cos" || Name == "cosf" ||
349 Name == "cosh";
350 case 'e':
351 return Name == "exp";
352 case 'f':
353 return Name == "fabs" || Name == "fmod" || Name == "floor";
354 case 'l':
355 return Name == "log" || Name == "log10";
356 case 'p':
357 return Name == "pow";
358 case 's':
Chris Lattner5cff2672006-06-17 18:17:52 +0000359 return Name == "sin" || Name == "sinh" ||
360 Name == "sqrt" || Name == "sqrtf";
John Criswellbd9d3702005-10-27 16:00:10 +0000361 case 't':
362 return Name == "tan" || Name == "tanh";
363 default:
364 return false;
365 }
366}
367
Chris Lattner72d88ae2007-01-30 23:15:43 +0000368static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
369 const Type *Ty) {
John Criswellbd9d3702005-10-27 16:00:10 +0000370 errno = 0;
371 V = NativeFP(V);
372 if (errno == 0)
373 return ConstantFP::get(Ty, V);
Chris Lattner72d88ae2007-01-30 23:15:43 +0000374 errno = 0;
John Criswellbd9d3702005-10-27 16:00:10 +0000375 return 0;
376}
377
378/// ConstantFoldCall - Attempt to constant fold a call to the specified function
379/// with the specified arguments, returning null if unsuccessful.
380Constant *
Chris Lattner72d88ae2007-01-30 23:15:43 +0000381llvm::ConstantFoldCall(Function *F, Constant** Operands, unsigned NumOperands) {
John Criswellbd9d3702005-10-27 16:00:10 +0000382 const std::string &Name = F->getName();
383 const Type *Ty = F->getReturnType();
384
Chris Lattner72d88ae2007-01-30 23:15:43 +0000385 if (NumOperands == 1) {
John Criswellbd9d3702005-10-27 16:00:10 +0000386 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
387 double V = Op->getValue();
388 switch (Name[0])
389 {
390 case 'a':
391 if (Name == "acos")
392 return ConstantFoldFP(acos, V, Ty);
393 else if (Name == "asin")
394 return ConstantFoldFP(asin, V, Ty);
395 else if (Name == "atan")
396 return ConstantFP::get(Ty, atan(V));
397 break;
398 case 'c':
399 if (Name == "ceil")
400 return ConstantFoldFP(ceil, V, Ty);
401 else if (Name == "cos")
402 return ConstantFP::get(Ty, cos(V));
403 else if (Name == "cosh")
404 return ConstantFP::get(Ty, cosh(V));
405 break;
406 case 'e':
407 if (Name == "exp")
408 return ConstantFP::get(Ty, exp(V));
409 break;
410 case 'f':
411 if (Name == "fabs")
412 return ConstantFP::get(Ty, fabs(V));
413 else if (Name == "floor")
414 return ConstantFoldFP(floor, V, Ty);
415 break;
416 case 'l':
417 if (Name == "log" && V > 0)
418 return ConstantFP::get(Ty, log(V));
419 else if (Name == "log10" && V > 0)
420 return ConstantFoldFP(log10, V, Ty);
Reid Spencer0b118202006-01-16 21:12:35 +0000421 else if (Name == "llvm.sqrt.f32" || Name == "llvm.sqrt.f64") {
John Criswellbd9d3702005-10-27 16:00:10 +0000422 if (V >= -0.0)
423 return ConstantFP::get(Ty, sqrt(V));
424 else // Undefined
425 return ConstantFP::get(Ty, 0.0);
426 }
427 break;
428 case 's':
429 if (Name == "sin")
430 return ConstantFP::get(Ty, sin(V));
431 else if (Name == "sinh")
432 return ConstantFP::get(Ty, sinh(V));
433 else if (Name == "sqrt" && V >= 0)
434 return ConstantFP::get(Ty, sqrt(V));
Chris Lattner5cff2672006-06-17 18:17:52 +0000435 else if (Name == "sqrtf" && V >= 0)
436 return ConstantFP::get(Ty, sqrt((float)V));
John Criswellbd9d3702005-10-27 16:00:10 +0000437 break;
438 case 't':
439 if (Name == "tan")
440 return ConstantFP::get(Ty, tan(V));
441 else if (Name == "tanh")
442 return ConstantFP::get(Ty, tanh(V));
443 break;
444 default:
445 break;
446 }
Reid Spencerb83eb642006-10-20 07:07:24 +0000447 } else if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000448 uint64_t V = Op->getZExtValue();
Nate Begeman6fb3bd62006-01-14 01:25:24 +0000449 if (Name == "llvm.bswap.i16")
Reid Spencerb83eb642006-10-20 07:07:24 +0000450 return ConstantInt::get(Ty, ByteSwap_16(V));
Nate Begeman6fb3bd62006-01-14 01:25:24 +0000451 else if (Name == "llvm.bswap.i32")
Reid Spencerb83eb642006-10-20 07:07:24 +0000452 return ConstantInt::get(Ty, ByteSwap_32(V));
Nate Begeman6fb3bd62006-01-14 01:25:24 +0000453 else if (Name == "llvm.bswap.i64")
Reid Spencerb83eb642006-10-20 07:07:24 +0000454 return ConstantInt::get(Ty, ByteSwap_64(V));
John Criswellbd9d3702005-10-27 16:00:10 +0000455 }
Chris Lattner72d88ae2007-01-30 23:15:43 +0000456 } else if (NumOperands == 2) {
John Criswellbd9d3702005-10-27 16:00:10 +0000457 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
458 double Op1V = Op1->getValue();
459 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
460 double Op2V = Op2->getValue();
461
John Criswellbd9d3702005-10-27 16:00:10 +0000462 if (Name == "pow") {
463 errno = 0;
464 double V = pow(Op1V, Op2V);
465 if (errno == 0)
466 return ConstantFP::get(Ty, V);
467 } else if (Name == "fmod") {
468 errno = 0;
469 double V = fmod(Op1V, Op2V);
470 if (errno == 0)
471 return ConstantFP::get(Ty, V);
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000472 } else if (Name == "atan2") {
John Criswellbd9d3702005-10-27 16:00:10 +0000473 return ConstantFP::get(Ty, atan2(Op1V,Op2V));
Chris Lattnerb5282dc2007-01-15 06:27:37 +0000474 }
475 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
476 if (Name == "llvm.powi.f32") {
477 return ConstantFP::get(Ty, std::pow((float)Op1V,
478 (int)Op2C->getZExtValue()));
479 } else if (Name == "llvm.powi.f64") {
480 return ConstantFP::get(Ty, std::pow((double)Op1V,
481 (int)Op2C->getZExtValue()));
482 }
John Criswellbd9d3702005-10-27 16:00:10 +0000483 }
484 }
485 }
486 return 0;
487}
488