blob: cd25acb9ba9a713c7480e673258398293fda2227 [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"
Alp Tokerc817d6a2014-06-09 18:28:53 +000024#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DerivedTypes.h"
28#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000029#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000030#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Instructions.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/Operator.h"
Torok Edwin56d06592009-07-11 20:10:48 +000034#include "llvm/Support/ErrorHandling.h"
John Criswell970af112005-10-27 16:00:10 +000035#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>
Alp Tokerc817d6a2014-06-09 18:28:53 +000039
40#ifdef HAVE_FENV_H
41#include <fenv.h>
Alp Tokerc817d6a2014-06-09 18:28:53 +000042#endif
43
John Criswell970af112005-10-27 16:00:10 +000044using namespace llvm;
45
Chris Lattner44d68b92007-01-31 00:51:48 +000046//===----------------------------------------------------------------------===//
47// Constant Folding internal helper functions
48//===----------------------------------------------------------------------===//
49
Sanjay Patel0d7dee62014-10-02 15:13:22 +000050/// Constant fold bitcast, symbolically evaluating it with DataLayout.
51/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000052/// ConstantExpr if unfoldable.
Chris Lattner229907c2011-07-18 04:54:35 +000053static Constant *FoldBitCast(Constant *C, Type *DestTy,
Micah Villmowcdfe20b2012-10-08 16:38:25 +000054 const DataLayout &TD) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000055 // Catch the obvious splat cases.
56 if (C->isNullValue() && !DestTy->isX86_MMXTy())
57 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000058 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
59 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +000060 return Constant::getAllOnesValue(DestTy);
61
Rafael Espindolabb893fe2012-01-27 23:33:07 +000062 // Handle a vector->integer cast.
63 if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
Michael Ilsemana7b93c12013-02-26 22:51:07 +000064 VectorType *VTy = dyn_cast<VectorType>(C->getType());
Craig Topper9f008862014-04-15 04:59:12 +000065 if (!VTy)
Rafael Espindolabb893fe2012-01-27 23:33:07 +000066 return ConstantExpr::getBitCast(C, DestTy);
67
Michael Ilsemana7b93c12013-02-26 22:51:07 +000068 unsigned NumSrcElts = VTy->getNumElements();
69 Type *SrcEltTy = VTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +000070
Rafael Espindolabb893fe2012-01-27 23:33:07 +000071 // If the vector is a vector of floating point, convert it to vector of int
72 // to simplify things.
Chris Lattner8213c8a2012-02-06 21:56:39 +000073 if (SrcEltTy->isFloatingPointTy()) {
74 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Rafael Espindolabb893fe2012-01-27 23:33:07 +000075 Type *SrcIVTy =
76 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
Chandler Carruthef860a22013-01-02 09:10:48 +000077 // Ask IR to do the conversion now that #elts line up.
Rafael Espindolabb893fe2012-01-27 23:33:07 +000078 C = ConstantExpr::getBitCast(C, SrcIVTy);
79 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000080
Michael Ilsemana7b93c12013-02-26 22:51:07 +000081 ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
Craig Topper9f008862014-04-15 04:59:12 +000082 if (!CDV)
Michael Ilsemana7b93c12013-02-26 22:51:07 +000083 return ConstantExpr::getBitCast(C, DestTy);
84
Rafael Espindolabb893fe2012-01-27 23:33:07 +000085 // Now that we know that the input value is a vector of integers, just shift
86 // and insert them into our result.
Chris Lattner8213c8a2012-02-06 21:56:39 +000087 unsigned BitShift = TD.getTypeAllocSizeInBits(SrcEltTy);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000088 APInt Result(IT->getBitWidth(), 0);
89 for (unsigned i = 0; i != NumSrcElts; ++i) {
Chris Lattner8213c8a2012-02-06 21:56:39 +000090 Result <<= BitShift;
91 if (TD.isLittleEndian())
92 Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
93 else
94 Result |= CDV->getElementAsInteger(i);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000095 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000096
Rafael Espindolabb893fe2012-01-27 23:33:07 +000097 return ConstantInt::get(IT, Result);
98 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000099
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000100 // The code below only handles casts to vectors currently.
Chris Lattner229907c2011-07-18 04:54:35 +0000101 VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000102 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000103 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000104
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000105 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
106 // vector so the code below can handle it uniformly.
107 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
108 Constant *Ops = C; // don't take the address of C!
Chris Lattner69229312011-02-15 00:14:00 +0000109 return FoldBitCast(ConstantVector::get(Ops), DestTy, TD);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000110 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000111
Chris Lattner9d051242009-10-25 06:08:26 +0000112 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000113 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000114 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000115
Chandler Carruthef860a22013-01-02 09:10:48 +0000116 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000117 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000118 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000119 if (NumDstElt == NumSrcElt)
120 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000121
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000122 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000123 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000124
125 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000126 // requires endianness information to do the right thing. For example,
127 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
128 // folds to (little endian):
129 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
130 // and to (big endian):
131 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000132
Chris Lattner9d051242009-10-25 06:08:26 +0000133 // First thing is first. We only want to think about integer here, so if
134 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000135 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000136 // Fold to an vector of integers with same size as our FP type.
137 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000138 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000139 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
140 // Recursively handle this integer conversion, if possible.
141 C = FoldBitCast(C, DestIVTy, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000142
Chandler Carruthef860a22013-01-02 09:10:48 +0000143 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000144 return ConstantExpr::getBitCast(C, DestTy);
145 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000146
Chris Lattner9d051242009-10-25 06:08:26 +0000147 // Okay, we know the destination is integer, if the input is FP, convert
148 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000149 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000150 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000151 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000152 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000153 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000154 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000155 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000156 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
157 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000158 return C;
159 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000160
Chris Lattner9d051242009-10-25 06:08:26 +0000161 // Now we know that the input and output vectors are both integer vectors
162 // of the same size, and that their #elements is not the same. Do the
163 // conversion here, which depends on whether the input or output has
164 // more elements.
165 bool isLittleEndian = TD.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000166
Chris Lattner9d051242009-10-25 06:08:26 +0000167 SmallVector<Constant*, 32> Result;
168 if (NumDstElt < NumSrcElt) {
169 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
170 Constant *Zero = Constant::getNullValue(DstEltTy);
171 unsigned Ratio = NumSrcElt/NumDstElt;
172 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
173 unsigned SrcElt = 0;
174 for (unsigned i = 0; i != NumDstElt; ++i) {
175 // Build each element of the result.
176 Constant *Elt = Zero;
177 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
178 for (unsigned j = 0; j != Ratio; ++j) {
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000179 Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
Chris Lattner9d051242009-10-25 06:08:26 +0000180 if (!Src) // Reject constantexpr elements.
181 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000182
Chris Lattner9d051242009-10-25 06:08:26 +0000183 // Zero extend the element to the right size.
184 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000185
Chris Lattner9d051242009-10-25 06:08:26 +0000186 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000187 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000188 ConstantInt::get(Src->getType(), ShiftAmt));
189 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000190
Chris Lattner9d051242009-10-25 06:08:26 +0000191 // Mix it in.
192 Elt = ConstantExpr::getOr(Elt, Src);
193 }
194 Result.push_back(Elt);
195 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000196 return ConstantVector::get(Result);
197 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000198
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000199 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
200 unsigned Ratio = NumDstElt/NumSrcElt;
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000201 unsigned DstBitSize = TD.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000202
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000203 // Loop over each source value, expanding into multiple results.
204 for (unsigned i = 0; i != NumSrcElt; ++i) {
205 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
206 if (!Src) // Reject constantexpr elements.
207 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000208
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000209 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
210 for (unsigned j = 0; j != Ratio; ++j) {
211 // Shift the piece of the value into the right place, depending on
212 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000213 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000214 ConstantInt::get(Src->getType(), ShiftAmt));
215 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000216
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000217 // Truncate the element to an integer with the same pointer size and
218 // convert the element back to a pointer using a inttoptr.
219 if (DstEltTy->isPointerTy()) {
220 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
221 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
222 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
223 continue;
224 }
225
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000226 // Truncate and remember this piece.
227 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000228 }
229 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000230
Chris Lattner69229312011-02-15 00:14:00 +0000231 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000232}
233
234
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000235/// If this constant is a constant offset from a global, return the global and
236/// the constant. Because of constantexprs, this function is recursive.
Chris Lattner44d68b92007-01-31 00:51:48 +0000237static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
Benjamin Kramer546bb562013-01-23 21:21:24 +0000238 APInt &Offset, const DataLayout &TD) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000239 // Trivial case, constant is the global.
240 if ((GV = dyn_cast<GlobalValue>(C))) {
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000241 unsigned BitWidth = TD.getPointerTypeSizeInBits(GV->getType());
242 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000243 return true;
244 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000245
Chris Lattner44d68b92007-01-31 00:51:48 +0000246 // Otherwise, if this isn't a constant expr, bail out.
247 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
248 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000249
Chris Lattner44d68b92007-01-31 00:51:48 +0000250 // Look through ptr->int and ptr->ptr casts.
251 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenaultcaa9c712014-07-14 22:39:26 +0000252 CE->getOpcode() == Instruction::BitCast ||
253 CE->getOpcode() == Instruction::AddrSpaceCast)
Chris Lattner44d68b92007-01-31 00:51:48 +0000254 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, TD);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000255
256 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000257 GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
258 if (!GEP)
259 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000260
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000261 unsigned BitWidth = TD.getPointerTypeSizeInBits(GEP->getType());
262 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000263
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000264 // If the base isn't a global+constant, we aren't either.
265 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, TD))
266 return false;
267
268 // Otherwise, add any offset that our operands provide.
269 if (!GEP->accumulateConstantOffset(TD, TmpOffset))
270 return false;
271
272 Offset = TmpOffset;
273 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000274}
275
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000276/// Recursive helper to read bits out of global. C is the constant being copied
277/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
278/// results into and BytesLeft is the number of bytes left in
279/// the CurPtr buffer. TD is the target data.
Chris Lattnered00b802009-10-23 06:23:49 +0000280static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
281 unsigned char *CurPtr, unsigned BytesLeft,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000282 const DataLayout &TD) {
Chris Lattnered00b802009-10-23 06:23:49 +0000283 assert(ByteOffset <= TD.getTypeAllocSize(C->getType()) &&
284 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000285
Chris Lattner3db7bd22009-10-24 05:27:19 +0000286 // If this element is zero or undefined, we can just return since *CurPtr is
287 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000288 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
289 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000290
Chris Lattnered00b802009-10-23 06:23:49 +0000291 if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
292 if (CI->getBitWidth() > 64 ||
293 (CI->getBitWidth() & 7) != 0)
294 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000295
Chris Lattnered00b802009-10-23 06:23:49 +0000296 uint64_t Val = CI->getZExtValue();
297 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000298
Chris Lattnered00b802009-10-23 06:23:49 +0000299 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000300 int n = ByteOffset;
301 if (!TD.isLittleEndian())
302 n = IntBytes - n - 1;
303 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000304 ++ByteOffset;
305 }
306 return true;
307 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000308
Chris Lattnered00b802009-10-23 06:23:49 +0000309 if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
310 if (CFP->getType()->isDoubleTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000311 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000312 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
313 }
314 if (CFP->getType()->isFloatTy()){
Chris Lattner9d051242009-10-25 06:08:26 +0000315 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000316 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
317 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000318 if (CFP->getType()->isHalfTy()){
319 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), TD);
320 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, TD);
321 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000322 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000323 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000324
Chris Lattnered00b802009-10-23 06:23:49 +0000325 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
326 const StructLayout *SL = TD.getStructLayout(CS->getType());
327 unsigned Index = SL->getElementContainingOffset(ByteOffset);
328 uint64_t CurEltOffset = SL->getElementOffset(Index);
329 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000330
Chris Lattnered00b802009-10-23 06:23:49 +0000331 while (1) {
332 // If the element access is to the element itself and not to tail padding,
333 // read the bytes from the element.
334 uint64_t EltSize = TD.getTypeAllocSize(CS->getOperand(Index)->getType());
335
336 if (ByteOffset < EltSize &&
337 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
338 BytesLeft, TD))
339 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000340
Chris Lattnered00b802009-10-23 06:23:49 +0000341 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000342
Chris Lattnered00b802009-10-23 06:23:49 +0000343 // Check to see if we read from the last struct element, if so we're done.
344 if (Index == CS->getType()->getNumElements())
345 return true;
346
347 // If we read all of the bytes we needed from this element we're done.
348 uint64_t NextEltOffset = SL->getElementOffset(Index);
349
Matt Arsenault8c789092013-08-12 23:15:58 +0000350 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000351 return true;
352
353 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000354 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
355 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000356 ByteOffset = 0;
357 CurEltOffset = NextEltOffset;
358 }
359 // not reached.
360 }
361
Chris Lattner67058832012-01-25 06:48:06 +0000362 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
363 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000364 Type *EltTy = C->getType()->getSequentialElementType();
Chris Lattner67058832012-01-25 06:48:06 +0000365 uint64_t EltSize = TD.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000366 uint64_t Index = ByteOffset / EltSize;
367 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000368 uint64_t NumElts;
369 if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
370 NumElts = AT->getNumElements();
371 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000372 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000373
Chris Lattner67058832012-01-25 06:48:06 +0000374 for (; Index != NumElts; ++Index) {
375 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
376 BytesLeft, TD))
377 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000378
379 uint64_t BytesWritten = EltSize - Offset;
380 assert(BytesWritten <= EltSize && "Not indexing into this element?");
381 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000382 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000383
Chris Lattner67058832012-01-25 06:48:06 +0000384 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000385 BytesLeft -= BytesWritten;
386 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000387 }
388 return true;
389 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000390
Anders Carlssond21b06a2011-02-06 20:11:56 +0000391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000392 if (CE->getOpcode() == Instruction::IntToPtr &&
Matt Arsenault7a960a82013-08-20 21:20:04 +0000393 CE->getOperand(0)->getType() == TD.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000394 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Chris Lattner67058832012-01-25 06:48:06 +0000395 BytesLeft, TD);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000396 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000397 }
398
Chris Lattnered00b802009-10-23 06:23:49 +0000399 // Otherwise, unknown initializer type.
400 return false;
401}
402
403static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000404 const DataLayout &TD) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000405 PointerType *PTy = cast<PointerType>(C->getType());
406 Type *LoadTy = PTy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000407 IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000408
Chris Lattnered00b802009-10-23 06:23:49 +0000409 // If this isn't an integer load we can't fold it directly.
410 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000411 unsigned AS = PTy->getAddressSpace();
412
Chris Lattnered00b802009-10-23 06:23:49 +0000413 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000414 // and then bitcast the result. This can be useful for union cases. Note
415 // that address spaces don't matter here since we're not going to result in
416 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000417 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000418 if (LoadTy->isHalfTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000419 MapTy = Type::getInt16PtrTy(C->getContext(), AS);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000420 else if (LoadTy->isFloatTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000421 MapTy = Type::getInt32PtrTy(C->getContext(), AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000422 else if (LoadTy->isDoubleTy())
Matt Arsenault7a960a82013-08-20 21:20:04 +0000423 MapTy = Type::getInt64PtrTy(C->getContext(), AS);
Duncan Sands19d0b472010-02-16 11:11:14 +0000424 else if (LoadTy->isVectorTy()) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000425 MapTy = PointerType::getIntNPtrTy(C->getContext(),
426 TD.getTypeAllocSizeInBits(LoadTy),
427 AS);
Chris Lattnerccf1e842009-10-23 06:57:37 +0000428 } else
Craig Topper9f008862014-04-15 04:59:12 +0000429 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000430
Chris Lattner9d051242009-10-25 06:08:26 +0000431 C = FoldBitCast(C, MapTy, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000432 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, TD))
Chris Lattner9d051242009-10-25 06:08:26 +0000433 return FoldBitCast(Res, LoadTy, TD);
Craig Topper9f008862014-04-15 04:59:12 +0000434 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000435 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000436
Chris Lattnered00b802009-10-23 06:23:49 +0000437 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000438 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000439 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000440
Chris Lattnered00b802009-10-23 06:23:49 +0000441 GlobalValue *GVal;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000442 APInt Offset;
Chris Lattnered00b802009-10-23 06:23:49 +0000443 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, TD))
Craig Topper9f008862014-04-15 04:59:12 +0000444 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000445
Chris Lattnered00b802009-10-23 06:23:49 +0000446 GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000447 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000448 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000449 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000450
451 // If we're loading off the beginning of the global, some bytes may be valid,
452 // but we don't try to handle this.
Matt Arsenault8c789092013-08-12 23:15:58 +0000453 if (Offset.isNegative())
Craig Topper9f008862014-04-15 04:59:12 +0000454 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000455
Chris Lattnered00b802009-10-23 06:23:49 +0000456 // If we're not accessing anything in this constant, the result is undefined.
Benjamin Kramer546bb562013-01-23 21:21:24 +0000457 if (Offset.getZExtValue() >=
458 TD.getTypeAllocSize(GV->getInitializer()->getType()))
Chris Lattnered00b802009-10-23 06:23:49 +0000459 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000460
Chris Lattner59f94c02009-10-23 06:50:36 +0000461 unsigned char RawBytes[32] = {0};
Benjamin Kramer546bb562013-01-23 21:21:24 +0000462 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
Chris Lattnered00b802009-10-23 06:23:49 +0000463 BytesLoaded, TD))
Craig Topper9f008862014-04-15 04:59:12 +0000464 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000465
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000466 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
467 if (TD.isLittleEndian()) {
468 ResultVal = RawBytes[BytesLoaded - 1];
469 for (unsigned i = 1; i != BytesLoaded; ++i) {
470 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000471 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000472 }
473 } else {
474 ResultVal = RawBytes[0];
475 for (unsigned i = 1; i != BytesLoaded; ++i) {
476 ResultVal <<= 8;
477 ResultVal |= RawBytes[i];
478 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000479 }
Chris Lattnered00b802009-10-23 06:23:49 +0000480
Chris Lattner59f94c02009-10-23 06:50:36 +0000481 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000482}
483
Chandler Carrutha0e56952014-05-15 09:56:28 +0000484static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
485 const DataLayout *DL) {
486 if (!DL)
487 return nullptr;
488 auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
489 if (!DestPtrTy)
490 return nullptr;
491 Type *DestTy = DestPtrTy->getElementType();
492
493 Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
494 if (!C)
495 return nullptr;
496
497 do {
498 Type *SrcTy = C->getType();
499
500 // If the type sizes are the same and a cast is legal, just directly
501 // cast the constant.
502 if (DL->getTypeSizeInBits(DestTy) == DL->getTypeSizeInBits(SrcTy)) {
503 Instruction::CastOps Cast = Instruction::BitCast;
504 // If we are going from a pointer to int or vice versa, we spell the cast
505 // differently.
506 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
507 Cast = Instruction::IntToPtr;
508 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
509 Cast = Instruction::PtrToInt;
510
511 if (CastInst::castIsValid(Cast, C, DestTy))
512 return ConstantExpr::getCast(Cast, C, DestTy);
513 }
514
515 // If this isn't an aggregate type, there is nothing we can do to drill down
516 // and find a bitcastable constant.
517 if (!SrcTy->isAggregateType())
518 return nullptr;
519
520 // We're simulating a load through a pointer that was bitcast to point to
521 // a different type, so we can try to walk down through the initial
522 // elements of an aggregate to see if some part of th e aggregate is
523 // castable to implement the "load" semantic model.
524 C = C->getAggregateElement(0u);
525 } while (C);
526
527 return nullptr;
528}
529
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000530/// Return the value that a load from C would produce if it is constant and
531/// determinable. If this is not determinable, return null.
Chris Lattner1664a4f2009-10-22 06:25:11 +0000532Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000533 const DataLayout *TD) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000534 // First, try the easy cases:
535 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
536 if (GV->isConstant() && GV->hasDefinitiveInitializer())
537 return GV->getInitializer();
538
Chris Lattnercf7e8942009-10-22 06:44:07 +0000539 // If the loaded value isn't a constant expr, we can't handle it.
540 ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000541 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000542 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000543
Chris Lattnercf7e8942009-10-22 06:44:07 +0000544 if (CE->getOpcode() == Instruction::GetElementPtr) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000545 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
546 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000547 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000548 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
549 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000550 }
551 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000552 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000553
Chandler Carrutha0e56952014-05-15 09:56:28 +0000554 if (CE->getOpcode() == Instruction::BitCast)
555 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, TD))
556 return LoadedC;
557
Chris Lattnercf7e8942009-10-22 06:44:07 +0000558 // Instead of loading constant c string, use corresponding integer value
559 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000560 StringRef Str;
561 if (TD && getConstantStringInfo(CE, Str) && !Str.empty()) {
562 unsigned StrLen = Str.size();
Chris Lattner229907c2011-07-18 04:54:35 +0000563 Type *Ty = cast<PointerType>(CE->getType())->getElementType();
Chris Lattnered00b802009-10-23 06:23:49 +0000564 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000565 // Replace load with immediate integer if the result is an integer or fp
566 // value.
567 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000568 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000569 APInt StrVal(NumBits, 0);
570 APInt SingleChar(NumBits, 0);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000571 if (TD->isLittleEndian()) {
Chris Lattnered00b802009-10-23 06:23:49 +0000572 for (signed i = StrLen-1; i >= 0; i--) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000573 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
Chris Lattner51d2f702009-10-22 06:38:35 +0000574 StrVal = (StrVal << 8) | SingleChar;
575 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000576 } else {
Chris Lattnered00b802009-10-23 06:23:49 +0000577 for (unsigned i = 0; i < StrLen; i++) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000578 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
579 StrVal = (StrVal << 8) | SingleChar;
580 }
581 // Append NULL at the end.
582 SingleChar = 0;
583 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000584 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000585
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000586 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
587 if (Ty->isFloatingPointTy())
588 Res = ConstantExpr::getBitCast(Res, Ty);
589 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000590 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000591 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000592
Chris Lattnercf7e8942009-10-22 06:44:07 +0000593 // If this load comes from anywhere in a constant global, and if the global
594 // is all undef or zero, we know what it loads.
Dan Gohman0f124e12011-01-24 18:53:32 +0000595 if (GlobalVariable *GV =
596 dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, TD))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000597 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner229907c2011-07-18 04:54:35 +0000598 Type *ResTy = cast<PointerType>(C->getType())->getElementType();
Chris Lattnercf7e8942009-10-22 06:44:07 +0000599 if (GV->getInitializer()->isNullValue())
600 return Constant::getNullValue(ResTy);
601 if (isa<UndefValue>(GV->getInitializer()))
602 return UndefValue::get(ResTy);
603 }
604 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000605
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000606 // Try hard to fold loads from bitcasted strange and non-type-safe things.
607 if (TD)
Chris Lattnered00b802009-10-23 06:23:49 +0000608 return FoldReinterpretLoadFromConstPtr(CE, *TD);
Craig Topper9f008862014-04-15 04:59:12 +0000609 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000610}
611
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000612static Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout *TD){
Craig Topper9f008862014-04-15 04:59:12 +0000613 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000614
Chris Lattner1664a4f2009-10-22 06:25:11 +0000615 if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
616 return ConstantFoldLoadFromConstPtr(C, TD);
Chris Lattnered00b802009-10-23 06:23:49 +0000617
Craig Topper9f008862014-04-15 04:59:12 +0000618 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000619}
Chris Lattner44d68b92007-01-31 00:51:48 +0000620
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000621/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000622/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000623/// these together. If target data info is available, it is provided as DL,
624/// otherwise DL is null.
Chris Lattner44d68b92007-01-31 00:51:48 +0000625static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
Nick Lewycky06417742013-02-14 03:23:37 +0000626 Constant *Op1, const DataLayout *DL){
Chris Lattner44d68b92007-01-31 00:51:48 +0000627 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000628
Chris Lattner44d68b92007-01-31 00:51:48 +0000629 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
630 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
631 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000632
633
Nick Lewycky06417742013-02-14 03:23:37 +0000634 if (Opc == Instruction::And && DL) {
Benjamin Kramerec1bb4f2013-04-19 16:56:24 +0000635 unsigned BitWidth = DL->getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000636 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
637 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000638 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
639 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
Nick Lewycky06417742013-02-14 03:23:37 +0000640 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
641 // All the bits of Op0 that the 'and' could be masking are already zero.
642 return Op0;
643 }
644 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
645 // All the bits of Op1 that the 'and' could be masking are already zero.
646 return Op1;
647 }
648
649 APInt KnownZero = KnownZero0 | KnownZero1;
650 APInt KnownOne = KnownOne0 & KnownOne1;
651 if ((KnownZero | KnownOne).isAllOnesValue()) {
652 return ConstantInt::get(Op0->getType(), KnownOne);
653 }
654 }
655
Chris Lattner44d68b92007-01-31 00:51:48 +0000656 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
657 // constant. This happens frequently when iterating over a global array.
Nick Lewycky06417742013-02-14 03:23:37 +0000658 if (Opc == Instruction::Sub && DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000659 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000660 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000661
Nick Lewycky06417742013-02-14 03:23:37 +0000662 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, *DL))
663 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, *DL) &&
Chris Lattner44d68b92007-01-31 00:51:48 +0000664 GV1 == GV2) {
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000665 unsigned OpSize = DL->getTypeSizeInBits(Op0->getType());
666
Chris Lattner44d68b92007-01-31 00:51:48 +0000667 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000668 // PtrToInt may change the bitwidth so we have convert to the right size
669 // first.
670 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
671 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000672 }
673 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000674
Craig Topper9f008862014-04-15 04:59:12 +0000675 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000676}
677
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000678/// If array indices are not pointer-sized integers, explicitly cast them so
679/// that they aren't implicitly casted by the getelementptr.
Jay Foadf4b14a22011-07-19 13:32:40 +0000680static Constant *CastGEPIndices(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000681 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000682 const TargetLibraryInfo *TLI) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000683 if (!TD)
Craig Topper9f008862014-04-15 04:59:12 +0000684 return nullptr;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000685
686 Type *IntPtrTy = TD->getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000687
688 bool Any = false;
689 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000690 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000691 if ((i == 1 ||
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000692 !isa<StructType>(GetElementPtrInst::getIndexedType(
693 Ops[0]->getType(),
694 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000695 Ops[i]->getType() != IntPtrTy) {
696 Any = true;
697 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
698 true,
699 IntPtrTy,
700 true),
701 Ops[i], IntPtrTy));
702 } else
703 NewIdxs.push_back(Ops[i]);
704 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000705
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000706 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000707 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000708
709 Constant *C = ConstantExpr::getGetElementPtr(Ops[0], NewIdxs);
710 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
Chad Rosierc24b86f2011-12-01 03:08:23 +0000711 if (Constant *Folded = ConstantFoldConstantExpression(CE, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000712 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000713 }
714
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000715 return C;
716}
717
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000718/// Strip the pointer casts, but preserve the address space information.
719static Constant* StripPtrCastKeepAS(Constant* Ptr) {
720 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
721 PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000722 Ptr = Ptr->stripPointerCasts();
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000723 PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
724
725 // Preserve the address space number of the pointer.
726 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
727 NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
728 OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000729 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000730 }
731 return Ptr;
732}
733
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000734/// If we can symbolically evaluate the GEP constant expression, do so.
Jay Foadf4b14a22011-07-19 13:32:40 +0000735static Constant *SymbolicallyEvaluateGEP(ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000736 Type *ResultTy, const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000737 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000738 Constant *Ptr = Ops[0];
Matt Arsenault8c789092013-08-12 23:15:58 +0000739 if (!TD || !Ptr->getType()->getPointerElementType()->isSized() ||
Nadav Rotem3924cb02011-12-05 06:29:09 +0000740 !Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000741 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000742
Matt Arsenault7a960a82013-08-20 21:20:04 +0000743 Type *IntPtrTy = TD->getIntPtrType(Ptr->getType());
Matt Arsenault8c789092013-08-12 23:15:58 +0000744 Type *ResultElementTy = ResultTy->getPointerElementType();
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000745
746 // If this is a constant expr gep that is effectively computing an
747 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000748 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000749 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000750
Chris Lattner5858e092011-01-06 06:19:46 +0000751 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
752 // "inttoptr (sub (ptrtoint Ptr), V)"
Matt Arsenault8c789092013-08-12 23:15:58 +0000753 if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
Chris Lattner5858e092011-01-06 06:19:46 +0000754 ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000755 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000756 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000757 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000758 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000759 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
760 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
761 Res = ConstantExpr::getIntToPtr(Res, ResultTy);
762 if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
Chad Rosierc24b86f2011-12-01 03:08:23 +0000763 Res = ConstantFoldConstantExpression(ResCE, TD, TLI);
Chris Lattner5858e092011-01-06 06:19:46 +0000764 return Res;
765 }
766 }
Craig Topper9f008862014-04-15 04:59:12 +0000767 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000768 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000769
Chris Lattner171608e2011-01-06 22:24:29 +0000770 unsigned BitWidth = TD->getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000771 APInt Offset =
772 APInt(BitWidth, TD->getIndexedOffset(Ptr->getType(),
Roman Divacky4717a8d2012-09-06 15:42:13 +0000773 makeArrayRef((Value *const*)
774 Ops.data() + 1,
Jay Foadbf904772011-07-19 14:01:37 +0000775 Ops.size() - 1)));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000776 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000777
778 // If this is a GEP of a GEP, fold it all into a single GEP.
779 while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000780 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000781
782 // Do not try the incorporate the sub-GEP if some index is not a number.
783 bool AllConstantInt = true;
784 for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
785 if (!isa<ConstantInt>(NestedOps[i])) {
786 AllConstantInt = false;
787 break;
788 }
789 if (!AllConstantInt)
790 break;
791
Dan Gohman474e488c2010-03-10 19:31:51 +0000792 Ptr = cast<Constant>(GEP->getOperand(0));
793 Offset += APInt(BitWidth,
Jay Foadbf904772011-07-19 14:01:37 +0000794 TD->getIndexedOffset(Ptr->getType(), NestedOps));
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000795 Ptr = StripPtrCastKeepAS(Ptr);
Dan Gohman474e488c2010-03-10 19:31:51 +0000796 }
797
Dan Gohman81ce8422009-08-19 18:18:36 +0000798 // If the base value for this address is a literal integer value, fold the
799 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000800 APInt BasePtr(BitWidth, 0);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000801 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
802 if (CE->getOpcode() == Instruction::IntToPtr) {
Jay Foad583abbc2010-12-07 08:25:19 +0000803 if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
804 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000805 }
806 }
807
Dan Gohmana5ca5782010-03-18 19:34:33 +0000808 if (Ptr->isNullValue() || BasePtr != 0) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000809 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Dan Gohman81ce8422009-08-19 18:18:36 +0000810 return ConstantExpr::getIntToPtr(C, ResultTy);
811 }
812
813 // Otherwise form a regular getelementptr. Recompute the indices so that
814 // we eliminate over-indexing of the notional static type array bounds.
815 // This makes it easy to determine if the getelementptr is "inbounds".
816 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Chris Lattner229907c2011-07-18 04:54:35 +0000817 Type *Ty = Ptr->getType();
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000818 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
Matt Arsenault7a960a82013-08-20 21:20:04 +0000819 SmallVector<Constant *, 32> NewIdxs;
820
Dan Gohmanc59ba422009-08-19 22:46:59 +0000821 do {
Chris Lattner229907c2011-07-18 04:54:35 +0000822 if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
Duncan Sands19d0b472010-02-16 11:11:14 +0000823 if (ATy->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000824 // The only pointer indexing we'll do is on the first index of the GEP.
825 if (!NewIdxs.empty())
826 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000827
Chris Lattner77c36d62009-12-03 01:05:45 +0000828 // Only handle pointers to sized types, not pointers to functions.
829 if (!ATy->getElementType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000830 return nullptr;
Chris Lattner77c36d62009-12-03 01:05:45 +0000831 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000832
Dan Gohman81ce8422009-08-19 18:18:36 +0000833 // Determine which element of the array the offset points into.
Dan Gohman23e62c52009-08-21 16:52:54 +0000834 APInt ElemSize(BitWidth, TD->getTypeAllocSize(ATy->getElementType()));
Dan Gohman81ce8422009-08-19 18:18:36 +0000835 if (ElemSize == 0)
Chris Lattner6ce03802010-11-21 08:39:01 +0000836 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000837 // index for this level and proceed to the next level to see if it can
838 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000839 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
840 else {
841 // The element size is non-zero divide the offset by the element
842 // size (rounding down), to compute the index at this level.
843 APInt NewIdx = Offset.udiv(ElemSize);
844 Offset -= NewIdx * ElemSize;
845 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
846 }
Dan Gohman81ce8422009-08-19 18:18:36 +0000847 Ty = ATy->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000848 } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000849 // If we end up with an offset that isn't valid for this struct type, we
850 // can't re-form this GEP in a regular form, so bail out. The pointer
851 // operand likely went through casts that are necessary to make the GEP
852 // sensible.
Dan Gohman81ce8422009-08-19 18:18:36 +0000853 const StructLayout &SL = *TD->getStructLayout(STy);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000854 if (Offset.uge(SL.getSizeInBytes()))
855 break;
856
857 // Determine which field of the struct the offset points into. The
858 // getZExtValue is fine as we've already ensured that the offset is
859 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000860 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000861 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
862 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000863 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000864 Ty = STy->getTypeAtIndex(ElIdx);
865 } else {
Dan Gohmanc59ba422009-08-19 22:46:59 +0000866 // We've reached some non-indexable type.
867 break;
Dan Gohman81ce8422009-08-19 18:18:36 +0000868 }
Matt Arsenault8c789092013-08-12 23:15:58 +0000869 } while (Ty != ResultElementTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000870
871 // If we haven't used up the entire offset by descending the static
872 // type, then the offset is pointing into the middle of an indivisible
873 // member, so we can't simplify it.
874 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000875 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000876
Dan Gohman21c62162009-09-11 00:04:14 +0000877 // Create a GEP.
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000878 Constant *C = ConstantExpr::getGetElementPtr(Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000879 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000880 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000881
Dan Gohmanc59ba422009-08-19 22:46:59 +0000882 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000883 // the type of what the original indices indexed, add a cast.
Matt Arsenault8c789092013-08-12 23:15:58 +0000884 if (Ty != ResultElementTy)
Chris Lattner9d051242009-10-25 06:08:26 +0000885 C = FoldBitCast(C, ResultTy, *TD);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000886
887 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000888}
889
Chris Lattner6a6b3fb2007-12-11 07:29:44 +0000890
Chris Lattner44d68b92007-01-31 00:51:48 +0000891
892//===----------------------------------------------------------------------===//
893// Constant Folding public APIs
894//===----------------------------------------------------------------------===//
895
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000896/// Try to constant fold the specified instruction.
Duncan Sands763dec02010-11-23 10:16:18 +0000897/// If successful, the constant result is returned, if not, null is returned.
898/// Note that this fails if not all of the operands are constant. Otherwise,
899/// this function can only fail when attempting to fold instructions like loads
900/// and stores, which have no constant expression form.
Chad Rosierc24b86f2011-12-01 03:08:23 +0000901Constant *llvm::ConstantFoldInstruction(Instruction *I,
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000902 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000903 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +0000904 // Handle PHI nodes quickly here...
Chris Lattner2ae054a2007-01-30 23:45:45 +0000905 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +0000906 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +0000907
Duncan Sands1d27f0122010-11-14 12:53:18 +0000908 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
909 Value *Incoming = PN->getIncomingValue(i);
Duncan Sands763dec02010-11-23 10:16:18 +0000910 // If the incoming value is undef then skip it. Note that while we could
911 // skip the value if it is equal to the phi node itself we choose not to
912 // because that would break the rule that constant folding only applies if
913 // all operands are constants.
914 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +0000915 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000916 // If the incoming value is not a constant, then give up.
Duncan Sands1d27f0122010-11-14 12:53:18 +0000917 Constant *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000918 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +0000919 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000920 // Fold the PHI's operands.
921 if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
922 C = ConstantFoldConstantExpression(NewC, TD, TLI);
923 // If the incoming value is a different constant to
924 // the one we saw previously, then give up.
925 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +0000926 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +0000927 CommonValue = C;
928 }
Chris Lattner2ae054a2007-01-30 23:45:45 +0000929
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000930
Duncan Sands1d27f0122010-11-14 12:53:18 +0000931 // If we reach here, all incoming values are the same constant or undef.
932 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +0000933 }
934
935 // Scan the operand list, checking to see if they are all constants, if so,
936 // hand off to ConstantFoldInstOperands.
937 SmallVector<Constant*, 8> Ops;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000938 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
939 Constant *Op = dyn_cast<Constant>(*i);
940 if (!Op)
Craig Topper9f008862014-04-15 04:59:12 +0000941 return nullptr; // All operands not constant!
Chris Lattner2ae054a2007-01-30 23:45:45 +0000942
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000943 // Fold the Instruction's operands.
944 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
945 Op = ConstantFoldConstantExpression(NewCE, TD, TLI);
946
947 Ops.push_back(Op);
948 }
949
Chris Lattnerd2265b42007-12-10 22:53:04 +0000950 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000951 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000952 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000953
Chris Lattner1664a4f2009-10-22 06:25:11 +0000954 if (const LoadInst *LI = dyn_cast<LoadInst>(I))
955 return ConstantFoldLoadInst(LI, TD);
Frits van Bommela98214d2010-11-29 20:36:52 +0000956
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000957 if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000958 return ConstantExpr::getInsertValue(
959 cast<Constant>(IVI->getAggregateOperand()),
960 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000961 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000962 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000963
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000964 if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +0000965 return ConstantExpr::getExtractValue(
966 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +0000967 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000968 }
Frits van Bommela98214d2010-11-29 20:36:52 +0000969
Chad Rosierc24b86f2011-12-01 03:08:23 +0000970 return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, TD, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +0000971}
972
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000973static Constant *
974ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout *TD,
975 const TargetLibraryInfo *TLI,
Craig Topper71b7b682014-08-21 05:55:13 +0000976 SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000977 SmallVector<Constant *, 8> Ops;
978 for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
979 ++i) {
Dan Gohman580b80d2009-11-23 16:22:21 +0000980 Constant *NewC = cast<Constant>(*i);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000981 // Recursively fold the ConstantExpr's operands. If we have already folded
982 // a ConstantExpr, we don't have to process it again.
983 if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
984 if (FoldedOps.insert(NewCE))
985 NewC = ConstantFoldConstantExpressionImpl(NewCE, TD, TLI, FoldedOps);
986 }
Dan Gohman580b80d2009-11-23 16:22:21 +0000987 Ops.push_back(NewC);
988 }
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000989
990 if (CE->isCompare())
Chris Lattnercdfb80d2009-11-09 23:06:58 +0000991 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
Chad Rosierc24b86f2011-12-01 03:08:23 +0000992 TD, TLI);
993 return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +0000994}
995
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000996/// Attempt to fold the constant expression
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +0000997/// using the specified DataLayout. If successful, the constant result is
998/// result is returned, if not, null is returned.
999Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
1000 const DataLayout *TD,
1001 const TargetLibraryInfo *TLI) {
1002 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
1003 return ConstantFoldConstantExpressionImpl(CE, TD, TLI, FoldedOps);
1004}
1005
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001006/// Attempt to constant fold an instruction with the
Chris Lattner2ae054a2007-01-30 23:45:45 +00001007/// specified opcode and operands. If successful, the constant result is
1008/// returned, if not, null is returned. Note that this function can fail when
1009/// attempting to fold instructions like loads and stores, which have no
1010/// constant expression form.
1011///
Dan Gohman580b80d2009-11-23 16:22:21 +00001012/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
1013/// information, due to only being passed an opcode and operands. Constant
1014/// folding using this function strips this information.
1015///
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001016Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
Jay Foadf4b14a22011-07-19 13:32:40 +00001017 ArrayRef<Constant *> Ops,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001018 const DataLayout *TD,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001019 const TargetLibraryInfo *TLI) {
Chris Lattner44d68b92007-01-31 00:51:48 +00001020 // Handle easy binops first.
Chris Lattnerd2265b42007-12-10 22:53:04 +00001021 if (Instruction::isBinaryOp(Opcode)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001022 if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
Chris Lattner46b5c642009-11-06 04:27:31 +00001023 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], TD))
Chris Lattner44d68b92007-01-31 00:51:48 +00001024 return C;
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001025 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001026
Owen Anderson487375e2009-07-29 18:55:55 +00001027 return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
Chris Lattner44d68b92007-01-31 00:51:48 +00001028 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001029
Chris Lattnerd2265b42007-12-10 22:53:04 +00001030 switch (Opcode) {
Craig Topper9f008862014-04-15 04:59:12 +00001031 default: return nullptr;
Chris Lattner8fb74c62010-01-02 01:22:23 +00001032 case Instruction::ICmp:
Craig Toppera2886c22012-02-07 05:05:23 +00001033 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
Chris Lattner2ae054a2007-01-30 23:45:45 +00001034 case Instruction::Call:
Jay Foadf4b14a22011-07-19 13:32:40 +00001035 if (Function *F = dyn_cast<Function>(Ops.back()))
Chris Lattner2ae054a2007-01-30 23:45:45 +00001036 if (canConstantFoldCallTo(F))
Chad Rosierc24b86f2011-12-01 03:08:23 +00001037 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
Craig Topper9f008862014-04-15 04:59:12 +00001038 return nullptr;
Chris Lattner460e34a2007-08-11 23:49:01 +00001039 case Instruction::PtrToInt:
1040 // If the input is a inttoptr, eliminate the pair. This requires knowing
1041 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
1042 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1043 if (TD && CE->getOpcode() == Instruction::IntToPtr) {
1044 Constant *Input = CE->getOperand(0);
Dan Gohman7ccc52f2009-06-15 22:12:54 +00001045 unsigned InWidth = Input->getType()->getScalarSizeInBits();
Matt Arsenaultd12e8022013-09-17 23:23:16 +00001046 unsigned PtrWidth = TD->getPointerTypeSizeInBits(CE->getType());
1047 if (PtrWidth < InWidth) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001048 Constant *Mask =
Matt Arsenaultd12e8022013-09-17 23:23:16 +00001049 ConstantInt::get(CE->getContext(),
1050 APInt::getLowBitsSet(InWidth, PtrWidth));
Owen Anderson487375e2009-07-29 18:55:55 +00001051 Input = ConstantExpr::getAnd(Input, Mask);
Nick Lewycky730d5da2008-10-24 06:14:27 +00001052 }
Chris Lattner460e34a2007-08-11 23:49:01 +00001053 // Do a zext or trunc to get to the dest size.
Owen Anderson487375e2009-07-29 18:55:55 +00001054 return ConstantExpr::getIntegerCast(Input, DestTy, false);
Chris Lattner460e34a2007-08-11 23:49:01 +00001055 }
1056 }
Owen Anderson487375e2009-07-29 18:55:55 +00001057 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner460e34a2007-08-11 23:49:01 +00001058 case Instruction::IntToPtr:
Duncan Sandsea68a6c2008-08-13 20:20:35 +00001059 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001060 // the int size is >= the ptr size and the address spaces are the same.
1061 // This requires knowing the width of a pointer, so it can't be done in
1062 // ConstantExpr::getCast.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001063 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
1064 if (TD && CE->getOpcode() == Instruction::PtrToInt) {
1065 Constant *SrcPtr = CE->getOperand(0);
1066 unsigned SrcPtrSize = TD->getPointerTypeSizeInBits(SrcPtr->getType());
1067 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1068
1069 if (MidIntSize >= SrcPtrSize) {
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001070 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1071 if (SrcAS == DestTy->getPointerAddressSpace())
Matt Arsenault7a960a82013-08-20 21:20:04 +00001072 return FoldBitCast(CE->getOperand(0), DestTy, *TD);
1073 }
1074 }
1075 }
Dan Gohman8a0eb362010-02-23 16:35:41 +00001076
Owen Anderson487375e2009-07-29 18:55:55 +00001077 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001078 case Instruction::Trunc:
1079 case Instruction::ZExt:
1080 case Instruction::SExt:
1081 case Instruction::FPTrunc:
1082 case Instruction::FPExt:
1083 case Instruction::UIToFP:
1084 case Instruction::SIToFP:
1085 case Instruction::FPToUI:
1086 case Instruction::FPToSI:
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +00001087 case Instruction::AddrSpaceCast:
Owen Anderson487375e2009-07-29 18:55:55 +00001088 return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001089 case Instruction::BitCast:
Chris Lattner6a6b3fb2007-12-11 07:29:44 +00001090 if (TD)
Chris Lattner9d051242009-10-25 06:08:26 +00001091 return FoldBitCast(Ops[0], DestTy, *TD);
Owen Anderson487375e2009-07-29 18:55:55 +00001092 return ConstantExpr::getBitCast(Ops[0], DestTy);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001093 case Instruction::Select:
Owen Anderson487375e2009-07-29 18:55:55 +00001094 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001095 case Instruction::ExtractElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001096 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001097 case Instruction::InsertElement:
Owen Anderson487375e2009-07-29 18:55:55 +00001098 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001099 case Instruction::ShuffleVector:
Owen Anderson487375e2009-07-29 18:55:55 +00001100 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001101 case Instruction::GetElementPtr:
Chad Rosierc24b86f2011-12-01 03:08:23 +00001102 if (Constant *C = CastGEPIndices(Ops, DestTy, TD, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +00001103 return C;
Chad Rosierc24b86f2011-12-01 03:08:23 +00001104 if (Constant *C = SymbolicallyEvaluateGEP(Ops, DestTy, TD, TLI))
Chris Lattner44d68b92007-01-31 00:51:48 +00001105 return C;
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001106
Jay Foaded8db7d2011-07-21 14:31:17 +00001107 return ConstantExpr::getGetElementPtr(Ops[0], Ops.slice(1));
Chris Lattner2ae054a2007-01-30 23:45:45 +00001108 }
1109}
1110
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001111/// Attempt to constant fold a compare
Chris Lattnerd2265b42007-12-10 22:53:04 +00001112/// instruction (icmp/fcmp) with the specified operands. If it fails, it
1113/// returns a constant expression of the specified operands.
Chris Lattnerd2265b42007-12-10 22:53:04 +00001114Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001115 Constant *Ops0, Constant *Ops1,
Micah Villmowcdfe20b2012-10-08 16:38:25 +00001116 const DataLayout *TD,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001117 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001118 // fold: icmp (inttoptr x), null -> icmp x, 0
1119 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001120 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001121 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1122 //
1123 // ConstantExpr::getCompare cannot do this, because it doesn't have TD
1124 // around to know if bit truncation is happening.
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001125 if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
1126 if (TD && Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001127 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001128 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001129 // Convert the integer value to the right size to ensure we get the
1130 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001131 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001132 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001133 Constant *Null = Constant::getNullValue(C->getType());
Chad Rosierc24b86f2011-12-01 03:08:23 +00001134 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001135 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001136
Chris Lattnerd2265b42007-12-10 22:53:04 +00001137 // Only do this transformation if the int is intptrty in size, otherwise
1138 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001139 if (CE0->getOpcode() == Instruction::PtrToInt) {
1140 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1141 if (CE0->getType() == IntPtrTy) {
1142 Constant *C = CE0->getOperand(0);
1143 Constant *Null = Constant::getNullValue(C->getType());
1144 return ConstantFoldCompareInstOperands(Predicate, C, Null, TD, TLI);
1145 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001146 }
1147 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001148
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001149 if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001150 if (TD && CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001151 if (CE0->getOpcode() == Instruction::IntToPtr) {
Matt Arsenault7a960a82013-08-20 21:20:04 +00001152 Type *IntPtrTy = TD->getIntPtrType(CE0->getType());
1153
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001154 // Convert the integer value to the right size to ensure we get the
1155 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001156 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001157 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001158 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001159 IntPtrTy, false);
Chad Rosierc24b86f2011-12-01 03:08:23 +00001160 return ConstantFoldCompareInstOperands(Predicate, C0, C1, TD, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001161 }
1162
Chandler Carruth7ec50852012-11-01 08:07:29 +00001163 // Only do this transformation if the int is intptrty in size, otherwise
1164 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001165 if (CE0->getOpcode() == Instruction::PtrToInt) {
1166 Type *IntPtrTy = TD->getIntPtrType(CE0->getOperand(0)->getType());
1167 if (CE0->getType() == IntPtrTy &&
1168 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
1169 return ConstantFoldCompareInstOperands(Predicate,
1170 CE0->getOperand(0),
1171 CE1->getOperand(0),
1172 TD,
1173 TLI);
1174 }
1175 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001176 }
1177 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001178
Chris Lattner8fb74c62010-01-02 01:22:23 +00001179 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1180 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1181 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1182 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001183 Constant *LHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001184 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(0), Ops1,
1185 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001186 Constant *RHS =
Chad Rosierc24b86f2011-12-01 03:08:23 +00001187 ConstantFoldCompareInstOperands(Predicate, CE0->getOperand(1), Ops1,
1188 TD, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001189 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001190 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
1191 Constant *Ops[] = { LHS, RHS };
Chad Rosierc24b86f2011-12-01 03:08:23 +00001192 return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, TD, TLI);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001193 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001194 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001195
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001196 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001197}
1198
1199
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001200/// Given a constant and a getelementptr constantexpr, return the constant value
1201/// being addressed by the constant expression, or null if something is funny
1202/// and we can't decide.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001203Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001204 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001205 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001206 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001207
1208 // Loop over all of the operands, tracking down which value we are
1209 // addressing.
1210 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1211 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001212 if (!C)
1213 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001214 }
1215 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001216}
1217
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001218/// Given a constant and getelementptr indices (with an *implied* zero pointer
1219/// index that is not in the list), return the constant value being addressed by
1220/// a virtual load, or null if something is funny and we can't decide.
Chris Lattnerf488b352012-01-24 05:43:50 +00001221Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1222 ArrayRef<Constant*> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001223 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001224 // addressing.
1225 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Chris Lattner67058832012-01-25 06:48:06 +00001226 C = C->getAggregateElement(Indices[i]);
Craig Topper9f008862014-04-15 04:59:12 +00001227 if (!C)
1228 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001229 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001230 return C;
1231}
1232
1233
1234//===----------------------------------------------------------------------===//
1235// Constant Folding for Calls
1236//
John Criswell970af112005-10-27 16:00:10 +00001237
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001238/// Return true if it's even possible to fold a call to the specified function.
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001239bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001240 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001241 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001242 case Intrinsic::minnum:
1243 case Intrinsic::maxnum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001244 case Intrinsic::log:
1245 case Intrinsic::log2:
1246 case Intrinsic::log10:
1247 case Intrinsic::exp:
1248 case Intrinsic::exp2:
1249 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001250 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001251 case Intrinsic::sqrt:
Chad Rosier0155a632011-12-03 00:00:03 +00001252 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001253 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001254 case Intrinsic::bswap:
1255 case Intrinsic::ctpop:
1256 case Intrinsic::ctlz:
1257 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001258 case Intrinsic::fma:
1259 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001260 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001261 case Intrinsic::round:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001262 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001263 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001264 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001265 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001266 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001267 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001268 case Intrinsic::convert_from_fp16:
1269 case Intrinsic::convert_to_fp16:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001270 case Intrinsic::x86_sse_cvtss2si:
1271 case Intrinsic::x86_sse_cvtss2si64:
1272 case Intrinsic::x86_sse_cvttss2si:
1273 case Intrinsic::x86_sse_cvttss2si64:
1274 case Intrinsic::x86_sse2_cvtsd2si:
1275 case Intrinsic::x86_sse2_cvtsd2si64:
1276 case Intrinsic::x86_sse2_cvttsd2si:
1277 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001278 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001279 default:
1280 return false;
1281 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001282 }
1283
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001284 if (!F->hasName())
1285 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001286 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001287
Chris Lattner785f9982007-08-08 06:55:43 +00001288 // In these cases, the check of the length is required. We don't want to
1289 // return true for a name like "cos\0blah" which strcmp would return equal to
1290 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001291 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001292 default: return false;
1293 case 'a':
Chad Rosierc0955a52013-02-20 23:57:30 +00001294 return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
Chris Lattner785f9982007-08-08 06:55:43 +00001295 case 'c':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001296 return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
Chris Lattner785f9982007-08-08 06:55:43 +00001297 case 'e':
Chris Lattner713d5232011-05-22 22:22:35 +00001298 return Name == "exp" || Name == "exp2";
Chris Lattner785f9982007-08-08 06:55:43 +00001299 case 'f':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001300 return Name == "fabs" || Name == "fmod" || Name == "floor";
Chris Lattner785f9982007-08-08 06:55:43 +00001301 case 'l':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001302 return Name == "log" || Name == "log10";
Chris Lattner785f9982007-08-08 06:55:43 +00001303 case 'p':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001304 return Name == "pow";
Chris Lattner785f9982007-08-08 06:55:43 +00001305 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001306 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
1307 Name == "sinf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001308 case 't':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001309 return Name == "tan" || Name == "tanh";
John Criswell970af112005-10-27 16:00:10 +00001310 }
1311}
1312
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001313static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001314 if (Ty->isHalfTy()) {
1315 APFloat APF(V);
1316 bool unused;
1317 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1318 return ConstantFP::get(Ty->getContext(), APF);
1319 }
Chris Lattner351534f2009-10-05 05:06:24 +00001320 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001321 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001322 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001323 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001324 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001325
1326}
1327
Alp Tokerc817d6a2014-06-09 18:28:53 +00001328namespace {
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001329/// Clear the floating-point exception state.
Alp Tokerc817d6a2014-06-09 18:28:53 +00001330static inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001331#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001332 feclearexcept(FE_ALL_EXCEPT);
1333#endif
1334 errno = 0;
1335}
1336
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001337/// Test if a floating-point exception was raised.
Alp Tokerc817d6a2014-06-09 18:28:53 +00001338static inline bool llvm_fenv_testexcept() {
1339 int errno_val = errno;
1340 if (errno_val == ERANGE || errno_val == EDOM)
1341 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001342#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001343 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1344 return true;
1345#endif
1346 return false;
1347}
1348} // End namespace
1349
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001350static Constant *ConstantFoldFP(double (*NativeFP)(double), double V,
1351 Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001352 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001353 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001354 if (llvm_fenv_testexcept()) {
1355 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001356 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001357 }
1358
1359 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001360}
1361
Dan Gohman72efc042007-07-16 15:26:22 +00001362static Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double),
Chris Lattner229907c2011-07-18 04:54:35 +00001363 double V, double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001364 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001365 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001366 if (llvm_fenv_testexcept()) {
1367 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001368 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001369 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001370
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001371 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001372}
1373
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001374/// Attempt to fold an SSE floating point to integer conversion of a constant
1375/// floating point. If roundTowardZero is false, the default IEEE rounding is
1376/// used (toward nearest, ties to even). This matches the behavior of the
1377/// non-truncating SSE instructions in the default rounding mode. The desired
1378/// integer type Ty is used to select how many bits are available for the
1379/// result. Returns null if the conversion cannot be performed, otherwise
1380/// returns the Constant value resulting from the conversion.
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001381static Constant *ConstantFoldConvertToInt(const APFloat &Val,
1382 bool roundTowardZero, Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001383 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001384 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001385 assert(ResultWidth <= 64 &&
1386 "Can only constant fold conversions to 64 and 32 bit ints");
1387
1388 uint64_t UIntVal;
1389 bool isExact = false;
1390 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1391 : APFloat::rmNearestTiesToEven;
1392 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1393 /*isSigned=*/true, mode,
1394 &isExact);
1395 if (status != APFloat::opOK && status != APFloat::opInexact)
Craig Topper9f008862014-04-15 04:59:12 +00001396 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001397 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1398}
1399
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001400static double getValueAsDouble(ConstantFP *Op) {
1401 Type *Ty = Op->getType();
1402
1403 if (Ty->isFloatTy())
1404 return Op->getValueAPF().convertToFloat();
1405
1406 if (Ty->isDoubleTy())
1407 return Op->getValueAPF().convertToDouble();
1408
1409 bool unused;
1410 APFloat APF = Op->getValueAPF();
1411 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1412 return APF.convertToDouble();
1413}
1414
Benjamin Kramer061d1472014-03-05 19:41:48 +00001415static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
1416 Type *Ty, ArrayRef<Constant *> Operands,
1417 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001418 if (Operands.size() == 1) {
John Criswell970af112005-10-27 16:00:10 +00001419 if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001420 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001421 APFloat Val(Op->getValueAPF());
1422
1423 bool lost = false;
1424 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1425
Benjamin Kramer061d1472014-03-05 19:41:48 +00001426 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001427 }
1428
Owen Andersond4ebfd82013-02-06 22:43:31 +00001429 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001430 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001431
Karthik Bhatb67688a2014-03-07 04:36:21 +00001432 if (IntrinsicID == Intrinsic::round) {
1433 APFloat V = Op->getValueAPF();
1434 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1435 return ConstantFP::get(Ty->getContext(), V);
1436 }
1437
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001438 /// We only fold functions with finite arguments. Folding NaN and inf is
1439 /// likely to be aborted with an exception anyway, and some host libms
1440 /// have known errors raising exceptions.
1441 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001442 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001443
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001444 /// Currently APFloat versions of these functions do not exist, so we use
1445 /// the host native double versions. Float versions are not called
1446 /// directly but for all these it is true (float)(f((double)arg)) ==
1447 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001448 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001449
Benjamin Kramer061d1472014-03-05 19:41:48 +00001450 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001451 default: break;
1452 case Intrinsic::fabs:
1453 return ConstantFoldFP(fabs, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001454#if HAVE_LOG2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001455 case Intrinsic::log2:
1456 return ConstantFoldFP(log2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001457#endif
1458#if HAVE_LOG
Owen Andersond4ebfd82013-02-06 22:43:31 +00001459 case Intrinsic::log:
1460 return ConstantFoldFP(log, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001461#endif
1462#if HAVE_LOG10
Owen Andersond4ebfd82013-02-06 22:43:31 +00001463 case Intrinsic::log10:
1464 return ConstantFoldFP(log10, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001465#endif
1466#if HAVE_EXP
Owen Andersond4ebfd82013-02-06 22:43:31 +00001467 case Intrinsic::exp:
1468 return ConstantFoldFP(exp, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001469#endif
1470#if HAVE_EXP2
Owen Andersond4ebfd82013-02-06 22:43:31 +00001471 case Intrinsic::exp2:
1472 return ConstantFoldFP(exp2, V, Ty);
Owen Anderson132ae8b2013-02-07 00:21:34 +00001473#endif
Owen Andersond4ebfd82013-02-06 22:43:31 +00001474 case Intrinsic::floor:
1475 return ConstantFoldFP(floor, V, Ty);
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001476 case Intrinsic::ceil:
1477 return ConstantFoldFP(ceil, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001478 }
1479
Benjamin Kramer061d1472014-03-05 19:41:48 +00001480 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001481 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001482
Daniel Dunbarca414c72009-07-26 08:34:35 +00001483 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001484 case 'a':
Chad Rosier576c0f82011-12-01 23:16:03 +00001485 if (Name == "acos" && TLI->has(LibFunc::acos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001486 return ConstantFoldFP(acos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001487 else if (Name == "asin" && TLI->has(LibFunc::asin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001488 return ConstantFoldFP(asin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001489 else if (Name == "atan" && TLI->has(LibFunc::atan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001490 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001491 break;
1492 case 'c':
Chad Rosier576c0f82011-12-01 23:16:03 +00001493 if (Name == "ceil" && TLI->has(LibFunc::ceil))
Chris Lattner46b5c642009-11-06 04:27:31 +00001494 return ConstantFoldFP(ceil, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001495 else if (Name == "cos" && TLI->has(LibFunc::cos))
Chris Lattner46b5c642009-11-06 04:27:31 +00001496 return ConstantFoldFP(cos, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001497 else if (Name == "cosh" && TLI->has(LibFunc::cosh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001498 return ConstantFoldFP(cosh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001499 else if (Name == "cosf" && TLI->has(LibFunc::cosf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001500 return ConstantFoldFP(cos, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001501 break;
1502 case 'e':
Chad Rosier576c0f82011-12-01 23:16:03 +00001503 if (Name == "exp" && TLI->has(LibFunc::exp))
Chris Lattner46b5c642009-11-06 04:27:31 +00001504 return ConstantFoldFP(exp, V, Ty);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001505
Chad Rosier576c0f82011-12-01 23:16:03 +00001506 if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
Chris Lattner713d5232011-05-22 22:22:35 +00001507 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1508 // C99 library.
1509 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
1510 }
Chris Lattner785f9982007-08-08 06:55:43 +00001511 break;
1512 case 'f':
Chad Rosier576c0f82011-12-01 23:16:03 +00001513 if (Name == "fabs" && TLI->has(LibFunc::fabs))
Chris Lattner46b5c642009-11-06 04:27:31 +00001514 return ConstantFoldFP(fabs, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001515 else if (Name == "floor" && TLI->has(LibFunc::floor))
Chris Lattner46b5c642009-11-06 04:27:31 +00001516 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001517 break;
1518 case 'l':
Chad Rosier576c0f82011-12-01 23:16:03 +00001519 if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
Chris Lattner46b5c642009-11-06 04:27:31 +00001520 return ConstantFoldFP(log, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001521 else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
Chris Lattner46b5c642009-11-06 04:27:31 +00001522 return ConstantFoldFP(log10, V, Ty);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001523 else if (IntrinsicID == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001524 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001525 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001526 return ConstantFoldFP(sqrt, V, Ty);
Sanjay Patel7b2cd9a2014-10-01 20:36:33 +00001527 else {
1528 // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1529 // all guarantee or favor returning NaN - the square root of a
1530 // negative number is not defined for the LLVM sqrt intrinsic.
1531 // This is because the intrinsic should only be emitted in place of
1532 // libm's sqrt function when using "no-nans-fp-math".
1533 return UndefValue::get(Ty);
1534 }
Chris Lattner785f9982007-08-08 06:55:43 +00001535 }
1536 break;
1537 case 's':
Chad Rosier576c0f82011-12-01 23:16:03 +00001538 if (Name == "sin" && TLI->has(LibFunc::sin))
Chris Lattner46b5c642009-11-06 04:27:31 +00001539 return ConstantFoldFP(sin, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001540 else if (Name == "sinh" && TLI->has(LibFunc::sinh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001541 return ConstantFoldFP(sinh, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001542 else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
Chris Lattner46b5c642009-11-06 04:27:31 +00001543 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001544 else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001545 return ConstantFoldFP(sqrt, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001546 else if (Name == "sinf" && TLI->has(LibFunc::sinf))
Chris Lattner46b5c642009-11-06 04:27:31 +00001547 return ConstantFoldFP(sin, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001548 break;
1549 case 't':
Chad Rosier576c0f82011-12-01 23:16:03 +00001550 if (Name == "tan" && TLI->has(LibFunc::tan))
Chris Lattner46b5c642009-11-06 04:27:31 +00001551 return ConstantFoldFP(tan, V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001552 else if (Name == "tanh" && TLI->has(LibFunc::tanh))
Chris Lattner46b5c642009-11-06 04:27:31 +00001553 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001554 break;
1555 default:
1556 break;
John Criswell970af112005-10-27 16:00:10 +00001557 }
Craig Topper9f008862014-04-15 04:59:12 +00001558 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001559 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001560
Chris Lattner9ca7c092009-10-05 05:00:35 +00001561 if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001562 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001563 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001564 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001565 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001566 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001567 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001568 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001569
1570 bool lost = false;
1571 APFloat::opStatus status =
1572 Val.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven, &lost);
1573
1574 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001575 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001576 assert(status == APFloat::opOK && !lost &&
1577 "Precision lost during fp16 constfolding");
1578
Benjamin Kramer061d1472014-03-05 19:41:48 +00001579 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001580 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001581 default:
Craig Topper9f008862014-04-15 04:59:12 +00001582 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001583 }
John Criswell970af112005-10-27 16:00:10 +00001584 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001585
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001586 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001587 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001588 isa<ConstantDataVector>(Operands[0])) {
1589 Constant *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001590 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001591 default: break;
1592 case Intrinsic::x86_sse_cvtss2si:
1593 case Intrinsic::x86_sse_cvtss2si64:
1594 case Intrinsic::x86_sse2_cvtsd2si:
1595 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001596 if (ConstantFP *FPOp =
1597 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1598 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1599 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001600 case Intrinsic::x86_sse_cvttss2si:
1601 case Intrinsic::x86_sse_cvttss2si64:
1602 case Intrinsic::x86_sse2_cvttsd2si:
1603 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001604 if (ConstantFP *FPOp =
1605 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001606 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001607 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001608 }
1609 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001610
Dan Gohmancf39be32010-02-17 00:54:58 +00001611 if (isa<UndefValue>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001612 if (IntrinsicID == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001613 return Operands[0];
Craig Topper9f008862014-04-15 04:59:12 +00001614 return nullptr;
Dan Gohmancf39be32010-02-17 00:54:58 +00001615 }
1616
Craig Topper9f008862014-04-15 04:59:12 +00001617 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001618 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001619
Jay Foadf4b14a22011-07-19 13:32:40 +00001620 if (Operands.size() == 2) {
John Criswell970af112005-10-27 16:00:10 +00001621 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001622 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001623 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001624 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001625
John Criswell970af112005-10-27 16:00:10 +00001626 if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001627 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001628 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001629
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001630 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001631 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001632 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1633 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001634 if (IntrinsicID == Intrinsic::copysign) {
1635 APFloat V1 = Op1->getValueAPF();
1636 APFloat V2 = Op2->getValueAPF();
1637 V1.copySign(V2);
1638 return ConstantFP::get(Ty->getContext(), V1);
1639 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001640
1641 if (IntrinsicID == Intrinsic::minnum) {
1642 const APFloat &C1 = Op1->getValueAPF();
1643 const APFloat &C2 = Op2->getValueAPF();
1644 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1645 }
1646
1647 if (IntrinsicID == Intrinsic::maxnum) {
1648 const APFloat &C1 = Op1->getValueAPF();
1649 const APFloat &C2 = Op2->getValueAPF();
1650 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1651 }
1652
Chad Rosier0155a632011-12-03 00:00:03 +00001653 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001654 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001655 if (Name == "pow" && TLI->has(LibFunc::pow))
Chris Lattner46b5c642009-11-06 04:27:31 +00001656 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001657 if (Name == "fmod" && TLI->has(LibFunc::fmod))
Chris Lattner46b5c642009-11-06 04:27:31 +00001658 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Chad Rosier576c0f82011-12-01 23:16:03 +00001659 if (Name == "atan2" && TLI->has(LibFunc::atan2))
Chris Lattner46b5c642009-11-06 04:27:31 +00001660 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
Chris Lattner26933dd2007-01-15 06:27:37 +00001661 } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001662 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1663 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001664 APFloat((float)std::pow((float)Op1V,
1665 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001666 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1667 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001668 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001669 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001670 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1671 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001672 APFloat((double)std::pow((double)Op1V,
1673 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001674 }
Craig Topper9f008862014-04-15 04:59:12 +00001675 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001676 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001677
Chris Lattner59d93982009-10-05 05:26:04 +00001678 if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1679 if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001680 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001681 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001682 case Intrinsic::sadd_with_overflow:
1683 case Intrinsic::uadd_with_overflow:
1684 case Intrinsic::ssub_with_overflow:
1685 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001686 case Intrinsic::smul_with_overflow:
1687 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001688 APInt Res;
1689 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001690 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001691 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001692 case Intrinsic::sadd_with_overflow:
1693 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1694 break;
1695 case Intrinsic::uadd_with_overflow:
1696 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1697 break;
1698 case Intrinsic::ssub_with_overflow:
1699 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1700 break;
1701 case Intrinsic::usub_with_overflow:
1702 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1703 break;
1704 case Intrinsic::smul_with_overflow:
1705 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1706 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001707 case Intrinsic::umul_with_overflow:
1708 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1709 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001710 }
Chris Lattner59d93982009-10-05 05:26:04 +00001711 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001712 ConstantInt::get(Ty->getContext(), Res),
1713 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001714 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001715 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001716 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001717 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001718 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1719 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001720 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1721 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001722 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1723 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001724 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001725 }
1726 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001727
Craig Topper9f008862014-04-15 04:59:12 +00001728 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001729 }
Craig Topper9f008862014-04-15 04:59:12 +00001730 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001731 }
Matt Arsenault83778582014-03-05 00:02:00 +00001732
1733 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001734 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001735
1736 if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1737 if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1738 if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001739 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001740 default: break;
1741 case Intrinsic::fma:
1742 case Intrinsic::fmuladd: {
1743 APFloat V = Op1->getValueAPF();
1744 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1745 Op3->getValueAPF(),
1746 APFloat::rmNearestTiesToEven);
1747 if (s != APFloat::opInvalidOp)
1748 return ConstantFP::get(Ty->getContext(), V);
1749
Craig Topper9f008862014-04-15 04:59:12 +00001750 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001751 }
1752 }
1753 }
1754 }
1755 }
1756
Craig Topper9f008862014-04-15 04:59:12 +00001757 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001758}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001759
1760static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1761 VectorType *VTy,
1762 ArrayRef<Constant *> Operands,
1763 const TargetLibraryInfo *TLI) {
1764 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1765 SmallVector<Constant *, 4> Lane(Operands.size());
1766 Type *Ty = VTy->getElementType();
1767
1768 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1769 // Gather a column of constants.
1770 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1771 Constant *Agg = Operands[J]->getAggregateElement(I);
1772 if (!Agg)
1773 return nullptr;
1774
1775 Lane[J] = Agg;
1776 }
1777
1778 // Use the regular scalar folding to simplify this column.
1779 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1780 if (!Folded)
1781 return nullptr;
1782 Result[I] = Folded;
1783 }
1784
1785 return ConstantVector::get(Result);
1786}
1787
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001788/// Attempt to constant fold a call to the specified function
Benjamin Kramer061d1472014-03-05 19:41:48 +00001789/// with the specified arguments, returning null if unsuccessful.
1790Constant *
1791llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1792 const TargetLibraryInfo *TLI) {
1793 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00001794 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001795 StringRef Name = F->getName();
1796
1797 Type *Ty = F->getReturnType();
1798
1799 if (VectorType *VTy = dyn_cast<VectorType>(Ty))
1800 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1801
1802 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1803}