blob: e093631d8f19cfc98e94cb004431672361d4fdbe [file] [log] [blame]
Dan Gohman91d598d2009-09-10 23:07:18 +00001//===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
John Criswell970af112005-10-27 16:00:10 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
John Criswell970af112005-10-27 16:00:10 +00007//
8//===----------------------------------------------------------------------===//
9//
Dan Gohman91d598d2009-09-10 23:07:18 +000010// This file defines routines for folding instructions into constants.
11//
Chandler Carruthef860a22013-01-02 09:10:48 +000012// Also, to supplement the basic IR ConstantExpr simplifications,
Dan Gohman91d598d2009-09-10 23:07:18 +000013// this file defines some additional folding routines that can make use of
Chandler Carruthef860a22013-01-02 09:10:48 +000014// DataLayout information. These functions cannot go in IR due to library
Dan Gohman91d598d2009-09-10 23:07:18 +000015// dependency issues.
John Criswell970af112005-10-27 16:00:10 +000016//
17//===----------------------------------------------------------------------===//
18
19#include "llvm/Analysis/ConstantFolding.h"
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +000020#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000021#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/Analysis/ValueTracking.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000024#include "llvm/IR/Constants.h"
25#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/GlobalVariable.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Operator.h"
Torok Edwin56d06592009-07-11 20:10:48 +000032#include "llvm/Support/ErrorHandling.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000033#include "llvm/Support/FEnv.h"
John Criswell970af112005-10-27 16:00:10 +000034#include "llvm/Support/GetElementPtrTypeIterator.h"
35#include "llvm/Support/MathExtras.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000036#include "llvm/Target/TargetLibraryInfo.h"
John Criswell970af112005-10-27 16:00:10 +000037#include <cerrno>
Jeff Cohencc08c832006-12-02 02:22:01 +000038#include <cmath>
John Criswell970af112005-10-27 16:00:10 +000039using namespace llvm;
40
Chris Lattner44d68b92007-01-31 00:51:48 +000041//===----------------------------------------------------------------------===//
42// Constant Folding internal helper functions
43//===----------------------------------------------------------------------===//
44
NAKAMURA Takumidce89992012-11-05 00:11:11 +000045/// FoldBitCast - Constant fold bitcast, symbolically evaluating it with
Micah Villmowcdfe20b2012-10-08 16:38:25 +000046/// DataLayout. This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000047/// ConstantExpr if unfoldable.
Chris Lattner229907c2011-07-18 04:54:35 +000048static Constant *FoldBitCast(Constant *C, Type *DestTy,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000049 const DataLayout &TD) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000050 // Catch the obvious splat cases.
51 if (C->isNullValue() && !DestTy->isX86_MMXTy())
52 return Constant::getNullValue(DestTy);
53 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy())
54 return Constant::getAllOnesValue(DestTy);
55
Rafael Espindolabb893fe2012-01-27 23:33:07 +000056 // Handle a vector->integer cast.
57 if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
Michael Ilsemana7b93c12013-02-26 22:51:07 +000058 VectorType *VTy = dyn_cast<VectorType>(C->getType());
59 if (VTy == 0)
Rafael Espindolabb893fe2012-01-27 23:33:07 +000060 return ConstantExpr::getBitCast(C, DestTy);
61
Michael Ilsemana7b93c12013-02-26 22:51:07 +000062 unsigned NumSrcElts = VTy->getNumElements();
63 Type *SrcEltTy = VTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +000064
Rafael Espindolabb893fe2012-01-27 23:33:07 +000065 // If the vector is a vector of floating point, convert it to vector of int
66 // to simplify things.
Chris Lattner8213c8a2012-02-06 21:56:39 +000067 if (SrcEltTy->isFloatingPointTy()) {
68 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Rafael Espindolabb893fe2012-01-27 23:33:07 +000069 Type *SrcIVTy =
70 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
Chandler Carruthef860a22013-01-02 09:10:48 +000071 // Ask IR to do the conversion now that #elts line up.
Rafael Espindolabb893fe2012-01-27 23:33:07 +000072 C = ConstantExpr::getBitCast(C, SrcIVTy);
73 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000074
Michael Ilsemana7b93c12013-02-26 22:51:07 +000075 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
76 if (CDV == 0)
77 return ConstantExpr::getBitCast(C, DestTy);
78
Rafael Espindolabb893fe2012-01-27 23:33:07 +000079 // Now that we know that the input value is a vector of integers, just shift
80 // and insert them into our result.
Chris Lattner8213c8a2012-02-06 21:56:39 +000081 unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000082 APInt Result(IT->getBitWidth(), 0);
83 for (unsigned i = 0; i != NumSrcElts; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +000084 Result <<= BitShift;
85 if (TD.isLittleEndian())
86 Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
87 else
88 Result |= CDV->getElementAsInteger(i);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000089 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000090
Rafael Espindolabb893fe2012-01-27 23:33:07 +000091 return ConstantInt::get(IT, Result);
92 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000093
Nadav Rotemad4a70a2011-08-20 14:02:29 +000094 // The code below only handles casts to vectors currently.
Chris Lattner229907c2011-07-18 04:54:35 +000095 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +000096 if (DestVTy == 0)
97 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +000098
Chris Lattnerd8e8fb42009-10-25 06:15:37 +000099 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
100 // vector so the code below can handle it uniformly.
101 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
102 Constant *Ops = C; // don't take the address of C!
Chris Lattner69229312011-02-15 00:14:00 +0000103 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000104 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000105
Chris Lattner9d051242009-10-25 06:08:26 +0000106 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000107 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000108 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000109
Chandler Carruthef860a22013-01-02 09:10:48 +0000110 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000111 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000112 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000113 if (NumDstElt == NumSrcElt)
114 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000115
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000116 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000117 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000118
119 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000120 // requires endianness information to do the right thing. For example,
121 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
122 // folds to (little endian):
123 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
124 // and to (big endian):
125 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000126
Chris Lattner9d051242009-10-25 06:08:26 +0000127 // First thing is first. We only want to think about integer here, so if
128 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000129 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000130 // Fold to an vector of integers with same size as our FP type.
131 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000132 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000133 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
134 // Recursively handle this integer conversion, if possible.
135 C = FoldBitCast(C, DestIVTy, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000136
Chandler Carruthef860a22013-01-02 09:10:48 +0000137 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000138 return ConstantExpr::getBitCast(C, DestTy);
139 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000140
Chris Lattner9d051242009-10-25 06:08:26 +0000141 // Okay, we know the destination is integer, if the input is FP, convert
142 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000143 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000144 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000145 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000146 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000147 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000148 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000149 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000150 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
151 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000152 return C;
153 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000154
Chris Lattner9d051242009-10-25 06:08:26 +0000155 // Now we know that the input and output vectors are both integer vectors
156 // of the same size, and that their #elements is not the same. Do the
157 // conversion here, which depends on whether the input or output has
158 // more elements.
159 bool isLittleEndian = TD.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000160
Chris Lattner9d051242009-10-25 06:08:26 +0000161 SmallVector<Constant*, 32> Result;
162 if (NumDstElt < NumSrcElt) {
163 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
164 Constant *Zero = Constant::getNullValue(DstEltTy);
165 unsigned Ratio = NumSrcElt/NumDstElt;
166 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
167 unsigned SrcElt = 0;
168 for (unsigned i = 0; i != NumDstElt; ++i) {
169 // Build each element of the result.
170 Constant *Elt = Zero;
171 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
172 for (unsigned j = 0; j != Ratio; ++j) {
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000173 Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
Chris Lattner9d051242009-10-25 06:08:26 +0000174 if (!Src) // Reject constantexpr elements.
175 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000176
Chris Lattner9d051242009-10-25 06:08:26 +0000177 // Zero extend the element to the right size.
178 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000179
Chris Lattner9d051242009-10-25 06:08:26 +0000180 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000181 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000182 ConstantInt::get(Src->getType(), ShiftAmt));
183 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000184
Chris Lattner9d051242009-10-25 06:08:26 +0000185 // Mix it in.
186 Elt = ConstantExpr::getOr(Elt, Src);
187 }
188 Result.push_back(Elt);
189 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000190 return ConstantVector::get(Result);
191 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000192
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000193 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
194 unsigned Ratio = NumDstElt/NumSrcElt;
195 unsigned DstBitSize = DstEltTy->getPrimitiveSizeInBits();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000196
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000197 // Loop over each source value, expanding into multiple results.
198 for (unsigned i = 0; i != NumSrcElt; ++i) {
199 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
200 if (!Src) // Reject constantexpr elements.
201 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000202
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000203 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
204 for (unsigned j = 0; j != Ratio; ++j) {
205 // Shift the piece of the value into the right place, depending on
206 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000207 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000208 ConstantInt::get(Src->getType(), ShiftAmt));
209 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000210
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000211 // Truncate and remember this piece.
212 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000213 }
214 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000215
Chris Lattner69229312011-02-15 00:14:00 +0000216 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000217}
218
219
Chris Lattner44d68b92007-01-31 00:51:48 +0000220/// IsConstantOffsetFromGlobal - If this constant is actually a constant offset
221/// from a global, return the global and the constant. Because of
222/// constantexprs, this function is recursive.
223static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
Benjamin Kramer546bb562013-01-23 21:21:24 +0000224 APInt &Offset, const DataLayout &TD) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000225 // Trivial case, constant is the global.
226 if ((GV = dyn_cast<GlobalValue>(C))) {
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000227 unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
228 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000229 return true;
230 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000231
Chris Lattner44d68b92007-01-31 00:51:48 +0000232 // Otherwise, if this isn't a constant expr, bail out.
233 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
234 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000235
Chris Lattner44d68b92007-01-31 00:51:48 +0000236 // Look through ptr->int and ptr->ptr casts.
237 if (CE->getOpcode() == Instruction::PtrToInt ||
238 CE->getOpcode() == Instruction::BitCast)
239 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000240
241 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000242 GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
243 if (!GEP)
244 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000245
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000246 unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
247 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000248
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000249 // If the base isn't a global+constant, we aren't either.
250 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
251 return false;
252
253 // Otherwise, add any offset that our operands provide.
254 if (!GEP->accumulateConstantOffset(TD, TmpOffset))
255 return false;
256
257 Offset = TmpOffset;
258 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000259}
260
Chris Lattnered00b802009-10-23 06:23:49 +0000261/// ReadDataFromGlobal - Recursive helper to read bits out of global. C is the
262/// constant being copied out of. ByteOffset is an offset into C. CurPtr is the
263/// pointer to copy results into and BytesLeft is the number of bytes left in
264/// the CurPtr buffer. TD is the target data.
265static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
266 unsigned char *CurPtr, unsigned BytesLeft,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000267 const DataLayout &TD) {
Chris Lattnered00b802009-10-23 06:23:49 +0000268 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
269 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000270
Chris Lattner3db7bd22009-10-24 05:27:19 +0000271 // If this element is zero or undefined, we can just return since *CurPtr is
272 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000273 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
274 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000275
Chris Lattnered00b802009-10-23 06:23:49 +0000276 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
277 if (CI->getBitWidth() > 64 ||
278 (CI->getBitWidth() & 7) != 0)
279 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000280
Chris Lattnered00b802009-10-23 06:23:49 +0000281 uint64_t Val = CI->getZExtValue();
282 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000283
Chris Lattnered00b802009-10-23 06:23:49 +0000284 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000285 int n = ByteOffset;
286 if (!TD.isLittleEndian())
287 n = IntBytes - n - 1;
288 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000289 ++ByteOffset;
290 }
291 return true;
292 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000293
Chris Lattnered00b802009-10-23 06:23:49 +0000294 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
295 if (CFP->getType()->isDoubleTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000296 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000297 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
298 }
299 if (CFP->getType()->isFloatTy()){
Chris Lattner9d051242009-10-25 06:08:26 +0000300 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000301 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
302 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000303 if (CFP->getType()->isHalfTy()){
304 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
305 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
306 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000307 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000308 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000309
Chris Lattnered00b802009-10-23 06:23:49 +0000310 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
311 const StructLayout *SL = TD.getStructLayout(CS->getType());
312 unsigned Index = SL->getElementContainingOffset(ByteOffset);
313 uint64_t CurEltOffset = SL->getElementOffset(Index);
314 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000315
Chris Lattnered00b802009-10-23 06:23:49 +0000316 while (1) {
317 // If the element access is to the element itself and not to tail padding,
318 // read the bytes from the element.
319 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
320
321 if (ByteOffset < EltSize &&
322 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
323 BytesLeft, TD))
324 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000325
Chris Lattnered00b802009-10-23 06:23:49 +0000326 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000327
Chris Lattnered00b802009-10-23 06:23:49 +0000328 // Check to see if we read from the last struct element, if so we're done.
329 if (Index == CS->getType()->getNumElements())
330 return true;
331
332 // If we read all of the bytes we needed from this element we're done.
333 uint64_t NextEltOffset = SL->getElementOffset(Index);
334
Matt Arsenault8c789092013-08-12 23:15:58 +0000335 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000336 return true;
337
338 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000339 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
340 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000341 ByteOffset = 0;
342 CurEltOffset = NextEltOffset;
343 }
344 // not reached.
345 }
346
Chris Lattner67058832012-01-25 06:48:06 +0000347 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
348 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000349 Type *EltTy = C->getType()->getSequentialElementType();
Chris Lattner67058832012-01-25 06:48:06 +0000350 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000351 uint64_t Index = ByteOffset / EltSize;
352 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000353 uint64_t NumElts;
354 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
355 NumElts = AT->getNumElements();
356 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000357 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000358
Chris Lattner67058832012-01-25 06:48:06 +0000359 for (; Index != NumElts; ++Index) {
360 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
361 BytesLeft, TD))
362 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000363
364 uint64_t BytesWritten = EltSize - Offset;
365 assert(BytesWritten <= EltSize && "Not indexing into this element?");
366 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000367 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000368
Chris Lattner67058832012-01-25 06:48:06 +0000369 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000370 BytesLeft -= BytesWritten;
371 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000372 }
373 return true;
374 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000375
Anders Carlssond21b06a2011-02-06 20:11:56 +0000376 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000377 if (CE->getOpcode() == Instruction::IntToPtr &&
Matt Arsenault7a960a82013-08-20 21:20:04 +0000378 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000379 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Chris Lattner67058832012-01-25 06:48:06 +0000380 BytesLeft, TD);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000381 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000382 }
383
Chris Lattnered00b802009-10-23 06:23:49 +0000384 // Otherwise, unknown initializer type.
385 return false;
386}
387
388static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000389 const DataLayout &TD) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000390 PointerType *PTy = cast<PointerType>(C->getType());
391 Type *LoadTy = PTy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000392 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000393
Chris Lattnered00b802009-10-23 06:23:49 +0000394 // If this isn't an integer load we can't fold it directly.
395 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000396 unsigned AS = PTy->getAddressSpace();
397
Chris Lattnered00b802009-10-23 06:23:49 +0000398 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000399 // and then bitcast the result. This can be useful for union cases. Note
400 // that address spaces don't matter here since we're not going to result in
401 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000402 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000403 if (LoadTy->isHalfTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000404 MapTy = Type::getInt16PtrTy(C->getContext(), AS);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000405 else if (LoadTy->isFloatTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000406 MapTy = Type::getInt32PtrTy(C->getContext(), AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000407 else if (LoadTy->isDoubleTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000408 MapTy = Type::getInt64PtrTy(C->getContext(), AS);
Duncan Sands19d0b472010-02-16 11:11:14 +0000409 else if (LoadTy->isVectorTy()) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000410 MapTy = PointerType::getIntNPtrTy(C->getContext(),
411 TD.getTypeAllocSizeInBits(LoadTy),
412 AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000413 } else
Chris Lattnered00b802009-10-23 06:23:49 +0000414 return 0;
415
Chris Lattner9d051242009-10-25 06:08:26 +0000416 C = FoldBitCast(C, MapTy, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000417 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
Chris Lattner9d051242009-10-25 06:08:26 +0000418 return FoldBitCast(Res, LoadTy, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000419 return 0;
420 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000421
Chris Lattnered00b802009-10-23 06:23:49 +0000422 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000423 if (BytesLoaded > 32 || BytesLoaded == 0)
424 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000425
Chris Lattnered00b802009-10-23 06:23:49 +0000426 GlobalValue *GVal;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000427 APInt Offset;
Chris Lattnered00b802009-10-23 06:23:49 +0000428 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
429 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000430
Chris Lattnered00b802009-10-23 06:23:49 +0000431 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000432 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000433 !GV->getInitializer()->getType()->isSized())
434 return 0;
435
436 // If we're loading off the beginning of the global, some bytes may be valid,
437 // but we don't try to handle this.
Matt Arsenault8c789092013-08-12 23:15:58 +0000438 if (Offset.isNegative())
439 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000440
Chris Lattnered00b802009-10-23 06:23:49 +0000441 // If we're not accessing anything in this constant, the result is undefined.
Benjamin Kramer546bb562013-01-23 21:21:24 +0000442 if (Offset.getZExtValue() >=
443 TD.getTypeAllocSize(GV->getInitializer()->getType()))
Chris Lattnered00b802009-10-23 06:23:49 +0000444 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000445
Chris Lattner59f94c02009-10-23 06:50:36 +0000446 unsigned char RawBytes[32] = {0};
Benjamin Kramer546bb562013-01-23 21:21:24 +0000447 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
Chris Lattnered00b802009-10-23 06:23:49 +0000448 BytesLoaded, TD))
449 return 0;
450
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000451 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
452 if (TD.isLittleEndian()) {
453 ResultVal = RawBytes[BytesLoaded - 1];
454 for (unsigned i = 1; i != BytesLoaded; ++i) {
455 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000456 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000457 }
458 } else {
459 ResultVal = RawBytes[0];
460 for (unsigned i = 1; i != BytesLoaded; ++i) {
461 ResultVal <<= 8;
462 ResultVal |= RawBytes[i];
463 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000464 }
Chris Lattnered00b802009-10-23 06:23:49 +0000465
Chris Lattner59f94c02009-10-23 06:50:36 +0000466 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000467}
468
Chris Lattner1664a4f2009-10-22 06:25:11 +0000469/// ConstantFoldLoadFromConstPtr - Return the value that a load from C would
470/// produce if it is constant and determinable. If this is not determinable,
471/// return null.
472Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000473 const DataLayout *TD) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000474 // First, try the easy cases:
475 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
476 if (GV->isConstant() && GV->hasDefinitiveInitializer())
477 return GV->getInitializer();
478
Chris Lattnercf7e8942009-10-22 06:44:07 +0000479 // If the loaded value isn't a constant expr, we can't handle it.
480 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000481 if (!CE)
482 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000483
Chris Lattnercf7e8942009-10-22 06:44:07 +0000484 if (CE->getOpcode() == Instruction::GetElementPtr) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000485 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
486 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000487 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000488 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
489 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000490 }
491 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000492 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000493
Chris Lattnercf7e8942009-10-22 06:44:07 +0000494 // Instead of loading constant c string, use corresponding integer value
495 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000496 StringRef Str;
497 if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
498 unsigned StrLen = Str.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000499 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
Chris Lattnered00b802009-10-23 06:23:49 +0000500 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000501 // Replace load with immediate integer if the result is an integer or fp
502 // value.
503 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000504 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000505 APInt StrVal(NumBits, 0);
506 APInt SingleChar(NumBits, 0);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000507 if (TD->isLittleEndian()) {
Chris Lattnered00b802009-10-23 06:23:49 +0000508 for (signed i = StrLen-1; i >= 0; i--) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000509 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner51d2f702009-10-22 06:38:35 +0000510 StrVal = (StrVal << 8) | SingleChar;
511 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000512 } else {
Chris Lattnered00b802009-10-23 06:23:49 +0000513 for (unsigned i = 0; i < StrLen; i++) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000514 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
515 StrVal = (StrVal << 8) | SingleChar;
516 }
517 // Append NULL at the end.
518 SingleChar = 0;
519 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000520 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000521
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000522 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
523 if (Ty->isFloatingPointTy())
524 Res = ConstantExpr::getBitCast(Res, Ty);
525 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000526 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000527 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000528
Chris Lattnercf7e8942009-10-22 06:44:07 +0000529 // If this load comes from anywhere in a constant global, and if the global
530 // is all undef or zero, we know what it loads.
Dan Gohman0f124e12011-01-24 18:53:32 +0000531 if (GlobalVariable *GV =
532 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000533 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000534 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
Chris Lattnercf7e8942009-10-22 06:44:07 +0000535 if (GV->getInitializer()->isNullValue())
536 return Constant::getNullValue(ResTy);
537 if (isa<UndefValue>(GV->getInitializer()))
538 return UndefValue::get(ResTy);
539 }
540 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000541
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000542 // Try hard to fold loads from bitcasted strange and non-type-safe things.
543 if (TD)
Chris Lattnered00b802009-10-23 06:23:49 +0000544 return FoldReinterpretLoadFromConstPtr(CE, *TD);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000545 return 0;
546}
547
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000548static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
Chris Lattner1664a4f2009-10-22 06:25:11 +0000549 if (LI->isVolatile()) return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000550
Chris Lattner1664a4f2009-10-22 06:25:11 +0000551 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
552 return ConstantFoldLoadFromConstPtr(C, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000553
Chris Lattner1664a4f2009-10-22 06:25:11 +0000554 return 0;
555}
Chris Lattner44d68b92007-01-31 00:51:48 +0000556
557/// SymbolicallyEvaluateBinop - One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000558/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000559/// these together. If target data info is available, it is provided as DL,
560/// otherwise DL is null.
Chris Lattner44d68b92007-01-31 00:51:48 +0000561static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Nick Lewycky06417742013-02-14 03:23:37 +0000562 Constant *Op1, const DataLayout *DL){
Chris Lattner44d68b92007-01-31 00:51:48 +0000563 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000564
Chris Lattner44d68b92007-01-31 00:51:48 +0000565 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
566 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
567 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000568
569
Nick Lewycky06417742013-02-14 03:23:37 +0000570 if (Opc == Instruction::And && DL) {
Benjamin Kramerec1bb4f2013-04-19 16:56:24 +0000571 unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000572 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
573 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
574 ComputeMaskedBits(Op0, KnownZero0, KnownOne0, DL);
575 ComputeMaskedBits(Op1, KnownZero1, KnownOne1, DL);
576 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
577 // All the bits of Op0 that the 'and' could be masking are already zero.
578 return Op0;
579 }
580 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
581 // All the bits of Op1 that the 'and' could be masking are already zero.
582 return Op1;
583 }
584
585 APInt KnownZero = KnownZero0 | KnownZero1;
586 APInt KnownOne = KnownOne0 & KnownOne1;
587 if ((KnownZero | KnownOne).isAllOnesValue()) {
588 return ConstantInt::get(Op0->getType(), KnownOne);
589 }
590 }
591
Chris Lattner44d68b92007-01-31 00:51:48 +0000592 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
593 // constant. This happens frequently when iterating over a global array.
Nick Lewycky06417742013-02-14 03:23:37 +0000594 if (Opc == Instruction::Sub && DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000595 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000596 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000597
Nick Lewycky06417742013-02-14 03:23:37 +0000598 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
599 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
Chris Lattner44d68b92007-01-31 00:51:48 +0000600 GV1 == GV2) {
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000601 unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
602
Chris Lattner44d68b92007-01-31 00:51:48 +0000603 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000604 // PtrToInt may change the bitwidth so we have convert to the right size
605 // first.
606 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
607 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000608 }
609 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000610
Chris Lattner44d68b92007-01-31 00:51:48 +0000611 return 0;
612}
613
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000614/// CastGEPIndices - If array indices are not pointer-sized integers,
615/// explicitly cast them so that they aren't implicitly casted by the
616/// getelementptr.
Jay Foadf4b14a22011-07-19 13:32:40 +0000617static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000618 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000619 const TargetLibraryInfo *TLI) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000620 if (!TD)
621 return 0;
622
623 Type *IntPtrTy = TD->getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000624
625 bool Any = false;
626 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000627 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000628 if ((i == 1 ||
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000629 !isa<StructType>(GetElementPtrInst::getIndexedType(
630 Ops[0]->getType(),
631 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000632 Ops[i]->getType() != IntPtrTy) {
633 Any = true;
634 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
635 true,
636 IntPtrTy,
637 true),
638 Ops[i], IntPtrTy));
639 } else
640 NewIdxs.push_back(Ops[i]);
641 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000642
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000643 if (!Any)
644 return 0;
645
646 Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
647 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chad Rosierc24b86f2011-12-01 03:08:23 +0000648 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000649 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000650 }
651
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000652 return C;
653}
654
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000655/// Strip the pointer casts, but preserve the address space information.
656static Constant* StripPtrCastKeepAS(Constant* Ptr) {
657 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
658 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
659 Ptr = cast<Constant>(Ptr->stripPointerCasts());
660 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
661
662 // Preserve the address space number of the pointer.
663 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
664 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
665 OldPtrTy->getAddressSpace());
666 Ptr = ConstantExpr::getBitCast(Ptr, NewPtrTy);
667 }
668 return Ptr;
669}
670
Chris Lattner44d68b92007-01-31 00:51:48 +0000671/// SymbolicallyEvaluateGEP - If we can symbolically evaluate the specified GEP
672/// constant expression, do so.
Jay Foadf4b14a22011-07-19 13:32:40 +0000673static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000674 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000675 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000676 Constant *Ptr = Ops[0];
Matt Arsenault8c789092013-08-12 23:15:58 +0000677 if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
Nadav Rotem3924cb02011-12-05 06:29:09 +0000678 !Ptr->getType()->isPointerTy())
Chris Lattner44d68b92007-01-31 00:51:48 +0000679 return 0;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000680
Matt Arsenault7a960a82013-08-20 21:20:04 +0000681 Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
Matt Arsenault8c789092013-08-12 23:15:58 +0000682 Type *ResultElementTy = ResultTy->getPointerElementType();
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000683
684 // If this is a constant expr gep that is effectively computing an
685 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000686 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000687 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000688
Chris Lattner5858e092011-01-06 06:19:46 +0000689 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
690 // "inttoptr (sub (ptrtoint Ptr), V)"
Matt Arsenault8c789092013-08-12 23:15:58 +0000691 if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
Chris Lattner5858e092011-01-06 06:19:46 +0000692 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
Chris Lattner08f43452011-01-16 03:43:53 +0000693 assert((CE == 0 || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000694 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000695 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000696 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000697 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
698 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
699 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
700 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
Chad Rosierc24b86f2011-12-01 03:08:23 +0000701 Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
Chris Lattner5858e092011-01-06 06:19:46 +0000702 return Res;
703 }
704 }
Dan Gohman81ce8422009-08-19 18:18:36 +0000705 return 0;
Chris Lattner5858e092011-01-06 06:19:46 +0000706 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000707
Chris Lattner171608e2011-01-06 22:24:29 +0000708 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000709 APInt Offset =
710 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
Roman Divacky4717a8d2012-09-06 15:42:13 +0000711 makeArrayRef((Value *const*)
712 Ops.data() + 1,
Jay Foadbf904772011-07-19 14:01:37 +0000713 Ops.size() - 1)));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000714 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000715
716 // If this is a GEP of a GEP, fold it all into a single GEP.
717 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000718 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000719
720 // Do not try the incorporate the sub-GEP if some index is not a number.
721 bool AllConstantInt = true;
722 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
723 if (!isa<ConstantInt>(NestedOps[i])) {
724 AllConstantInt = false;
725 break;
726 }
727 if (!AllConstantInt)
728 break;
729
Dan Gohman474e488c2010-03-10 19:31:51 +0000730 Ptr = cast<Constant>(GEP->getOperand(0));
731 Offset += APInt(BitWidth,
Jay Foadbf904772011-07-19 14:01:37 +0000732 TD->getIndexedOffset(Ptr->getType(), NestedOps));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000733 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000734 }
735
Dan Gohman81ce8422009-08-19 18:18:36 +0000736 // If the base value for this address is a literal integer value, fold the
737 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000738 APInt BasePtr(BitWidth, 0);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000739 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
740 if (CE->getOpcode() == Instruction::IntToPtr) {
Jay Foad583abbc2010-12-07 08:25:19 +0000741 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
742 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000743 }
744 }
745
Dan Gohmana5ca5782010-03-18 19:34:33 +0000746 if (Ptr->isNullValue() || BasePtr != 0) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000747 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Dan Gohman81ce8422009-08-19 18:18:36 +0000748 return ConstantExpr::getIntToPtr(C, ResultTy);
749 }
750
751 // Otherwise form a regular getelementptr. Recompute the indices so that
752 // we eliminate over-indexing of the notional static type array bounds.
753 // This makes it easy to determine if the getelementptr is "inbounds".
754 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Chris Lattner229907c2011-07-18 04:54:35 +0000755 Type *Ty = Ptr->getType();
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000756 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
Matt Arsenault7a960a82013-08-20 21:20:04 +0000757 SmallVector<Constant *, 32> NewIdxs;
758
Dan Gohmanc59ba422009-08-19 22:46:59 +0000759 do {
Chris Lattner229907c2011-07-18 04:54:35 +0000760 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000761 if (ATy->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000762 // The only pointer indexing we'll do is on the first index of the GEP.
763 if (!NewIdxs.empty())
764 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000765
Chris Lattner77c36d62009-12-03 01:05:45 +0000766 // Only handle pointers to sized types, not pointers to functions.
767 if (!ATy->getElementType()->isSized())
768 return 0;
769 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000770
Dan Gohman81ce8422009-08-19 18:18:36 +0000771 // Determine which element of the array the offset points into.
Dan Gohman23e62c52009-08-21 16:52:54 +0000772 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohman81ce8422009-08-19 18:18:36 +0000773 if (ElemSize == 0)
Chris Lattner6ce03802010-11-21 08:39:01 +0000774 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000775 // index for this level and proceed to the next level to see if it can
776 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000777 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
778 else {
779 // The element size is non-zero divide the offset by the element
780 // size (rounding down), to compute the index at this level.
781 APInt NewIdx = Offset.udiv(ElemSize);
782 Offset -= NewIdx * ElemSize;
783 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
784 }
Dan Gohman81ce8422009-08-19 18:18:36 +0000785 Ty = ATy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000786 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000787 // If we end up with an offset that isn't valid for this struct type, we
788 // can't re-form this GEP in a regular form, so bail out. The pointer
789 // operand likely went through casts that are necessary to make the GEP
790 // sensible.
Dan Gohman81ce8422009-08-19 18:18:36 +0000791 const StructLayout &SL = *TD->getStructLayout(STy);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000792 if (Offset.uge(SL.getSizeInBytes()))
793 break;
794
795 // Determine which field of the struct the offset points into. The
796 // getZExtValue is fine as we've already ensured that the offset is
797 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000798 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000799 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
800 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000801 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000802 Ty = STy->getTypeAtIndex(ElIdx);
803 } else {
Dan Gohmanc59ba422009-08-19 22:46:59 +0000804 // We've reached some non-indexable type.
805 break;
Dan Gohman81ce8422009-08-19 18:18:36 +0000806 }
Matt Arsenault8c789092013-08-12 23:15:58 +0000807 } while (Ty != ResultElementTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000808
809 // If we haven't used up the entire offset by descending the static
810 // type, then the offset is pointing into the middle of an indivisible
811 // member, so we can't simplify it.
812 if (Offset != 0)
813 return 0;
Dan Gohman81ce8422009-08-19 18:18:36 +0000814
Dan Gohman21c62162009-09-11 00:04:14 +0000815 // Create a GEP.
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000816 Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000817 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000818 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000819
Dan Gohmanc59ba422009-08-19 22:46:59 +0000820 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000821 // the type of what the original indices indexed, add a cast.
Matt Arsenault8c789092013-08-12 23:15:58 +0000822 if (Ty != ResultElementTy)
Chris Lattner9d051242009-10-25 06:08:26 +0000823 C = FoldBitCast(C, ResultTy, *TD);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000824
825 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000826}
827
Chris Lattner6a6b3fb2007-12-11 07:29:44 +0000828
Chris Lattner44d68b92007-01-31 00:51:48 +0000829
830//===----------------------------------------------------------------------===//
831// Constant Folding public APIs
832//===----------------------------------------------------------------------===//
833
Duncan Sands763dec02010-11-23 10:16:18 +0000834/// ConstantFoldInstruction - Try to constant fold the specified instruction.
835/// If successful, the constant result is returned, if not, null is returned.
836/// Note that this fails if not all of the operands are constant. Otherwise,
837/// this function can only fail when attempting to fold instructions like loads
838/// and stores, which have no constant expression form.
Chad Rosierc24b86f2011-12-01 03:08:23 +0000839Constant *llvm::ConstantFoldInstruction(Instruction *I,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000840 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000841 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +0000842 // Handle PHI nodes quickly here...
Chris Lattner2ae054a2007-01-30 23:45:45 +0000843 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Duncan Sands1d27f0122010-11-14 12:53:18 +0000844 Constant *CommonValue = 0;
John Criswell970af112005-10-27 16:00:10 +0000845
Duncan Sands1d27f0122010-11-14 12:53:18 +0000846 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
847 Value *Incoming = PN->getIncomingValue(i);
Duncan Sands763dec02010-11-23 10:16:18 +0000848 // If the incoming value is undef then skip it. Note that while we could
849 // skip the value if it is equal to the phi node itself we choose not to
850 // because that would break the rule that constant folding only applies if
851 // all operands are constants.
852 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +0000853 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000854 // If the incoming value is not a constant, then give up.
Duncan Sands1d27f0122010-11-14 12:53:18 +0000855 Constant *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000856 if (!C)
857 return 0;
858 // Fold the PHI's operands.
859 if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
860 C = ConstantFoldConstantExpression(NewC, TD, TLI);
861 // If the incoming value is a different constant to
862 // the one we saw previously, then give up.
863 if (CommonValue && C != CommonValue)
Duncan Sands1d27f0122010-11-14 12:53:18 +0000864 return 0;
865 CommonValue = C;
866 }
Chris Lattner2ae054a2007-01-30 23:45:45 +0000867
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000868
Duncan Sands1d27f0122010-11-14 12:53:18 +0000869 // If we reach here, all incoming values are the same constant or undef.
870 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +0000871 }
872
873 // Scan the operand list, checking to see if they are all constants, if so,
874 // hand off to ConstantFoldInstOperands.
875 SmallVector<Constant*, 8> Ops;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000876 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
877 Constant *Op = dyn_cast<Constant>(*i);
878 if (!Op)
Chris Lattner2ae054a2007-01-30 23:45:45 +0000879 return 0; // All operands not constant!
880
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000881 // Fold the Instruction's operands.
882 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
883 Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
884
885 Ops.push_back(Op);
886 }
887
Chris Lattnerd2265b42007-12-10 22:53:04 +0000888 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000889 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000890 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000891
Chris Lattner1664a4f2009-10-22 06:25:11 +0000892 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
893 return ConstantFoldLoadInst(LI, TD);
Frits van Bommela98214d2010-11-29 20:36:52 +0000894
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000895 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000896 return ConstantExpr::getInsertValue(
897 cast<Constant>(IVI->getAggregateOperand()),
898 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000899 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000900 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000901
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000902 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000903 return ConstantExpr::getExtractValue(
904 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000905 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000906 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000907
Chad Rosierc24b86f2011-12-01 03:08:23 +0000908 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +0000909}
910
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000911static Constant *
912ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
913 const TargetLibraryInfo *TLI,
914 SmallPtrSet<ConstantExpr *, 4> &FoldedOps) {
915 SmallVector<Constant *, 8> Ops;
916 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
917 ++i) {
Dan Gohman580b80d2009-11-23 16:22:21 +0000918 Constant *NewC = cast<Constant>(*i);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000919 // Recursively fold the ConstantExpr's operands. If we have already folded
920 // a ConstantExpr, we don't have to process it again.
921 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
922 if (FoldedOps.insert(NewCE))
923 NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
924 }
Dan Gohman580b80d2009-11-23 16:22:21 +0000925 Ops.push_back(NewC);
926 }
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000927
928 if (CE->isCompare())
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000929 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000930 TD, TLI);
931 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000932}
933
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000934/// ConstantFoldConstantExpression - Attempt to fold the constant expression
935/// using the specified DataLayout. If successful, the constant result is
936/// result is returned, if not, null is returned.
937Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
938 const DataLayout *TD,
939 const TargetLibraryInfo *TLI) {
940 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
941 return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
942}
943
Chris Lattner2ae054a2007-01-30 23:45:45 +0000944/// ConstantFoldInstOperands - Attempt to constant fold an instruction with the
945/// specified opcode and operands. If successful, the constant result is
946/// returned, if not, null is returned. Note that this function can fail when
947/// attempting to fold instructions like loads and stores, which have no
948/// constant expression form.
949///
Dan Gohman580b80d2009-11-23 16:22:21 +0000950/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
951/// information, due to only being passed an opcode and operands. Constant
952/// folding using this function strips this information.
953///
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000954Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
Jay Foadf4b14a22011-07-19 13:32:40 +0000955 ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000956 const DataLayout *TD,
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000957 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000958 // Handle easy binops first.
Chris Lattnerd2265b42007-12-10 22:53:04 +0000959 if (Instruction::isBinaryOp(Opcode)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000960 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
Chris Lattner46b5c642009-11-06 04:27:31 +0000961 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
Chris Lattner44d68b92007-01-31 00:51:48 +0000962 return C;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000963 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000964
Owen Anderson487375e2009-07-29 18:55:55 +0000965 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner44d68b92007-01-31 00:51:48 +0000966 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000967
Chris Lattnerd2265b42007-12-10 22:53:04 +0000968 switch (Opcode) {
Chris Lattner2ae054a2007-01-30 23:45:45 +0000969 default: return 0;
Chris Lattner8fb74c62010-01-02 01:22:23 +0000970 case Instruction::ICmp:
Craig Toppera2886c22012-02-07 05:05:23 +0000971 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
Chris Lattner2ae054a2007-01-30 23:45:45 +0000972 case Instruction::Call:
Jay Foadf4b14a22011-07-19 13:32:40 +0000973 if (Function *F = dyn_cast<Function>(Ops.back()))
Chris Lattner2ae054a2007-01-30 23:45:45 +0000974 if (canConstantFoldCallTo(F))
Chad Rosierc24b86f2011-12-01 03:08:23 +0000975 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +0000976 return 0;
Chris Lattner460e34a2007-08-11 23:49:01 +0000977 case Instruction::PtrToInt:
978 // If the input is a inttoptr, eliminate the pair. This requires knowing
979 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
980 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
981 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
982 Constant *Input = CE->getOperand(0);
Dan Gohman7ccc52f2009-06-15 22:12:54 +0000983 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Matt Arsenaultd12e8022013-09-17 23:23:16 +0000984 unsigned PtrWidth = TD->getPointerTypeSizeInBits(CE->getType());
985 if (PtrWidth < InWidth) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000986 Constant *Mask =
Matt Arsenaultd12e8022013-09-17 23:23:16 +0000987 ConstantInt::get(CE->getContext(),
988 APInt::getLowBitsSet(InWidth, PtrWidth));
Owen Anderson487375e2009-07-29 18:55:55 +0000989 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky730d5da2008-10-24 06:14:27 +0000990 }
Chris Lattner460e34a2007-08-11 23:49:01 +0000991 // Do a zext or trunc to get to the dest size.
Owen Anderson487375e2009-07-29 18:55:55 +0000992 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner460e34a2007-08-11 23:49:01 +0000993 }
994 }
Owen Anderson487375e2009-07-29 18:55:55 +0000995 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner460e34a2007-08-11 23:49:01 +0000996 case Instruction::IntToPtr:
Duncan Sandsea68a6c2008-08-13 20:20:35 +0000997 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
998 // the int size is >= the ptr size. This requires knowing the width of a
999 // pointer, so it can't be done in ConstantExpr::getCast.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001000 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1001 if (TD && CE->getOpcode() == Instruction::PtrToInt) {
1002 Constant *SrcPtr = CE->getOperand(0);
1003 unsigned SrcPtrSize = TD->getPointerTypeSizeInBits(SrcPtr->getType());
1004 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1005
1006 if (MidIntSize >= SrcPtrSize) {
1007 unsigned DestPtrSize = TD->getPointerTypeSizeInBits(DestTy);
1008 if (SrcPtrSize == DestPtrSize)
1009 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
1010 }
1011 }
1012 }
Dan Gohman8a0eb362010-02-23 16:35:41 +00001013
Owen Anderson487375e2009-07-29 18:55:55 +00001014 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001015 case Instruction::Trunc:
1016 case Instruction::ZExt:
1017 case Instruction::SExt:
1018 case Instruction::FPTrunc:
1019 case Instruction::FPExt:
1020 case Instruction::UIToFP:
1021 case Instruction::SIToFP:
1022 case Instruction::FPToUI:
1023 case Instruction::FPToSI:
Owen Anderson487375e2009-07-29 18:55:55 +00001024 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001025 case Instruction::BitCast:
Chris Lattner6a6b3fb2007-12-11 07:29:44 +00001026 if (TD)
Chris Lattner9d051242009-10-25 06:08:26 +00001027 return FoldBitCast(Ops[0], DestTy, *TD);
Owen Anderson487375e2009-07-29 18:55:55 +00001028 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001029 case Instruction::Select:
Owen Anderson487375e2009-07-29 18:55:55 +00001030 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001031 case Instruction::ExtractElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001032 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001033 case Instruction::InsertElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001034 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001035 case Instruction::ShuffleVector:
Owen Anderson487375e2009-07-29 18:55:55 +00001036 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001037 case Instruction::GetElementPtr:
Chad Rosierc24b86f2011-12-01 03:08:23 +00001038 if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001039 return C;
Chad Rosierc24b86f2011-12-01 03:08:23 +00001040 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
Chris Lattner44d68b92007-01-31 00:51:48 +00001041 return C;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001042
Jay Foaded8db7d2011-07-21 14:31:17 +00001043 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
Chris Lattner2ae054a2007-01-30 23:45:45 +00001044 }
1045}
1046
Chris Lattnerd2265b42007-12-10 22:53:04 +00001047/// ConstantFoldCompareInstOperands - Attempt to constant fold a compare
1048/// instruction (icmp/fcmp) with the specified operands. If it fails, it
1049/// returns a constant expression of the specified operands.
1050///
1051Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001052 Constant *Ops0, Constant *Ops1,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001053 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001054 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001055 // fold: icmp (inttoptr x), null -> icmp x, 0
1056 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001057 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001058 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1059 //
1060 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1061 // around to know if bit truncation is happening.
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001062 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1063 if (TD && Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001064 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001065 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001066 // Convert the integer value to the right size to ensure we get the
1067 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001068 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001069 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001070 Constant *Null = Constant::getNullValue(C->getType());
Chad Rosierc24b86f2011-12-01 03:08:23 +00001071 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001072 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001073
Chris Lattnerd2265b42007-12-10 22:53:04 +00001074 // Only do this transformation if the int is intptrty in size, otherwise
1075 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001076 if (CE0->getOpcode() == Instruction::PtrToInt) {
1077 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1078 if (CE0->getType() == IntPtrTy) {
1079 Constant *C = CE0->getOperand(0);
1080 Constant *Null = Constant::getNullValue(C->getType());
1081 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1082 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001083 }
1084 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001085
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001086 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001087 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001088 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001089 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1090
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001091 // Convert the integer value to the right size to ensure we get the
1092 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001093 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001094 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001095 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001096 IntPtrTy, false);
Chad Rosierc24b86f2011-12-01 03:08:23 +00001097 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001098 }
1099
Chandler Carruth7ec50852012-11-01 08:07:29 +00001100 // Only do this transformation if the int is intptrty in size, otherwise
1101 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001102 if (CE0->getOpcode() == Instruction::PtrToInt) {
1103 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1104 if (CE0->getType() == IntPtrTy &&
1105 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1106 return ConstantFoldCompareInstOperands(Predicate,
1107 CE0->getOperand(0),
1108 CE1->getOperand(0),
1109 TD,
1110 TLI);
1111 }
1112 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001113 }
1114 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001115
Chris Lattner8fb74c62010-01-02 01:22:23 +00001116 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1117 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1118 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1119 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001120 Constant *LHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001121 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1122 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001123 Constant *RHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001124 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1125 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001126 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001127 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1128 Constant *Ops[] = { LHS, RHS };
Chad Rosierc24b86f2011-12-01 03:08:23 +00001129 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001130 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001131 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001132
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001133 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001134}
1135
1136
Chris Lattner2ae054a2007-01-30 23:45:45 +00001137/// ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a
1138/// getelementptr constantexpr, return the constant value being addressed by the
1139/// constant expression, or null if something is funny and we can't decide.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001140Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001141 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001142 if (!CE->getOperand(1)->isNullValue())
Chris Lattner2ae054a2007-01-30 23:45:45 +00001143 return 0; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001144
1145 // Loop over all of the operands, tracking down which value we are
1146 // addressing.
1147 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1148 C = C->getAggregateElement(CE->getOperand(i));
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001149 if (C == 0)
1150 return 0;
Chris Lattner67058832012-01-25 06:48:06 +00001151 }
1152 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001153}
1154
1155/// ConstantFoldLoadThroughGEPIndices - Given a constant and getelementptr
1156/// indices (with an *implied* zero pointer index that is not in the list),
1157/// return the constant value being addressed by a virtual load, or null if
1158/// something is funny and we can't decide.
1159Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1160 ArrayRef<Constant*> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001161 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001162 // addressing.
1163 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +00001164 C = C->getAggregateElement(Indices[i]);
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001165 if (C == 0)
1166 return 0;
Chris Lattnerf488b352012-01-24 05:43:50 +00001167 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001168 return C;
1169}
1170
1171
1172//===----------------------------------------------------------------------===//
1173// Constant Folding for Calls
1174//
John Criswell970af112005-10-27 16:00:10 +00001175
1176/// canConstantFoldCallTo - Return true if its even possible to fold a call to
1177/// the specified function.
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001178bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001179 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001180 case Intrinsic::fabs:
1181 case Intrinsic::log:
1182 case Intrinsic::log2:
1183 case Intrinsic::log10:
1184 case Intrinsic::exp:
1185 case Intrinsic::exp2:
1186 case Intrinsic::floor:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001187 case Intrinsic::sqrt:
Chad Rosier0155a632011-12-03 00:00:03 +00001188 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001189 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001190 case Intrinsic::bswap:
1191 case Intrinsic::ctpop:
1192 case Intrinsic::ctlz:
1193 case Intrinsic::cttz:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001194 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001195 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001196 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001197 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001198 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001199 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001200 case Intrinsic::convert_from_fp16:
1201 case Intrinsic::convert_to_fp16:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001202 case Intrinsic::x86_sse_cvtss2si:
1203 case Intrinsic::x86_sse_cvtss2si64:
1204 case Intrinsic::x86_sse_cvttss2si:
1205 case Intrinsic::x86_sse_cvttss2si64:
1206 case Intrinsic::x86_sse2_cvtsd2si:
1207 case Intrinsic::x86_sse2_cvtsd2si64:
1208 case Intrinsic::x86_sse2_cvttsd2si:
1209 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001210 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001211 default:
1212 return false;
1213 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001214 }
1215
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001216 if (!F->hasName())
1217 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001218 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001219
Chris Lattner785f9982007-08-08 06:55:43 +00001220 // In these cases, the check of the length is required. We don't want to
1221 // return true for a name like "cos\0blah" which strcmp would return equal to
1222 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001223 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001224 default: return false;
1225 case 'a':
Chad Rosierc0955a52013-02-20 23:57:30 +00001226 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
Chris Lattner785f9982007-08-08 06:55:43 +00001227 case 'c':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001228 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattner785f9982007-08-08 06:55:43 +00001229 case 'e':
Chris Lattner713d5232011-05-22 22:22:35 +00001230 return Name == "exp" || Name == "exp2";
Chris Lattner785f9982007-08-08 06:55:43 +00001231 case 'f':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001232 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattner785f9982007-08-08 06:55:43 +00001233 case 'l':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001234 return Name == "log" || Name == "log10";
Chris Lattner785f9982007-08-08 06:55:43 +00001235 case 'p':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001236 return Name == "pow";
Chris Lattner785f9982007-08-08 06:55:43 +00001237 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001238 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1239 Name == "sinf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001240 case 't':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001241 return Name == "tan" || Name == "tanh";
John Criswell970af112005-10-27 16:00:10 +00001242 }
1243}
1244
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001245static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
Chris Lattner229907c2011-07-18 04:54:35 +00001246 Type *Ty) {
Dan Gohmanb48f9042010-09-17 20:06:27 +00001247 sys::llvm_fenv_clearexcept();
John Criswell970af112005-10-27 16:00:10 +00001248 V = NativeFP(V);
Dan Gohmanb48f9042010-09-17 20:06:27 +00001249 if (sys::llvm_fenv_testexcept()) {
1250 sys::llvm_fenv_clearexcept();
Chris Lattner519a51a2008-03-30 18:02:00 +00001251 return 0;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001252 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001253
Owen Andersond4ebfd82013-02-06 22:43:31 +00001254 if (Ty->isHalfTy()) {
1255 APFloat APF(V);
1256 bool unused;
1257 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1258 return ConstantFP::get(Ty->getContext(), APF);
1259 }
Chris Lattner351534f2009-10-05 05:06:24 +00001260 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001261 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001262 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001263 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001264 llvm_unreachable("Can only constant fold half/float/double");
John Criswell970af112005-10-27 16:00:10 +00001265}
1266
Dan Gohman72efc042007-07-16 15:26:22 +00001267static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
Chris Lattner229907c2011-07-18 04:54:35 +00001268 double V, double W, Type *Ty) {
Dan Gohmanb48f9042010-09-17 20:06:27 +00001269 sys::llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001270 V = NativeFP(V, W);
Dan Gohmanb48f9042010-09-17 20:06:27 +00001271 if (sys::llvm_fenv_testexcept()) {
1272 sys::llvm_fenv_clearexcept();
Chris Lattner519a51a2008-03-30 18:02:00 +00001273 return 0;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001274 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001275
Owen Andersond4ebfd82013-02-06 22:43:31 +00001276 if (Ty->isHalfTy()) {
1277 APFloat APF(V);
1278 bool unused;
1279 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1280 return ConstantFP::get(Ty->getContext(), APF);
1281 }
Chris Lattner351534f2009-10-05 05:06:24 +00001282 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001283 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001284 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001285 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001286 llvm_unreachable("Can only constant fold half/float/double");
Dan Gohman72efc042007-07-16 15:26:22 +00001287}
1288
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001289/// ConstantFoldConvertToInt - Attempt to an SSE floating point to integer
1290/// conversion of a constant floating point. If roundTowardZero is false, the
1291/// default IEEE rounding is used (toward nearest, ties to even). This matches
1292/// the behavior of the non-truncating SSE instructions in the default rounding
1293/// mode. The desired integer type Ty is used to select how many bits are
1294/// available for the result. Returns null if the conversion cannot be
1295/// performed, otherwise returns the Constant value resulting from the
1296/// conversion.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001297static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1298 bool roundTowardZero, Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001299 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001300 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001301 assert(ResultWidth <= 64 &&
1302 "Can only constant fold conversions to 64 and 32 bit ints");
1303
1304 uint64_t UIntVal;
1305 bool isExact = false;
1306 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1307 : APFloat::rmNearestTiesToEven;
1308 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1309 /*isSigned=*/true, mode,
1310 &isExact);
1311 if (status != APFloat::opOK && status != APFloat::opInexact)
1312 return 0;
1313 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1314}
1315
John Criswell970af112005-10-27 16:00:10 +00001316/// ConstantFoldCall - Attempt to constant fold a call to the specified function
1317/// with the specified arguments, returning null if unsuccessful.
1318Constant *
Chad Rosierc24b86f2011-12-01 03:08:23 +00001319llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1320 const TargetLibraryInfo *TLI) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001321 if (!F->hasName())
1322 return 0;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001323 StringRef Name = F->getName();
Chris Lattner59d93982009-10-05 05:26:04 +00001324
Chris Lattner229907c2011-07-18 04:54:35 +00001325 Type *Ty = F->getReturnType();
Jay Foadf4b14a22011-07-19 13:32:40 +00001326 if (Operands.size() == 1) {
John Criswell970af112005-10-27 16:00:10 +00001327 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001328 if (F->getIntrinsicID() == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001329 APFloat Val(Op->getValueAPF());
1330
1331 bool lost = false;
1332 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1333
1334 return ConstantInt::get(F->getContext(), Val.bitcastToAPInt());
1335 }
Chad Rosier576c0f82011-12-01 23:16:03 +00001336 if (!TLI)
1337 return 0;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001338
Owen Andersond4ebfd82013-02-06 22:43:31 +00001339 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001340 return 0;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001341
1342 /// We only fold functions with finite arguments. Folding NaN and inf is
1343 /// likely to be aborted with an exception anyway, and some host libms
1344 /// have known errors raising exceptions.
1345 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
1346 return 0;
1347
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001348 /// Currently APFloat versions of these functions do not exist, so we use
1349 /// the host native double versions. Float versions are not called
1350 /// directly but for all these it is true (float)(f((double)arg)) ==
1351 /// f(arg). Long double not supported yet.
Owen Andersond4ebfd82013-02-06 22:43:31 +00001352 double V;
1353 if (Ty->isFloatTy())
1354 V = Op->getValueAPF().convertToFloat();
1355 else if (Ty->isDoubleTy())
1356 V = Op->getValueAPF().convertToDouble();
1357 else {
1358 bool unused;
1359 APFloat APF = Op->getValueAPF();
1360 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1361 V = APF.convertToDouble();
1362 }
1363
1364 switch (F->getIntrinsicID()) {
1365 default: break;
1366 case Intrinsic::fabs:
1367 return ConstantFoldFP(fabs, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001368#if HAVE_LOG2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001369 case Intrinsic::log2:
1370 return ConstantFoldFP(log2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001371#endif
1372#if HAVE_LOG
Owen Andersond4ebfd82013-02-06 22:43:31 +00001373 case Intrinsic::log:
1374 return ConstantFoldFP(log, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001375#endif
1376#if HAVE_LOG10
Owen Andersond4ebfd82013-02-06 22:43:31 +00001377 case Intrinsic::log10:
1378 return ConstantFoldFP(log10, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001379#endif
1380#if HAVE_EXP
Owen Andersond4ebfd82013-02-06 22:43:31 +00001381 case Intrinsic::exp:
1382 return ConstantFoldFP(exp, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001383#endif
1384#if HAVE_EXP2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001385 case Intrinsic::exp2:
1386 return ConstantFoldFP(exp2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001387#endif
Owen Andersond4ebfd82013-02-06 22:43:31 +00001388 case Intrinsic::floor:
1389 return ConstantFoldFP(floor, V, Ty);
1390 }
1391
Daniel Dunbarca414c72009-07-26 08:34:35 +00001392 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001393 case 'a':
Chad Rosier576c0f82011-12-01 23:16:03 +00001394 if (Name == "acos" && TLI->has(LibFunc::acos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001395 return ConstantFoldFP(acos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001396 else if (Name == "asin" && TLI->has(LibFunc::asin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001397 return ConstantFoldFP(asin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001398 else if (Name == "atan" && TLI->has(LibFunc::atan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001399 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001400 break;
1401 case 'c':
Chad Rosier576c0f82011-12-01 23:16:03 +00001402 if (Name == "ceil" && TLI->has(LibFunc::ceil))
Chris Lattner46b5c642009-11-06 04:27:31 +00001403 return ConstantFoldFP(ceil, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001404 else if (Name == "cos" && TLI->has(LibFunc::cos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001405 return ConstantFoldFP(cos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001406 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001407 return ConstantFoldFP(cosh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001408 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001409 return ConstantFoldFP(cos, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001410 break;
1411 case 'e':
Chad Rosier576c0f82011-12-01 23:16:03 +00001412 if (Name == "exp" && TLI->has(LibFunc::exp))
Chris Lattner46b5c642009-11-06 04:27:31 +00001413 return ConstantFoldFP(exp, V, Ty);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001414
Chad Rosier576c0f82011-12-01 23:16:03 +00001415 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
Chris Lattner713d5232011-05-22 22:22:35 +00001416 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1417 // C99 library.
1418 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1419 }
Chris Lattner785f9982007-08-08 06:55:43 +00001420 break;
1421 case 'f':
Chad Rosier576c0f82011-12-01 23:16:03 +00001422 if (Name == "fabs" && TLI->has(LibFunc::fabs))
Chris Lattner46b5c642009-11-06 04:27:31 +00001423 return ConstantFoldFP(fabs, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001424 else if (Name == "floor" && TLI->has(LibFunc::floor))
Chris Lattner46b5c642009-11-06 04:27:31 +00001425 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001426 break;
1427 case 'l':
Chad Rosier576c0f82011-12-01 23:16:03 +00001428 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
Chris Lattner46b5c642009-11-06 04:27:31 +00001429 return ConstantFoldFP(log, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001430 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
Chris Lattner46b5c642009-11-06 04:27:31 +00001431 return ConstantFoldFP(log10, V, Ty);
Chandler Carruth352d9b12011-01-10 09:02:58 +00001432 else if (F->getIntrinsicID() == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001433 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001434 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001435 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001436 else // Undefined
Owen Anderson5a1acd92009-07-31 20:28:14 +00001437 return Constant::getNullValue(Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001438 }
1439 break;
1440 case 's':
Chad Rosier576c0f82011-12-01 23:16:03 +00001441 if (Name == "sin" && TLI->has(LibFunc::sin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001442 return ConstantFoldFP(sin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001443 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001444 return ConstantFoldFP(sinh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001445 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
Chris Lattner46b5c642009-11-06 04:27:31 +00001446 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001447 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001448 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001449 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001450 return ConstantFoldFP(sin, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001451 break;
1452 case 't':
Chad Rosier576c0f82011-12-01 23:16:03 +00001453 if (Name == "tan" && TLI->has(LibFunc::tan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001454 return ConstantFoldFP(tan, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001455 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001456 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001457 break;
1458 default:
1459 break;
John Criswell970af112005-10-27 16:00:10 +00001460 }
Chris Lattner9ca7c092009-10-05 05:00:35 +00001461 return 0;
1462 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001463
Chris Lattner9ca7c092009-10-05 05:00:35 +00001464 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001465 switch (F->getIntrinsicID()) {
1466 case Intrinsic::bswap:
Chris Lattner46b5c642009-11-06 04:27:31 +00001467 return ConstantInt::get(F->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001468 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001469 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001470 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001471 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001472
1473 bool lost = false;
1474 APFloat::opStatus status =
1475 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1476
1477 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001478 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001479 assert(status == APFloat::opOK && !lost &&
1480 "Precision lost during fp16 constfolding");
1481
1482 return ConstantFP::get(F->getContext(), Val);
1483 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001484 default:
1485 return 0;
1486 }
John Criswell970af112005-10-27 16:00:10 +00001487 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001488
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001489 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001490 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001491 isa<ConstantDataVector>(Operands[0])) {
1492 Constant *Op = cast<Constant>(Operands[0]);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001493 switch (F->getIntrinsicID()) {
1494 default: break;
1495 case Intrinsic::x86_sse_cvtss2si:
1496 case Intrinsic::x86_sse_cvtss2si64:
1497 case Intrinsic::x86_sse2_cvtsd2si:
1498 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001499 if (ConstantFP *FPOp =
1500 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1501 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1502 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001503 case Intrinsic::x86_sse_cvttss2si:
1504 case Intrinsic::x86_sse_cvttss2si64:
1505 case Intrinsic::x86_sse2_cvttsd2si:
1506 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001507 if (ConstantFP *FPOp =
1508 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001509 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001510 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001511 }
1512 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001513
Dan Gohmancf39be32010-02-17 00:54:58 +00001514 if (isa<UndefValue>(Operands[0])) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001515 if (F->getIntrinsicID() == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001516 return Operands[0];
1517 return 0;
1518 }
1519
Chris Lattner9ca7c092009-10-05 05:00:35 +00001520 return 0;
1521 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001522
Jay Foadf4b14a22011-07-19 13:32:40 +00001523 if (Operands.size() == 2) {
John Criswell970af112005-10-27 16:00:10 +00001524 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001525 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001526 return 0;
Owen Andersond4ebfd82013-02-06 22:43:31 +00001527 double Op1V;
1528 if (Ty->isFloatTy())
1529 Op1V = Op1->getValueAPF().convertToFloat();
1530 else if (Ty->isDoubleTy())
1531 Op1V = Op1->getValueAPF().convertToDouble();
1532 else {
1533 bool unused;
1534 APFloat APF = Op1->getValueAPF();
1535 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1536 Op1V = APF.convertToDouble();
1537 }
1538
John Criswell970af112005-10-27 16:00:10 +00001539 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001540 if (Op2->getType() != Op1->getType())
1541 return 0;
Chad Rosier576c0f82011-12-01 23:16:03 +00001542
Owen Andersond4ebfd82013-02-06 22:43:31 +00001543 double Op2V;
1544 if (Ty->isFloatTy())
1545 Op2V = Op2->getValueAPF().convertToFloat();
1546 else if (Ty->isDoubleTy())
1547 Op2V = Op2->getValueAPF().convertToDouble();
1548 else {
1549 bool unused;
1550 APFloat APF = Op2->getValueAPF();
1551 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1552 Op2V = APF.convertToDouble();
1553 }
John Criswell970af112005-10-27 16:00:10 +00001554
Chad Rosier0155a632011-12-03 00:00:03 +00001555 if (F->getIntrinsicID() == Intrinsic::pow) {
1556 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1557 }
1558 if (!TLI)
1559 return 0;
Chad Rosier576c0f82011-12-01 23:16:03 +00001560 if (Name == "pow" && TLI->has(LibFunc::pow))
Chris Lattner46b5c642009-11-06 04:27:31 +00001561 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001562 if (Name == "fmod" && TLI->has(LibFunc::fmod))
Chris Lattner46b5c642009-11-06 04:27:31 +00001563 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001564 if (Name == "atan2" && TLI->has(LibFunc::atan2))
Chris Lattner46b5c642009-11-06 04:27:31 +00001565 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
Chris Lattner26933dd2007-01-15 06:27:37 +00001566 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001567 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isHalfTy())
1568 return ConstantFP::get(F->getContext(),
1569 APFloat((float)std::pow((float)Op1V,
1570 (int)Op2C->getZExtValue())));
Chandler Carruth352d9b12011-01-10 09:02:58 +00001571 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001572 return ConstantFP::get(F->getContext(),
1573 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001574 (int)Op2C->getZExtValue())));
Chandler Carruth352d9b12011-01-10 09:02:58 +00001575 if (F->getIntrinsicID() == Intrinsic::powi && Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001576 return ConstantFP::get(F->getContext(),
1577 APFloat((double)std::pow((double)Op1V,
1578 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001579 }
Chris Lattner9ca7c092009-10-05 05:00:35 +00001580 return 0;
John Criswell970af112005-10-27 16:00:10 +00001581 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001582
Chris Lattner59d93982009-10-05 05:26:04 +00001583 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1584 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
1585 switch (F->getIntrinsicID()) {
1586 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001587 case Intrinsic::sadd_with_overflow:
1588 case Intrinsic::uadd_with_overflow:
1589 case Intrinsic::ssub_with_overflow:
1590 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001591 case Intrinsic::smul_with_overflow:
1592 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001593 APInt Res;
1594 bool Overflow;
1595 switch (F->getIntrinsicID()) {
Craig Toppera2886c22012-02-07 05:05:23 +00001596 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001597 case Intrinsic::sadd_with_overflow:
1598 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1599 break;
1600 case Intrinsic::uadd_with_overflow:
1601 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1602 break;
1603 case Intrinsic::ssub_with_overflow:
1604 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1605 break;
1606 case Intrinsic::usub_with_overflow:
1607 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1608 break;
1609 case Intrinsic::smul_with_overflow:
1610 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1611 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001612 case Intrinsic::umul_with_overflow:
1613 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1614 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001615 }
Chris Lattner59d93982009-10-05 05:26:04 +00001616 Constant *Ops[] = {
Chris Lattner698661c2010-10-14 00:05:07 +00001617 ConstantInt::get(F->getContext(), Res),
1618 ConstantInt::get(Type::getInt1Ty(F->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001619 };
Chris Lattnercc19efa2011-06-20 04:01:31 +00001620 return ConstantStruct::get(cast<StructType>(F->getReturnType()), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001621 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001622 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001623 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1624 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001625 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1626 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001627 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1628 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001629 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001630 }
1631 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001632
Chris Lattner59d93982009-10-05 05:26:04 +00001633 return 0;
1634 }
1635 return 0;
John Criswell970af112005-10-27 16:00:10 +00001636 }
1637 return 0;
1638}