blob: ec442cedac06ccdcf834cd2026fc16c367b4e7aa [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"
Eugene Zelenko1804a772016-08-25 00:45:04 +000020#include "llvm/ADT/APFloat.h"
21#include "llvm/ADT/APInt.h"
22#include "llvm/ADT/ArrayRef.h"
23#include "llvm/ADT/DenseMap.h"
David Majnemere61e4bf2016-06-21 05:10:24 +000024#include "llvm/ADT/STLExtras.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000025#include "llvm/ADT/StringRef.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000026#include "llvm/ADT/SmallVector.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000027#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000028#include "llvm/Analysis/ValueTracking.h"
Alp Tokerc817d6a2014-06-09 18:28:53 +000029#include "llvm/Config/config.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000030#include "llvm/IR/Constant.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000031#include "llvm/IR/Constants.h"
32#include "llvm/IR/DataLayout.h"
33#include "llvm/IR/DerivedTypes.h"
34#include "llvm/IR/Function.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000035#include "llvm/IR/GlobalValue.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000036#include "llvm/IR/GlobalVariable.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000037#include "llvm/IR/InstrTypes.h"
38#include "llvm/IR/Instruction.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000039#include "llvm/IR/Instructions.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000040#include "llvm/IR/Operator.h"
Eugene Zelenko1804a772016-08-25 00:45:04 +000041#include "llvm/IR/Type.h"
42#include "llvm/IR/Value.h"
43#include "llvm/Support/Casting.h"
Torok Edwin56d06592009-07-11 20:10:48 +000044#include "llvm/Support/ErrorHandling.h"
John Criswell970af112005-10-27 16:00:10 +000045#include "llvm/Support/MathExtras.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000046#include <cassert>
John Criswell970af112005-10-27 16:00:10 +000047#include <cerrno>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000048#include <cfenv>
Jeff Cohencc08c832006-12-02 02:22:01 +000049#include <cmath>
Eugene Zelenko1804a772016-08-25 00:45:04 +000050#include <cstddef>
51#include <cstdint>
Alp Tokerc817d6a2014-06-09 18:28:53 +000052
John Criswell970af112005-10-27 16:00:10 +000053using namespace llvm;
54
Eugene Zelenko35623fb2016-03-28 17:40:08 +000055namespace {
56
Chris Lattner44d68b92007-01-31 00:51:48 +000057//===----------------------------------------------------------------------===//
58// Constant Folding internal helper functions
59//===----------------------------------------------------------------------===//
60
Sanjay Patel0d7dee62014-10-02 15:13:22 +000061/// Constant fold bitcast, symbolically evaluating it with DataLayout.
62/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000063/// ConstantExpr if unfoldable.
Eugene Zelenko35623fb2016-03-28 17:40:08 +000064Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000065 // Catch the obvious splat cases.
66 if (C->isNullValue() && !DestTy->isX86_MMXTy())
67 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000068 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
69 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +000070 return Constant::getAllOnesValue(DestTy);
71
Rafael Espindolabb893fe2012-01-27 23:33:07 +000072 // Handle a vector->integer cast.
David Majnemer90a97042016-07-13 04:22:12 +000073 if (auto *IT = dyn_cast<IntegerType>(DestTy)) {
74 auto *VTy = dyn_cast<VectorType>(C->getType());
Craig Topper9f008862014-04-15 04:59:12 +000075 if (!VTy)
Rafael Espindolabb893fe2012-01-27 23:33:07 +000076 return ConstantExpr::getBitCast(C, DestTy);
77
Michael Ilsemana7b93c12013-02-26 22:51:07 +000078 unsigned NumSrcElts = VTy->getNumElements();
79 Type *SrcEltTy = VTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +000080
Rafael Espindolabb893fe2012-01-27 23:33:07 +000081 // If the vector is a vector of floating point, convert it to vector of int
82 // to simplify things.
Chris Lattner8213c8a2012-02-06 21:56:39 +000083 if (SrcEltTy->isFloatingPointTy()) {
84 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Rafael Espindolabb893fe2012-01-27 23:33:07 +000085 Type *SrcIVTy =
86 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
Chandler Carruthef860a22013-01-02 09:10:48 +000087 // Ask IR to do the conversion now that #elts line up.
Rafael Espindolabb893fe2012-01-27 23:33:07 +000088 C = ConstantExpr::getBitCast(C, SrcIVTy);
89 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000090
Rafael Espindolabb893fe2012-01-27 23:33:07 +000091 // Now that we know that the input value is a vector of integers, just shift
92 // and insert them into our result.
Igor Breger73578492016-06-27 06:42:54 +000093 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000094 APInt Result(IT->getBitWidth(), 0);
95 for (unsigned i = 0; i != NumSrcElts; ++i) {
David Majnemer3918cdd2016-05-04 06:13:33 +000096 Constant *Element;
Mehdi Aminia28d91d2015-03-10 02:37:25 +000097 if (DL.isLittleEndian())
David Majnemer3918cdd2016-05-04 06:13:33 +000098 Element = C->getAggregateElement(NumSrcElts-i-1);
Chris Lattner8213c8a2012-02-06 21:56:39 +000099 else
David Majnemer3918cdd2016-05-04 06:13:33 +0000100 Element = C->getAggregateElement(i);
101
David Majnemere4218cf2016-07-29 04:06:09 +0000102 if (Element && isa<UndefValue>(Element)) {
103 Result <<= BitShift;
104 continue;
105 }
106
David Majnemer3918cdd2016-05-04 06:13:33 +0000107 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
108 if (!ElementCI)
109 return ConstantExpr::getBitCast(C, DestTy);
110
111 Result <<= BitShift;
112 Result |= ElementCI->getValue().zextOrSelf(IT->getBitWidth());
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000113 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000114
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000115 return ConstantInt::get(IT, Result);
116 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000117
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000118 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000119 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000120 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000121 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000122
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000123 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
124 // vector so the code below can handle it uniformly.
125 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
126 Constant *Ops = C; // don't take the address of C!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000127 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000128 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000129
Chris Lattner9d051242009-10-25 06:08:26 +0000130 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000131 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000132 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000133
Chandler Carruthef860a22013-01-02 09:10:48 +0000134 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000135 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000136 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000137 if (NumDstElt == NumSrcElt)
138 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000139
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000140 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000141 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000142
143 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000144 // requires endianness information to do the right thing. For example,
145 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
146 // folds to (little endian):
147 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
148 // and to (big endian):
149 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000150
Chris Lattner9d051242009-10-25 06:08:26 +0000151 // First thing is first. We only want to think about integer here, so if
152 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000153 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000154 // Fold to an vector of integers with same size as our FP type.
155 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000156 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000157 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
158 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000159 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000160
Chandler Carruthef860a22013-01-02 09:10:48 +0000161 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000162 return ConstantExpr::getBitCast(C, DestTy);
163 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000164
Chris Lattner9d051242009-10-25 06:08:26 +0000165 // Okay, we know the destination is integer, if the input is FP, convert
166 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000167 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000168 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000169 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000170 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000171 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000172 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000173 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000174 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
175 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000176 return C;
177 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000178
Chris Lattner9d051242009-10-25 06:08:26 +0000179 // Now we know that the input and output vectors are both integer vectors
180 // of the same size, and that their #elements is not the same. Do the
181 // conversion here, which depends on whether the input or output has
182 // more elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000183 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000184
Chris Lattner9d051242009-10-25 06:08:26 +0000185 SmallVector<Constant*, 32> Result;
186 if (NumDstElt < NumSrcElt) {
187 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
188 Constant *Zero = Constant::getNullValue(DstEltTy);
189 unsigned Ratio = NumSrcElt/NumDstElt;
190 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
191 unsigned SrcElt = 0;
192 for (unsigned i = 0; i != NumDstElt; ++i) {
193 // Build each element of the result.
194 Constant *Elt = Zero;
195 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
196 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemere4218cf2016-07-29 04:06:09 +0000197 Constant *Src = C->getAggregateElement(SrcElt++);
198 if (Src && isa<UndefValue>(Src))
David Majnemer718da3d2016-07-29 18:48:27 +0000199 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemere4218cf2016-07-29 04:06:09 +0000200 else
201 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner9d051242009-10-25 06:08:26 +0000202 if (!Src) // Reject constantexpr elements.
203 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000204
Chris Lattner9d051242009-10-25 06:08:26 +0000205 // Zero extend the element to the right size.
206 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000207
Chris Lattner9d051242009-10-25 06:08:26 +0000208 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000209 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000210 ConstantInt::get(Src->getType(), ShiftAmt));
211 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000212
Chris Lattner9d051242009-10-25 06:08:26 +0000213 // Mix it in.
214 Elt = ConstantExpr::getOr(Elt, Src);
215 }
216 Result.push_back(Elt);
217 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000218 return ConstantVector::get(Result);
219 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000220
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000221 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
222 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000223 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000224
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000225 // Loop over each source value, expanding into multiple results.
226 for (unsigned i = 0; i != NumSrcElt; ++i) {
Andrea Di Biagio7277afe2016-09-13 14:50:47 +0000227 auto *Element = C->getAggregateElement(i);
228
229 if (!Element) // Reject constantexpr elements.
230 return ConstantExpr::getBitCast(C, DestTy);
231
232 if (isa<UndefValue>(Element)) {
233 // Correctly Propagate undef values.
234 Result.append(Ratio, UndefValue::get(DstEltTy));
235 continue;
236 }
237
238 auto *Src = dyn_cast<ConstantInt>(Element);
239 if (!Src)
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000240 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000241
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000242 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
243 for (unsigned j = 0; j != Ratio; ++j) {
244 // Shift the piece of the value into the right place, depending on
245 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000246 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000247 ConstantInt::get(Src->getType(), ShiftAmt));
248 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000249
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000250 // Truncate the element to an integer with the same pointer size and
251 // convert the element back to a pointer using a inttoptr.
252 if (DstEltTy->isPointerTy()) {
253 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
254 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
255 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
256 continue;
257 }
258
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000259 // Truncate and remember this piece.
260 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000261 }
262 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000263
Chris Lattner69229312011-02-15 00:14:00 +0000264 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000265}
266
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000267} // end anonymous namespace
268
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000269/// If this constant is a constant offset from a global, return the global and
270/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000271bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
272 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000273 // Trivial case, constant is the global.
274 if ((GV = dyn_cast<GlobalValue>(C))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000275 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000276 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000277 return true;
278 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000279
Chris Lattner44d68b92007-01-31 00:51:48 +0000280 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000281 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000282 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000283
Chris Lattner44d68b92007-01-31 00:51:48 +0000284 // Look through ptr->int and ptr->ptr casts.
285 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000286 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000287 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000288
289 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000290 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000291 if (!GEP)
292 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000293
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000294 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000295 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000296
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000297 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000298 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000299 return false;
300
301 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000302 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000303 return false;
304
305 Offset = TmpOffset;
306 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000307}
308
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000309namespace {
310
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000311/// Recursive helper to read bits out of global. C is the constant being copied
312/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
313/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000314/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000315bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
316 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000317 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000318 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000319
Chris Lattner3db7bd22009-10-24 05:27:19 +0000320 // If this element is zero or undefined, we can just return since *CurPtr is
321 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000322 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
323 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000324
David Majnemer90a97042016-07-13 04:22:12 +0000325 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000326 if (CI->getBitWidth() > 64 ||
327 (CI->getBitWidth() & 7) != 0)
328 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000329
Chris Lattnered00b802009-10-23 06:23:49 +0000330 uint64_t Val = CI->getZExtValue();
331 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000332
Chris Lattnered00b802009-10-23 06:23:49 +0000333 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000334 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000335 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000336 n = IntBytes - n - 1;
337 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000338 ++ByteOffset;
339 }
340 return true;
341 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000342
David Majnemer90a97042016-07-13 04:22:12 +0000343 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000344 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000345 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
346 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000347 }
348 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000349 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
350 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000351 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000352 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
354 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000355 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000356 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000357 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000358
David Majnemer90a97042016-07-13 04:22:12 +0000359 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000360 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000361 unsigned Index = SL->getElementContainingOffset(ByteOffset);
362 uint64_t CurEltOffset = SL->getElementOffset(Index);
363 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000364
Eugene Zelenko1804a772016-08-25 00:45:04 +0000365 while (true) {
Chris Lattnered00b802009-10-23 06:23:49 +0000366 // If the element access is to the element itself and not to tail padding,
367 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000368 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000369
370 if (ByteOffset < EltSize &&
371 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000372 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000373 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000374
Chris Lattnered00b802009-10-23 06:23:49 +0000375 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000376
Chris Lattnered00b802009-10-23 06:23:49 +0000377 // Check to see if we read from the last struct element, if so we're done.
378 if (Index == CS->getType()->getNumElements())
379 return true;
380
381 // If we read all of the bytes we needed from this element we're done.
382 uint64_t NextEltOffset = SL->getElementOffset(Index);
383
Matt Arsenault8c789092013-08-12 23:15:58 +0000384 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000385 return true;
386
387 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000388 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
389 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000390 ByteOffset = 0;
391 CurEltOffset = NextEltOffset;
392 }
393 // not reached.
394 }
395
Chris Lattner67058832012-01-25 06:48:06 +0000396 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
397 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000398 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000399 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000400 uint64_t Index = ByteOffset / EltSize;
401 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000402 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000403 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000404 NumElts = AT->getNumElements();
405 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000406 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000407
Chris Lattner67058832012-01-25 06:48:06 +0000408 for (; Index != NumElts; ++Index) {
409 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000410 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000411 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000412
413 uint64_t BytesWritten = EltSize - Offset;
414 assert(BytesWritten <= EltSize && "Not indexing into this element?");
415 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000416 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000417
Chris Lattner67058832012-01-25 06:48:06 +0000418 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000419 BytesLeft -= BytesWritten;
420 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000421 }
422 return true;
423 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000424
David Majnemer90a97042016-07-13 04:22:12 +0000425 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000426 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000427 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000428 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000429 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000430 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000431 }
432
Chris Lattnered00b802009-10-23 06:23:49 +0000433 // Otherwise, unknown initializer type.
434 return false;
435}
436
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000437Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
438 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000439 auto *PTy = cast<PointerType>(C->getType());
440 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000441
Chris Lattnered00b802009-10-23 06:23:49 +0000442 // If this isn't an integer load we can't fold it directly.
443 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000444 unsigned AS = PTy->getAddressSpace();
445
Chris Lattnered00b802009-10-23 06:23:49 +0000446 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000447 // and then bitcast the result. This can be useful for union cases. Note
448 // that address spaces don't matter here since we're not going to result in
449 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000450 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000451 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000452 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000453 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000454 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000455 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000456 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000457 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000458 MapTy = PointerType::getIntNTy(C->getContext(),
459 DL.getTypeAllocSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000460 } else
Craig Topper9f008862014-04-15 04:59:12 +0000461 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000462
Eduard Burtescu14239212016-01-22 01:17:26 +0000463 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
464 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000465 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000466 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000467 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000468
Chris Lattnered00b802009-10-23 06:23:49 +0000469 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000470 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000471 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000472
Chris Lattnered00b802009-10-23 06:23:49 +0000473 GlobalValue *GVal;
David Majnemerf89660a2016-07-13 23:33:07 +0000474 APInt OffsetAI;
475 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000476 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000477
David Majnemer90a97042016-07-13 04:22:12 +0000478 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000479 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000480 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000481 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000482
David Majnemerf89660a2016-07-13 23:33:07 +0000483 int64_t Offset = OffsetAI.getSExtValue();
484 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000485
Chris Lattnered00b802009-10-23 06:23:49 +0000486 // If we're not accessing anything in this constant, the result is undefined.
David Majnemerf89660a2016-07-13 23:33:07 +0000487 if (Offset + BytesLoaded <= 0)
488 return UndefValue::get(IntType);
489
490 // If we're not accessing anything in this constant, the result is undefined.
491 if (Offset >= InitializerSize)
Chris Lattnered00b802009-10-23 06:23:49 +0000492 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000493
Chris Lattner59f94c02009-10-23 06:50:36 +0000494 unsigned char RawBytes[32] = {0};
David Majnemerf89660a2016-07-13 23:33:07 +0000495 unsigned char *CurPtr = RawBytes;
496 unsigned BytesLeft = BytesLoaded;
497
498 // If we're loading off the beginning of the global, some bytes may be valid.
499 if (Offset < 0) {
500 CurPtr += -Offset;
501 BytesLeft += Offset;
502 Offset = 0;
503 }
504
505 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000506 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000507
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000508 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000509 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000510 ResultVal = RawBytes[BytesLoaded - 1];
511 for (unsigned i = 1; i != BytesLoaded; ++i) {
512 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000513 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000514 }
515 } else {
516 ResultVal = RawBytes[0];
517 for (unsigned i = 1; i != BytesLoaded; ++i) {
518 ResultVal <<= 8;
519 ResultVal |= RawBytes[i];
520 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000521 }
Chris Lattnered00b802009-10-23 06:23:49 +0000522
Chris Lattner59f94c02009-10-23 06:50:36 +0000523 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000524}
525
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000526Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
527 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000528 auto *SrcPtr = CE->getOperand(0);
529 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
530 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000531 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000532 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000533
Eduard Burtescu14239212016-01-22 01:17:26 +0000534 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000535 if (!C)
536 return nullptr;
537
538 do {
539 Type *SrcTy = C->getType();
540
541 // If the type sizes are the same and a cast is legal, just directly
542 // cast the constant.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000543 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
Chandler Carrutha0e56952014-05-15 09:56:28 +0000544 Instruction::CastOps Cast = Instruction::BitCast;
545 // If we are going from a pointer to int or vice versa, we spell the cast
546 // differently.
547 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
548 Cast = Instruction::IntToPtr;
549 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
550 Cast = Instruction::PtrToInt;
551
552 if (CastInst::castIsValid(Cast, C, DestTy))
553 return ConstantExpr::getCast(Cast, C, DestTy);
554 }
555
556 // If this isn't an aggregate type, there is nothing we can do to drill down
557 // and find a bitcastable constant.
558 if (!SrcTy->isAggregateType())
559 return nullptr;
560
561 // We're simulating a load through a pointer that was bitcast to point to
562 // a different type, so we can try to walk down through the initial
563 // elements of an aggregate to see if some part of th e aggregate is
564 // castable to implement the "load" semantic model.
565 C = C->getAggregateElement(0u);
566 } while (C);
567
568 return nullptr;
569}
570
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000571} // end anonymous namespace
572
Eduard Burtescu14239212016-01-22 01:17:26 +0000573Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000574 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000575 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000576 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000577 if (GV->isConstant() && GV->hasDefinitiveInitializer())
578 return GV->getInitializer();
579
David Majnemered9abe12015-07-22 22:29:30 +0000580 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000581 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000582 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000583
Chris Lattnercf7e8942009-10-22 06:44:07 +0000584 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000585 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000586 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000587 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000588
Chris Lattnercf7e8942009-10-22 06:44:07 +0000589 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000590 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000591 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000592 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000593 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
594 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000595 }
596 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000597 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000598
Chandler Carrutha0e56952014-05-15 09:56:28 +0000599 if (CE->getOpcode() == Instruction::BitCast)
Eduard Burtescu14239212016-01-22 01:17:26 +0000600 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000601 return LoadedC;
602
Chris Lattnercf7e8942009-10-22 06:44:07 +0000603 // Instead of loading constant c string, use corresponding integer value
604 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000605 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000606 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000607 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000608 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000609 // Replace load with immediate integer if the result is an integer or fp
610 // value.
611 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000612 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000613 APInt StrVal(NumBits, 0);
614 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000615 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000616 for (unsigned char C : reverse(Str.bytes())) {
617 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000618 StrVal = (StrVal << 8) | SingleChar;
619 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000620 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000621 for (unsigned char C : Str.bytes()) {
622 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000623 StrVal = (StrVal << 8) | SingleChar;
624 }
625 // Append NULL at the end.
626 SingleChar = 0;
627 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000628 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000629
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000630 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
631 if (Ty->isFloatingPointTy())
632 Res = ConstantExpr::getBitCast(Res, Ty);
633 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000634 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000635 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000636
Chris Lattnercf7e8942009-10-22 06:44:07 +0000637 // If this load comes from anywhere in a constant global, and if the global
638 // is all undef or zero, we know what it loads.
David Majnemer90a97042016-07-13 04:22:12 +0000639 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000640 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000641 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000642 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000643 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000644 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000645 }
646 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000647
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000648 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000649 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000650}
651
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000652namespace {
653
654Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000655 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000656
David Majnemer90a97042016-07-13 04:22:12 +0000657 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000658 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000659
Craig Topper9f008862014-04-15 04:59:12 +0000660 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000661}
Chris Lattner44d68b92007-01-31 00:51:48 +0000662
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000663/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000664/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000665/// these together. If target data info is available, it is provided as DL,
666/// otherwise DL is null.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000667Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
668 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000669 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000670
Chris Lattner44d68b92007-01-31 00:51:48 +0000671 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
672 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
673 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000674
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000675 if (Opc == Instruction::And) {
676 unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000677 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
678 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000679 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
680 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
Nick Lewycky06417742013-02-14 03:23:37 +0000681 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
682 // All the bits of Op0 that the 'and' could be masking are already zero.
683 return Op0;
684 }
685 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
686 // All the bits of Op1 that the 'and' could be masking are already zero.
687 return Op1;
688 }
689
690 APInt KnownZero = KnownZero0 | KnownZero1;
691 APInt KnownOne = KnownOne0 & KnownOne1;
692 if ((KnownZero | KnownOne).isAllOnesValue()) {
693 return ConstantInt::get(Op0->getType(), KnownOne);
694 }
695 }
696
Chris Lattner44d68b92007-01-31 00:51:48 +0000697 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
698 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000699 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000700 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000701 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000702
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000703 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
704 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
705 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000706
Chris Lattner44d68b92007-01-31 00:51:48 +0000707 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000708 // PtrToInt may change the bitwidth so we have convert to the right size
709 // first.
710 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
711 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000712 }
713 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000714
Craig Topper9f008862014-04-15 04:59:12 +0000715 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000716}
717
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000718/// If array indices are not pointer-sized integers, explicitly cast them so
719/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000720Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
721 Type *ResultTy, const DataLayout &DL,
722 const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000723 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000724
725 bool Any = false;
726 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000727 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000728 if ((i == 1 ||
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000729 !isa<StructType>(GetElementPtrInst::getIndexedType(SrcElemTy,
David Blaikied288fb82015-03-30 21:41:43 +0000730 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000731 Ops[i]->getType() != IntPtrTy) {
732 Any = true;
733 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
734 true,
735 IntPtrTy,
736 true),
737 Ops[i], IntPtrTy));
738 } else
739 NewIdxs.push_back(Ops[i]);
740 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000741
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000742 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000743 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000744
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000745 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], NewIdxs);
David Majnemerd536f232016-07-29 03:27:26 +0000746 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
747 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000748
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000749 return C;
750}
751
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000752/// Strip the pointer casts, but preserve the address space information.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000753Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000754 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000755 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000756 Ptr = Ptr->stripPointerCasts();
David Majnemer90a97042016-07-13 04:22:12 +0000757 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000758
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000759 ElemTy = NewPtrTy->getPointerElementType();
760
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000761 // Preserve the address space number of the pointer.
762 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000763 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000764 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000765 }
766 return Ptr;
767}
768
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000769/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000770Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
771 ArrayRef<Constant *> Ops,
772 const DataLayout &DL,
773 const TargetLibraryInfo *TLI) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000774 Type *SrcElemTy = GEP->getSourceElementType();
775 Type *ResElemTy = GEP->getResultElementType();
776 Type *ResTy = GEP->getType();
777 if (!SrcElemTy->isSized())
778 return nullptr;
779
780 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, DL, TLI))
781 return C;
782
Chris Lattner44d68b92007-01-31 00:51:48 +0000783 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000784 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000785 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000786
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000787 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000788
789 // If this is a constant expr gep that is effectively computing an
790 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000791 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000792 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000793
Chris Lattner5858e092011-01-06 06:19:46 +0000794 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
795 // "inttoptr (sub (ptrtoint Ptr), V)"
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000796 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
David Majnemer90a97042016-07-13 04:22:12 +0000797 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000798 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000799 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000800 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000801 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000802 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
803 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000804 Res = ConstantExpr::getIntToPtr(Res, ResTy);
David Majnemerd536f232016-07-29 03:27:26 +0000805 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
806 Res = FoldedRes;
Chris Lattner5858e092011-01-06 06:19:46 +0000807 return Res;
808 }
809 }
Craig Topper9f008862014-04-15 04:59:12 +0000810 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000811 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000812
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000813 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000814 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000815 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000816 DL.getIndexedOffsetInType(
817 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000818 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000819 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000820
821 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000822 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000823 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000824
825 // Do not try the incorporate the sub-GEP if some index is not a number.
826 bool AllConstantInt = true;
David Majnemer90a97042016-07-13 04:22:12 +0000827 for (Value *NestedOp : NestedOps)
828 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000829 AllConstantInt = false;
830 break;
831 }
832 if (!AllConstantInt)
833 break;
834
Dan Gohman474e488c2010-03-10 19:31:51 +0000835 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000836 SrcElemTy = GEP->getSourceElementType();
837 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000838 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000839 }
840
Dan Gohman81ce8422009-08-19 18:18:36 +0000841 // If the base value for this address is a literal integer value, fold the
842 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000843 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000844 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000845 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000846 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000847 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000848 }
849 }
850
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000851 auto *PTy = cast<PointerType>(Ptr->getType());
852 if ((Ptr->isNullValue() || BasePtr != 0) &&
853 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000854 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000855 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-08-19 18:18:36 +0000856 }
857
858 // Otherwise form a regular getelementptr. Recompute the indices so that
859 // we eliminate over-indexing of the notional static type array bounds.
860 // This makes it easy to determine if the getelementptr is "inbounds".
861 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000862 Type *Ty = PTy;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000863 SmallVector<Constant *, 32> NewIdxs;
864
Dan Gohmanc59ba422009-08-19 22:46:59 +0000865 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000866 if (!Ty->isStructTy()) {
867 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000868 // The only pointer indexing we'll do is on the first index of the GEP.
869 if (!NewIdxs.empty())
870 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000871
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000872 Ty = SrcElemTy;
873
Chris Lattner77c36d62009-12-03 01:05:45 +0000874 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000875 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000876 return nullptr;
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000877 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
878 Ty = ATy->getElementType();
879 } else {
880 // We've reached some non-indexable type.
881 break;
Chris Lattner77c36d62009-12-03 01:05:45 +0000882 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000883
Dan Gohman81ce8422009-08-19 18:18:36 +0000884 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000885 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer1b3db332016-07-13 05:16:16 +0000886 if (ElemSize == 0) {
Chris Lattner6ce03802010-11-21 08:39:01 +0000887 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000888 // index for this level and proceed to the next level to see if it can
889 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000890 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer1b3db332016-07-13 05:16:16 +0000891 } else {
Chris Lattner6ce03802010-11-21 08:39:01 +0000892 // The element size is non-zero divide the offset by the element
893 // size (rounding down), to compute the index at this level.
David Majnemer4cff2f82016-07-13 15:53:46 +0000894 bool Overflow;
895 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
896 if (Overflow)
897 break;
Chris Lattner6ce03802010-11-21 08:39:01 +0000898 Offset -= NewIdx * ElemSize;
899 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
900 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000901 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000902 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000903 // If we end up with an offset that isn't valid for this struct type, we
904 // can't re-form this GEP in a regular form, so bail out. The pointer
905 // operand likely went through casts that are necessary to make the GEP
906 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000907 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer1b3db332016-07-13 05:16:16 +0000908 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000909 break;
910
911 // Determine which field of the struct the offset points into. The
912 // getZExtValue is fine as we've already ensured that the offset is
913 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000914 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000915 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
916 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000917 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000918 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000919 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000920 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000921
922 // If we haven't used up the entire offset by descending the static
923 // type, then the offset is pointing into the middle of an indivisible
924 // member, so we can't simplify it.
925 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000926 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000927
Dan Gohman21c62162009-09-11 00:04:14 +0000928 // Create a GEP.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000929 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000930 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000931 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000932
Dan Gohmanc59ba422009-08-19 22:46:59 +0000933 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000934 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000935 if (Ty != ResElemTy)
936 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000937
938 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000939}
940
Manuel Jacobe9024592016-01-21 06:33:22 +0000941/// Attempt to constant fold an instruction with the
942/// specified opcode and operands. If successful, the constant result is
943/// returned, if not, null is returned. Note that this function can fail when
944/// attempting to fold instructions like loads and stores, which have no
945/// constant expression form.
946///
947/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
948/// information, due to only being passed an opcode and operands. Constant
949/// folding using this function strips this information.
950///
David Majnemera926b3e2016-07-29 03:27:33 +0000951Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000952 ArrayRef<Constant *> Ops,
953 const DataLayout &DL,
954 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +0000955 Type *DestTy = InstOrCE->getType();
956
Manuel Jacobe9024592016-01-21 06:33:22 +0000957 // Handle easy binops first.
958 if (Instruction::isBinaryOp(Opcode))
959 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
960
961 if (Instruction::isCast(Opcode))
962 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
963
David Majnemer17bdf442016-07-13 03:42:38 +0000964 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000965 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
966 return C;
967
968 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(),
969 Ops[0], Ops.slice(1));
970 }
971
David Majnemer57b94c82016-07-29 03:27:31 +0000972 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
973 return CE->getWithOperands(Ops);
974
Manuel Jacobe9024592016-01-21 06:33:22 +0000975 switch (Opcode) {
976 default: return nullptr;
977 case Instruction::ICmp:
978 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
979 case Instruction::Call:
David Majnemer90a97042016-07-13 04:22:12 +0000980 if (auto *F = dyn_cast<Function>(Ops.back()))
Manuel Jacobe9024592016-01-21 06:33:22 +0000981 if (canConstantFoldCallTo(F))
982 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
983 return nullptr;
984 case Instruction::Select:
985 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
986 case Instruction::ExtractElement:
987 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
988 case Instruction::InsertElement:
989 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
990 case Instruction::ShuffleVector:
991 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +0000992 }
993}
994
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000995} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +0000996
997//===----------------------------------------------------------------------===//
998// Constant Folding public APIs
999//===----------------------------------------------------------------------===//
1000
David Majnemerd536f232016-07-29 03:27:26 +00001001namespace {
1002
1003Constant *
1004ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1005 const TargetLibraryInfo *TLI,
1006 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1007 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1008 return nullptr;
1009
1010 SmallVector<Constant *, 8> Ops;
1011 for (const Use &NewU : C->operands()) {
1012 auto *NewC = cast<Constant>(&NewU);
1013 // Recursively fold the ConstantExpr's operands. If we have already folded
1014 // a ConstantExpr, we don't have to process it again.
1015 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1016 auto It = FoldedOps.find(NewC);
1017 if (It == FoldedOps.end()) {
1018 if (auto *FoldedC =
1019 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
1020 NewC = FoldedC;
1021 FoldedOps.insert({NewC, FoldedC});
1022 } else {
1023 FoldedOps.insert({NewC, NewC});
1024 }
1025 } else {
1026 NewC = It->second;
1027 }
1028 }
1029 Ops.push_back(NewC);
1030 }
1031
1032 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1033 if (CE->isCompare())
1034 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1035 DL, TLI);
1036
David Majnemera926b3e2016-07-29 03:27:33 +00001037 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemerd536f232016-07-29 03:27:26 +00001038 }
1039
1040 assert(isa<ConstantVector>(C));
1041 return ConstantVector::get(Ops);
1042}
1043
1044} // end anonymous namespace
1045
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001046Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001047 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +00001048 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +00001049 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +00001050 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +00001051
David Majnemerd536f232016-07-29 03:27:26 +00001052 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooper833f34d2015-05-12 20:05:31 +00001053 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +00001054 // If the incoming value is undef then skip it. Note that while we could
1055 // skip the value if it is equal to the phi node itself we choose not to
1056 // because that would break the rule that constant folding only applies if
1057 // all operands are constants.
1058 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +00001059 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001060 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +00001061 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001062 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00001063 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001064 // Fold the PHI's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001065 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1066 C = FoldedC;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001067 // If the incoming value is a different constant to
1068 // the one we saw previously, then give up.
1069 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00001070 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +00001071 CommonValue = C;
1072 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001073
Duncan Sands1d27f0122010-11-14 12:53:18 +00001074 // If we reach here, all incoming values are the same constant or undef.
1075 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +00001076 }
1077
1078 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +00001079 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001080 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1081 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +00001082
David Majnemerd536f232016-07-29 03:27:26 +00001083 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001084 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001085 for (const Use &OpU : I->operands()) {
1086 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001087 // Fold the Instruction's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001088 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1089 Op = FoldedOp;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001090
1091 Ops.push_back(Op);
1092 }
1093
David Majnemer90a97042016-07-13 04:22:12 +00001094 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001095 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001096 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001097
David Majnemer90a97042016-07-13 04:22:12 +00001098 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001099 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001100
David Majnemer90a97042016-07-13 04:22:12 +00001101 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001102 return ConstantExpr::getInsertValue(
1103 cast<Constant>(IVI->getAggregateOperand()),
1104 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001105 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001106 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001107
David Majnemer90a97042016-07-13 04:22:12 +00001108 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001109 return ConstantExpr::getExtractValue(
1110 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001111 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001112 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001113
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001114 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001115}
1116
David Majnemerd536f232016-07-29 03:27:26 +00001117Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1118 const TargetLibraryInfo *TLI) {
1119 SmallDenseMap<Constant *, Constant *> FoldedOps;
1120 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001121}
1122
Manuel Jacobe9024592016-01-21 06:33:22 +00001123Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001124 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001125 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001126 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001127 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001128}
1129
Chris Lattnerd2265b42007-12-10 22:53:04 +00001130Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001131 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001132 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001133 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001134 // fold: icmp (inttoptr x), null -> icmp x, 0
1135 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001136 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001137 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1138 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001139 // FIXME: The following comment is out of data and the DataLayout is here now.
1140 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001141 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001142 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001143 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001144 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001145 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001146 // Convert the integer value to the right size to ensure we get the
1147 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001148 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001149 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001150 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001151 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001152 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001153
Chris Lattnerd2265b42007-12-10 22:53:04 +00001154 // Only do this transformation if the int is intptrty in size, otherwise
1155 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001156 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001157 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001158 if (CE0->getType() == IntPtrTy) {
1159 Constant *C = CE0->getOperand(0);
1160 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001161 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001162 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001163 }
1164 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001165
David Majnemer90a97042016-07-13 04:22:12 +00001166 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001167 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001168 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001169 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001170
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001171 // Convert the integer value to the right size to ensure we get the
1172 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001173 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001174 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001175 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001176 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001177 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001178 }
1179
Chandler Carruth7ec50852012-11-01 08:07:29 +00001180 // Only do this transformation if the int is intptrty in size, otherwise
1181 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001182 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001183 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001184 if (CE0->getType() == IntPtrTy &&
1185 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001186 return ConstantFoldCompareInstOperands(
1187 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001188 }
1189 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001190 }
1191 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001192
Chris Lattner8fb74c62010-01-02 01:22:23 +00001193 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1194 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1195 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1196 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001197 Constant *LHS = ConstantFoldCompareInstOperands(
1198 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1199 Constant *RHS = ConstantFoldCompareInstOperands(
1200 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001201 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001202 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001203 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001204 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001205 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001206
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001207 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001208}
1209
Manuel Jacoba61ca372016-01-21 06:26:35 +00001210Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1211 Constant *RHS,
1212 const DataLayout &DL) {
1213 assert(Instruction::isBinaryOp(Opcode));
1214 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1215 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1216 return C;
1217
1218 return ConstantExpr::get(Opcode, LHS, RHS);
1219}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001220
Manuel Jacob925d0292016-01-21 06:31:08 +00001221Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1222 Type *DestTy, const DataLayout &DL) {
1223 assert(Instruction::isCast(Opcode));
1224 switch (Opcode) {
1225 default:
1226 llvm_unreachable("Missing case");
1227 case Instruction::PtrToInt:
1228 // If the input is a inttoptr, eliminate the pair. This requires knowing
1229 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001230 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001231 if (CE->getOpcode() == Instruction::IntToPtr) {
1232 Constant *Input = CE->getOperand(0);
1233 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1234 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1235 if (PtrWidth < InWidth) {
1236 Constant *Mask =
1237 ConstantInt::get(CE->getContext(),
1238 APInt::getLowBitsSet(InWidth, PtrWidth));
1239 Input = ConstantExpr::getAnd(Input, Mask);
1240 }
1241 // Do a zext or trunc to get to the dest size.
1242 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1243 }
1244 }
1245 return ConstantExpr::getCast(Opcode, C, DestTy);
1246 case Instruction::IntToPtr:
1247 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1248 // the int size is >= the ptr size and the address spaces are the same.
1249 // This requires knowing the width of a pointer, so it can't be done in
1250 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001251 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001252 if (CE->getOpcode() == Instruction::PtrToInt) {
1253 Constant *SrcPtr = CE->getOperand(0);
1254 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1255 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1256
1257 if (MidIntSize >= SrcPtrSize) {
1258 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1259 if (SrcAS == DestTy->getPointerAddressSpace())
1260 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1261 }
1262 }
1263 }
1264
1265 return ConstantExpr::getCast(Opcode, C, DestTy);
1266 case Instruction::Trunc:
1267 case Instruction::ZExt:
1268 case Instruction::SExt:
1269 case Instruction::FPTrunc:
1270 case Instruction::FPExt:
1271 case Instruction::UIToFP:
1272 case Instruction::SIToFP:
1273 case Instruction::FPToUI:
1274 case Instruction::FPToSI:
1275 case Instruction::AddrSpaceCast:
1276 return ConstantExpr::getCast(Opcode, C, DestTy);
1277 case Instruction::BitCast:
1278 return FoldBitCast(C, DestTy, DL);
1279 }
1280}
1281
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001282Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001283 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001284 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001285 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001286
1287 // Loop over all of the operands, tracking down which value we are
1288 // addressing.
1289 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1290 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001291 if (!C)
1292 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001293 }
1294 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001295}
1296
David Majnemer90a97042016-07-13 04:22:12 +00001297Constant *
1298llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1299 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001300 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001301 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001302 for (Constant *Index : Indices) {
1303 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001304 if (!C)
1305 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001306 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001307 return C;
1308}
1309
Chris Lattner2ae054a2007-01-30 23:45:45 +00001310//===----------------------------------------------------------------------===//
1311// Constant Folding for Calls
1312//
John Criswell970af112005-10-27 16:00:10 +00001313
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001314bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001315 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001316 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001317 case Intrinsic::minnum:
1318 case Intrinsic::maxnum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001319 case Intrinsic::log:
1320 case Intrinsic::log2:
1321 case Intrinsic::log10:
1322 case Intrinsic::exp:
1323 case Intrinsic::exp2:
1324 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001325 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001326 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001327 case Intrinsic::sin:
1328 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001329 case Intrinsic::trunc:
1330 case Intrinsic::rint:
1331 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001332 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001333 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001334 case Intrinsic::bswap:
1335 case Intrinsic::ctpop:
1336 case Intrinsic::ctlz:
1337 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001338 case Intrinsic::fma:
1339 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001340 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001341 case Intrinsic::round:
David Majnemer7f781ab2016-07-14 00:29:50 +00001342 case Intrinsic::masked_load:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001343 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001344 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001345 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001346 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001347 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001348 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001349 case Intrinsic::convert_from_fp16:
1350 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001351 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001352 case Intrinsic::x86_sse_cvtss2si:
1353 case Intrinsic::x86_sse_cvtss2si64:
1354 case Intrinsic::x86_sse_cvttss2si:
1355 case Intrinsic::x86_sse_cvttss2si64:
1356 case Intrinsic::x86_sse2_cvtsd2si:
1357 case Intrinsic::x86_sse2_cvtsd2si64:
1358 case Intrinsic::x86_sse2_cvttsd2si:
1359 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001360 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001361 default:
1362 return false;
1363 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001364 }
1365
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001366 if (!F->hasName())
1367 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001368 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001369
Chris Lattner785f9982007-08-08 06:55:43 +00001370 // In these cases, the check of the length is required. We don't want to
1371 // return true for a name like "cos\0blah" which strcmp would return equal to
1372 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001373 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001374 default:
1375 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001376 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001377 return Name == "acos" || Name == "asin" || Name == "atan" ||
1378 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1379 Name == "atanf" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001380 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001381 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1382 Name == "ceilf" || Name == "cosf" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001383 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001384 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001385 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001386 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1387 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001388 case 'l':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001389 return Name == "log" || Name == "log10" || Name == "logf" ||
1390 Name == "log10f";
Chris Lattner785f9982007-08-08 06:55:43 +00001391 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001392 return Name == "pow" || Name == "powf";
Chris Lattner785f9982007-08-08 06:55:43 +00001393 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001394 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001395 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001396 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001397 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
John Criswell970af112005-10-27 16:00:10 +00001398 }
1399}
1400
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001401namespace {
1402
1403Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001404 if (Ty->isHalfTy()) {
1405 APFloat APF(V);
1406 bool unused;
1407 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1408 return ConstantFP::get(Ty->getContext(), APF);
1409 }
Chris Lattner351534f2009-10-05 05:06:24 +00001410 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001411 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001412 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001413 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001414 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001415}
1416
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001417/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001418inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001419#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001420 feclearexcept(FE_ALL_EXCEPT);
1421#endif
1422 errno = 0;
1423}
1424
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001425/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001426inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001427 int errno_val = errno;
1428 if (errno_val == ERANGE || errno_val == EDOM)
1429 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001430#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001431 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1432 return true;
1433#endif
1434 return false;
1435}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001436
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001437Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001438 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001439 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001440 if (llvm_fenv_testexcept()) {
1441 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001442 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001443 }
1444
1445 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001446}
1447
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001448Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1449 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001450 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001451 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001452 if (llvm_fenv_testexcept()) {
1453 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001454 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001455 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001456
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001457 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001458}
1459
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001460/// Attempt to fold an SSE floating point to integer conversion of a constant
1461/// floating point. If roundTowardZero is false, the default IEEE rounding is
1462/// used (toward nearest, ties to even). This matches the behavior of the
1463/// non-truncating SSE instructions in the default rounding mode. The desired
1464/// integer type Ty is used to select how many bits are available for the
1465/// result. Returns null if the conversion cannot be performed, otherwise
1466/// returns the Constant value resulting from the conversion.
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001467Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1468 Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001469 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001470 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001471 assert(ResultWidth <= 64 &&
1472 "Can only constant fold conversions to 64 and 32 bit ints");
1473
1474 uint64_t UIntVal;
1475 bool isExact = false;
1476 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1477 : APFloat::rmNearestTiesToEven;
1478 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1479 /*isSigned=*/true, mode,
1480 &isExact);
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001481 if (status != APFloat::opOK &&
1482 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper9f008862014-04-15 04:59:12 +00001483 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001484 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1485}
1486
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001487double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001488 Type *Ty = Op->getType();
1489
1490 if (Ty->isFloatTy())
1491 return Op->getValueAPF().convertToFloat();
1492
1493 if (Ty->isDoubleTy())
1494 return Op->getValueAPF().convertToDouble();
1495
1496 bool unused;
1497 APFloat APF = Op->getValueAPF();
1498 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1499 return APF.convertToDouble();
1500}
1501
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001502Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1503 ArrayRef<Constant *> Operands,
1504 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001505 if (Operands.size() == 1) {
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001506 if (isa<UndefValue>(Operands[0])) {
1507 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1508 if (IntrinsicID == Intrinsic::cos)
1509 return Constant::getNullValue(Ty);
1510 }
David Majnemer90a97042016-07-13 04:22:12 +00001511 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001512 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001513 APFloat Val(Op->getValueAPF());
1514
1515 bool lost = false;
1516 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1517
Benjamin Kramer061d1472014-03-05 19:41:48 +00001518 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001519 }
1520
Owen Andersond4ebfd82013-02-06 22:43:31 +00001521 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001522 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001523
Karthik Bhatb67688a2014-03-07 04:36:21 +00001524 if (IntrinsicID == Intrinsic::round) {
1525 APFloat V = Op->getValueAPF();
1526 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1527 return ConstantFP::get(Ty->getContext(), V);
1528 }
1529
Karthik Bhatd818e382015-07-21 08:52:23 +00001530 if (IntrinsicID == Intrinsic::floor) {
1531 APFloat V = Op->getValueAPF();
1532 V.roundToIntegral(APFloat::rmTowardNegative);
1533 return ConstantFP::get(Ty->getContext(), V);
1534 }
1535
1536 if (IntrinsicID == Intrinsic::ceil) {
1537 APFloat V = Op->getValueAPF();
1538 V.roundToIntegral(APFloat::rmTowardPositive);
1539 return ConstantFP::get(Ty->getContext(), V);
1540 }
1541
1542 if (IntrinsicID == Intrinsic::trunc) {
1543 APFloat V = Op->getValueAPF();
1544 V.roundToIntegral(APFloat::rmTowardZero);
1545 return ConstantFP::get(Ty->getContext(), V);
1546 }
1547
1548 if (IntrinsicID == Intrinsic::rint) {
1549 APFloat V = Op->getValueAPF();
1550 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1551 return ConstantFP::get(Ty->getContext(), V);
1552 }
1553
1554 if (IntrinsicID == Intrinsic::nearbyint) {
1555 APFloat V = Op->getValueAPF();
1556 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1557 return ConstantFP::get(Ty->getContext(), V);
1558 }
1559
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001560 /// We only fold functions with finite arguments. Folding NaN and inf is
1561 /// likely to be aborted with an exception anyway, and some host libms
1562 /// have known errors raising exceptions.
1563 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001564 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001565
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001566 /// Currently APFloat versions of these functions do not exist, so we use
1567 /// the host native double versions. Float versions are not called
1568 /// directly but for all these it is true (float)(f((double)arg)) ==
1569 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001570 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001571
Benjamin Kramer061d1472014-03-05 19:41:48 +00001572 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001573 default: break;
1574 case Intrinsic::fabs:
1575 return ConstantFoldFP(fabs, V, Ty);
1576 case Intrinsic::log2:
Vince Harrond5281122015-05-07 00:05:26 +00001577 return ConstantFoldFP(Log2, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001578 case Intrinsic::log:
1579 return ConstantFoldFP(log, V, Ty);
1580 case Intrinsic::log10:
1581 return ConstantFoldFP(log10, V, Ty);
1582 case Intrinsic::exp:
1583 return ConstantFoldFP(exp, V, Ty);
1584 case Intrinsic::exp2:
1585 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001586 case Intrinsic::sin:
1587 return ConstantFoldFP(sin, V, Ty);
1588 case Intrinsic::cos:
1589 return ConstantFoldFP(cos, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001590 }
1591
Benjamin Kramer061d1472014-03-05 19:41:48 +00001592 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001593 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001594
Daniel Dunbarca414c72009-07-26 08:34:35 +00001595 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001596 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001597 if ((Name == "acos" && TLI->has(LibFunc::acos)) ||
1598 (Name == "acosf" && TLI->has(LibFunc::acosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001599 return ConstantFoldFP(acos, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001600 else if ((Name == "asin" && TLI->has(LibFunc::asin)) ||
1601 (Name == "asinf" && TLI->has(LibFunc::asinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001602 return ConstantFoldFP(asin, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001603 else if ((Name == "atan" && TLI->has(LibFunc::atan)) ||
1604 (Name == "atanf" && TLI->has(LibFunc::atanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001605 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001606 break;
1607 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001608 if ((Name == "ceil" && TLI->has(LibFunc::ceil)) ||
1609 (Name == "ceilf" && TLI->has(LibFunc::ceilf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001610 return ConstantFoldFP(ceil, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001611 else if ((Name == "cos" && TLI->has(LibFunc::cos)) ||
1612 (Name == "cosf" && TLI->has(LibFunc::cosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001613 return ConstantFoldFP(cos, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001614 else if ((Name == "cosh" && TLI->has(LibFunc::cosh)) ||
1615 (Name == "coshf" && TLI->has(LibFunc::coshf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001616 return ConstantFoldFP(cosh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001617 break;
1618 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001619 if ((Name == "exp" && TLI->has(LibFunc::exp)) ||
1620 (Name == "expf" && TLI->has(LibFunc::expf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001621 return ConstantFoldFP(exp, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001622 if ((Name == "exp2" && TLI->has(LibFunc::exp2)) ||
1623 (Name == "exp2f" && TLI->has(LibFunc::exp2f)))
Chris Lattner713d5232011-05-22 22:22:35 +00001624 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1625 // C99 library.
1626 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001627 break;
1628 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001629 if ((Name == "fabs" && TLI->has(LibFunc::fabs)) ||
1630 (Name == "fabsf" && TLI->has(LibFunc::fabsf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001631 return ConstantFoldFP(fabs, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001632 else if ((Name == "floor" && TLI->has(LibFunc::floor)) ||
1633 (Name == "floorf" && TLI->has(LibFunc::floorf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001634 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001635 break;
1636 case 'l':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001637 if ((Name == "log" && V > 0 && TLI->has(LibFunc::log)) ||
1638 (Name == "logf" && V > 0 && TLI->has(LibFunc::logf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001639 return ConstantFoldFP(log, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001640 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc::log10)) ||
1641 (Name == "log10f" && V > 0 && TLI->has(LibFunc::log10f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001642 return ConstantFoldFP(log10, V, Ty);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001643 else if (IntrinsicID == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001644 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001645 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001646 return ConstantFoldFP(sqrt, V, Ty);
Sanjay Patel7b2cd9a2014-10-01 20:36:33 +00001647 else {
1648 // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1649 // all guarantee or favor returning NaN - the square root of a
1650 // negative number is not defined for the LLVM sqrt intrinsic.
1651 // This is because the intrinsic should only be emitted in place of
1652 // libm's sqrt function when using "no-nans-fp-math".
1653 return UndefValue::get(Ty);
1654 }
Chris Lattner785f9982007-08-08 06:55:43 +00001655 }
1656 break;
1657 case 's':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001658 if ((Name == "sin" && TLI->has(LibFunc::sin)) ||
1659 (Name == "sinf" && TLI->has(LibFunc::sinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001660 return ConstantFoldFP(sin, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001661 else if ((Name == "sinh" && TLI->has(LibFunc::sinh)) ||
1662 (Name == "sinhf" && TLI->has(LibFunc::sinhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001663 return ConstantFoldFP(sinh, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001664 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt)) ||
1665 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001666 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001667 break;
1668 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001669 if ((Name == "tan" && TLI->has(LibFunc::tan)) ||
1670 (Name == "tanf" && TLI->has(LibFunc::tanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001671 return ConstantFoldFP(tan, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001672 else if ((Name == "tanh" && TLI->has(LibFunc::tanh)) ||
1673 (Name == "tanhf" && TLI->has(LibFunc::tanhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001674 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001675 break;
1676 default:
1677 break;
John Criswell970af112005-10-27 16:00:10 +00001678 }
Craig Topper9f008862014-04-15 04:59:12 +00001679 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001680 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001681
David Majnemer90a97042016-07-13 04:22:12 +00001682 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001683 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001684 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001685 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001686 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001687 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Matt Arsenault155dda92016-03-21 15:00:35 +00001688 case Intrinsic::bitreverse:
1689 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001690 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001691 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001692
1693 bool lost = false;
Andrea Di Biagio29059992015-05-14 18:01:48 +00001694 APFloat::opStatus status = Val.convert(
1695 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001696
1697 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001698 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001699 assert(status == APFloat::opOK && !lost &&
1700 "Precision lost during fp16 constfolding");
1701
Benjamin Kramer061d1472014-03-05 19:41:48 +00001702 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001703 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001704 default:
Craig Topper9f008862014-04-15 04:59:12 +00001705 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001706 }
John Criswell970af112005-10-27 16:00:10 +00001707 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001708
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001709 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001710 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001711 isa<ConstantDataVector>(Operands[0])) {
David Majnemer90a97042016-07-13 04:22:12 +00001712 auto *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001713 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001714 default: break;
1715 case Intrinsic::x86_sse_cvtss2si:
1716 case Intrinsic::x86_sse_cvtss2si64:
1717 case Intrinsic::x86_sse2_cvtsd2si:
1718 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001719 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001720 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1721 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1722 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001723 case Intrinsic::x86_sse_cvttss2si:
1724 case Intrinsic::x86_sse_cvttss2si64:
1725 case Intrinsic::x86_sse2_cvttsd2si:
1726 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001727 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001728 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1729 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1730 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001731 }
1732 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001733
Dan Gohmancf39be32010-02-17 00:54:58 +00001734 if (isa<UndefValue>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001735 if (IntrinsicID == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001736 return Operands[0];
Craig Topper9f008862014-04-15 04:59:12 +00001737 return nullptr;
Dan Gohmancf39be32010-02-17 00:54:58 +00001738 }
1739
Craig Topper9f008862014-04-15 04:59:12 +00001740 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001741 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001742
Jay Foadf4b14a22011-07-19 13:32:40 +00001743 if (Operands.size() == 2) {
David Majnemer90a97042016-07-13 04:22:12 +00001744 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001745 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001746 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001747 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001748
David Majnemer90a97042016-07-13 04:22:12 +00001749 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001750 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001751 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001752
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001753 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001754 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001755 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1756 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001757 if (IntrinsicID == Intrinsic::copysign) {
1758 APFloat V1 = Op1->getValueAPF();
Benjamin Kramer8f59adb2016-02-13 16:54:14 +00001759 const APFloat &V2 = Op2->getValueAPF();
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001760 V1.copySign(V2);
1761 return ConstantFP::get(Ty->getContext(), V1);
1762 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001763
1764 if (IntrinsicID == Intrinsic::minnum) {
1765 const APFloat &C1 = Op1->getValueAPF();
1766 const APFloat &C2 = Op2->getValueAPF();
1767 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1768 }
1769
1770 if (IntrinsicID == Intrinsic::maxnum) {
1771 const APFloat &C1 = Op1->getValueAPF();
1772 const APFloat &C2 = Op2->getValueAPF();
1773 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1774 }
1775
Chad Rosier0155a632011-12-03 00:00:03 +00001776 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001777 return nullptr;
Erik Schnetter5e93e282015-08-27 19:56:57 +00001778 if ((Name == "pow" && TLI->has(LibFunc::pow)) ||
1779 (Name == "powf" && TLI->has(LibFunc::powf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001780 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001781 if ((Name == "fmod" && TLI->has(LibFunc::fmod)) ||
1782 (Name == "fmodf" && TLI->has(LibFunc::fmodf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001783 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001784 if ((Name == "atan2" && TLI->has(LibFunc::atan2)) ||
1785 (Name == "atan2f" && TLI->has(LibFunc::atan2f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001786 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
David Majnemer90a97042016-07-13 04:22:12 +00001787 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001788 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1789 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001790 APFloat((float)std::pow((float)Op1V,
1791 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001792 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1793 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001794 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001795 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001796 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1797 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001798 APFloat((double)std::pow((double)Op1V,
1799 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001800 }
Craig Topper9f008862014-04-15 04:59:12 +00001801 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001802 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001803
David Majnemer90a97042016-07-13 04:22:12 +00001804 if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1805 if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001806 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001807 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001808 case Intrinsic::sadd_with_overflow:
1809 case Intrinsic::uadd_with_overflow:
1810 case Intrinsic::ssub_with_overflow:
1811 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001812 case Intrinsic::smul_with_overflow:
1813 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001814 APInt Res;
1815 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001816 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001817 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001818 case Intrinsic::sadd_with_overflow:
1819 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1820 break;
1821 case Intrinsic::uadd_with_overflow:
1822 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1823 break;
1824 case Intrinsic::ssub_with_overflow:
1825 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1826 break;
1827 case Intrinsic::usub_with_overflow:
1828 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1829 break;
1830 case Intrinsic::smul_with_overflow:
1831 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1832 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001833 case Intrinsic::umul_with_overflow:
1834 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1835 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001836 }
Chris Lattner59d93982009-10-05 05:26:04 +00001837 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001838 ConstantInt::get(Ty->getContext(), Res),
1839 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001840 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001841 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001842 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001843 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001844 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1845 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001846 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1847 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001848 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1849 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001850 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001851 }
1852 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001853
Craig Topper9f008862014-04-15 04:59:12 +00001854 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001855 }
Craig Topper9f008862014-04-15 04:59:12 +00001856 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001857 }
Matt Arsenault83778582014-03-05 00:02:00 +00001858
1859 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001860 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001861
David Majnemer90a97042016-07-13 04:22:12 +00001862 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1863 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1864 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001865 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001866 default: break;
1867 case Intrinsic::fma:
1868 case Intrinsic::fmuladd: {
1869 APFloat V = Op1->getValueAPF();
1870 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1871 Op3->getValueAPF(),
1872 APFloat::rmNearestTiesToEven);
1873 if (s != APFloat::opInvalidOp)
1874 return ConstantFP::get(Ty->getContext(), V);
1875
Craig Topper9f008862014-04-15 04:59:12 +00001876 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001877 }
1878 }
1879 }
1880 }
1881 }
1882
Craig Topper9f008862014-04-15 04:59:12 +00001883 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001884}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001885
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001886Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1887 VectorType *VTy, ArrayRef<Constant *> Operands,
David Majnemer7f781ab2016-07-14 00:29:50 +00001888 const DataLayout &DL,
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001889 const TargetLibraryInfo *TLI) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001890 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1891 SmallVector<Constant *, 4> Lane(Operands.size());
1892 Type *Ty = VTy->getElementType();
1893
David Majnemer7f781ab2016-07-14 00:29:50 +00001894 if (IntrinsicID == Intrinsic::masked_load) {
1895 auto *SrcPtr = Operands[0];
1896 auto *Mask = Operands[2];
1897 auto *Passthru = Operands[3];
David Majnemer17a95aa2016-07-14 06:58:37 +00001898
David Majnemer7f781ab2016-07-14 00:29:50 +00001899 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer7f781ab2016-07-14 00:29:50 +00001900
1901 SmallVector<Constant *, 32> NewElements;
1902 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer17a95aa2016-07-14 06:58:37 +00001903 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer7f781ab2016-07-14 00:29:50 +00001904 if (!MaskElt)
1905 break;
David Majnemer17a95aa2016-07-14 06:58:37 +00001906 auto *PassthruElt = Passthru->getAggregateElement(I);
1907 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
1908 if (isa<UndefValue>(MaskElt)) {
1909 if (PassthruElt)
1910 NewElements.push_back(PassthruElt);
1911 else if (VecElt)
1912 NewElements.push_back(VecElt);
1913 else
1914 return nullptr;
1915 }
1916 if (MaskElt->isNullValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00001917 if (!PassthruElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00001918 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001919 NewElements.push_back(PassthruElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00001920 } else if (MaskElt->isOneValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00001921 if (!VecElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00001922 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001923 NewElements.push_back(VecElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00001924 } else {
1925 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00001926 }
1927 }
David Majnemer17a95aa2016-07-14 06:58:37 +00001928 if (NewElements.size() != VTy->getNumElements())
1929 return nullptr;
1930 return ConstantVector::get(NewElements);
David Majnemer7f781ab2016-07-14 00:29:50 +00001931 }
1932
Benjamin Kramer061d1472014-03-05 19:41:48 +00001933 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1934 // Gather a column of constants.
1935 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1936 Constant *Agg = Operands[J]->getAggregateElement(I);
1937 if (!Agg)
1938 return nullptr;
1939
1940 Lane[J] = Agg;
1941 }
1942
1943 // Use the regular scalar folding to simplify this column.
1944 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1945 if (!Folded)
1946 return nullptr;
1947 Result[I] = Folded;
1948 }
1949
1950 return ConstantVector::get(Result);
1951}
1952
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001953} // end anonymous namespace
1954
Benjamin Kramer061d1472014-03-05 19:41:48 +00001955Constant *
1956llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1957 const TargetLibraryInfo *TLI) {
1958 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00001959 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001960 StringRef Name = F->getName();
1961
1962 Type *Ty = F->getReturnType();
1963
David Majnemer90a97042016-07-13 04:22:12 +00001964 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer7f781ab2016-07-14 00:29:50 +00001965 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
1966 F->getParent()->getDataLayout(), TLI);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001967
1968 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1969}
Eli Friedmanb6befc32016-11-02 20:48:11 +00001970
1971bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) {
1972 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
1973 // (and to some extent ConstantFoldScalarCall).
1974 Function *F = CS.getCalledFunction();
1975 if (!F)
1976 return false;
1977
1978 LibFunc::Func Func;
1979 if (!TLI || !TLI->getLibFunc(*F, Func))
1980 return false;
1981
1982 if (CS.getNumArgOperands() == 1) {
1983 if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
1984 const APFloat &Op = OpC->getValueAPF();
1985 switch (Func) {
1986 case LibFunc::logl:
1987 case LibFunc::log:
1988 case LibFunc::logf:
1989 case LibFunc::log2l:
1990 case LibFunc::log2:
1991 case LibFunc::log2f:
1992 case LibFunc::log10l:
1993 case LibFunc::log10:
1994 case LibFunc::log10f:
1995 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
1996
1997 case LibFunc::expl:
1998 case LibFunc::exp:
1999 case LibFunc::expf:
2000 // FIXME: These boundaries are slightly conservative.
2001 if (OpC->getType()->isDoubleTy())
2002 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2003 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2004 if (OpC->getType()->isFloatTy())
2005 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2006 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2007 break;
2008
2009 case LibFunc::exp2l:
2010 case LibFunc::exp2:
2011 case LibFunc::exp2f:
2012 // FIXME: These boundaries are slightly conservative.
2013 if (OpC->getType()->isDoubleTy())
2014 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2015 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2016 if (OpC->getType()->isFloatTy())
2017 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2018 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2019 break;
2020
2021 case LibFunc::sinl:
2022 case LibFunc::sin:
2023 case LibFunc::sinf:
2024 case LibFunc::cosl:
2025 case LibFunc::cos:
2026 case LibFunc::cosf:
2027 return !Op.isInfinity();
2028
2029 case LibFunc::tanl:
2030 case LibFunc::tan:
2031 case LibFunc::tanf: {
2032 // FIXME: Stop using the host math library.
2033 // FIXME: The computation isn't done in the right precision.
2034 Type *Ty = OpC->getType();
2035 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2036 double OpV = getValueAsDouble(OpC);
2037 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2038 }
2039 break;
2040 }
2041
2042 case LibFunc::asinl:
2043 case LibFunc::asin:
2044 case LibFunc::asinf:
2045 case LibFunc::acosl:
2046 case LibFunc::acos:
2047 case LibFunc::acosf:
2048 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2049 APFloat::cmpLessThan &&
2050 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2051 APFloat::cmpGreaterThan;
2052
2053 case LibFunc::sinh:
2054 case LibFunc::cosh:
2055 case LibFunc::sinhf:
2056 case LibFunc::coshf:
2057 case LibFunc::sinhl:
2058 case LibFunc::coshl:
2059 // FIXME: These boundaries are slightly conservative.
2060 if (OpC->getType()->isDoubleTy())
2061 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2062 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2063 if (OpC->getType()->isFloatTy())
2064 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2065 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2066 break;
2067
2068 case LibFunc::sqrtl:
2069 case LibFunc::sqrt:
2070 case LibFunc::sqrtf:
2071 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2072
2073 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2074 // maybe others?
2075 default:
2076 break;
2077 }
2078 }
2079 }
2080
2081 if (CS.getNumArgOperands() == 2) {
2082 ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2083 ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2084 if (Op0C && Op1C) {
2085 const APFloat &Op0 = Op0C->getValueAPF();
2086 const APFloat &Op1 = Op1C->getValueAPF();
2087
2088 switch (Func) {
2089 case LibFunc::powl:
2090 case LibFunc::pow:
2091 case LibFunc::powf: {
2092 // FIXME: Stop using the host math library.
2093 // FIXME: The computation isn't done in the right precision.
2094 Type *Ty = Op0C->getType();
2095 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2096 if (Ty == Op1C->getType()) {
2097 double Op0V = getValueAsDouble(Op0C);
2098 double Op1V = getValueAsDouble(Op1C);
2099 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2100 }
2101 }
2102 break;
2103 }
2104
2105 case LibFunc::fmodl:
2106 case LibFunc::fmod:
2107 case LibFunc::fmodf:
2108 return Op0.isNaN() || Op1.isNaN() ||
2109 (!Op0.isInfinity() && !Op1.isZero());
2110
2111 default:
2112 break;
2113 }
2114 }
2115 }
2116
2117 return false;
2118}