blob: e88b8f14d54ed4f895a19b95636e915587b30343 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/ADT/SmallVector.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000026#include "llvm/ADT/StringRef.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"
Craig Topperb45eabc2017-04-26 16:39:58 +000045#include "llvm/Support/KnownBits.h"
John Criswell970af112005-10-27 16:00:10 +000046#include "llvm/Support/MathExtras.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000047#include <cassert>
John Criswell970af112005-10-27 16:00:10 +000048#include <cerrno>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000049#include <cfenv>
Jeff Cohencc08c832006-12-02 02:22:01 +000050#include <cmath>
Eugene Zelenko1804a772016-08-25 00:45:04 +000051#include <cstddef>
52#include <cstdint>
Alp Tokerc817d6a2014-06-09 18:28:53 +000053
John Criswell970af112005-10-27 16:00:10 +000054using namespace llvm;
55
Eugene Zelenko35623fb2016-03-28 17:40:08 +000056namespace {
57
Chris Lattner44d68b92007-01-31 00:51:48 +000058//===----------------------------------------------------------------------===//
59// Constant Folding internal helper functions
60//===----------------------------------------------------------------------===//
61
Matt Arsenault47a4b392016-12-02 02:26:02 +000062static Constant *foldConstVectorToAPInt(APInt &Result, Type *DestTy,
63 Constant *C, Type *SrcEltTy,
64 unsigned NumSrcElts,
65 const DataLayout &DL) {
66 // Now that we know that the input value is a vector of integers, just shift
67 // and insert them into our result.
68 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
69 for (unsigned i = 0; i != NumSrcElts; ++i) {
70 Constant *Element;
71 if (DL.isLittleEndian())
72 Element = C->getAggregateElement(NumSrcElts - i - 1);
73 else
74 Element = C->getAggregateElement(i);
75
76 if (Element && isa<UndefValue>(Element)) {
77 Result <<= BitShift;
78 continue;
79 }
80
81 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
82 if (!ElementCI)
83 return ConstantExpr::getBitCast(C, DestTy);
84
85 Result <<= BitShift;
86 Result |= ElementCI->getValue().zextOrSelf(Result.getBitWidth());
87 }
88
89 return nullptr;
90}
91
Matt Arsenault624e1b32016-12-07 20:56:11 +000092/// Constant fold bitcast, symbolically evaluating it with DataLayout.
Sanjay Patel0d7dee62014-10-02 15:13:22 +000093/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000094/// ConstantExpr if unfoldable.
Eugene Zelenko35623fb2016-03-28 17:40:08 +000095Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000096 // Catch the obvious splat cases.
97 if (C->isNullValue() && !DestTy->isX86_MMXTy())
98 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000099 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
100 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +0000101 return Constant::getAllOnesValue(DestTy);
102
Matt Arsenault624e1b32016-12-07 20:56:11 +0000103 if (auto *VTy = dyn_cast<VectorType>(C->getType())) {
104 // Handle a vector->scalar integer/fp cast.
105 if (isa<IntegerType>(DestTy) || DestTy->isFloatingPointTy()) {
106 unsigned NumSrcElts = VTy->getNumElements();
107 Type *SrcEltTy = VTy->getElementType();
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000108
Matt Arsenault624e1b32016-12-07 20:56:11 +0000109 // If the vector is a vector of floating point, convert it to vector of int
110 // to simplify things.
111 if (SrcEltTy->isFloatingPointTy()) {
112 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
113 Type *SrcIVTy =
114 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
115 // Ask IR to do the conversion now that #elts line up.
116 C = ConstantExpr::getBitCast(C, SrcIVTy);
117 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000118
Matt Arsenault624e1b32016-12-07 20:56:11 +0000119 APInt Result(DL.getTypeSizeInBits(DestTy), 0);
120 if (Constant *CE = foldConstVectorToAPInt(Result, DestTy, C,
121 SrcEltTy, NumSrcElts, DL))
122 return CE;
123
124 if (isa<IntegerType>(DestTy))
125 return ConstantInt::get(DestTy, Result);
126
127 APFloat FP(DestTy->getFltSemantics(), Result);
128 return ConstantFP::get(DestTy->getContext(), FP);
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000129 }
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000130 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000131
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000132 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000133 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000134 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000135 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000136
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000137 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
138 // vector so the code below can handle it uniformly.
139 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
140 Constant *Ops = C; // don't take the address of C!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000141 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000142 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000143
Chris Lattner9d051242009-10-25 06:08:26 +0000144 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000145 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000146 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000147
Chandler Carruthef860a22013-01-02 09:10:48 +0000148 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000149 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000150 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000151 if (NumDstElt == NumSrcElt)
152 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000153
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000154 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000155 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000156
157 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000158 // requires endianness information to do the right thing. For example,
159 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
160 // folds to (little endian):
161 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
162 // and to (big endian):
163 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000164
Chris Lattner9d051242009-10-25 06:08:26 +0000165 // First thing is first. We only want to think about integer here, so if
166 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000167 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000168 // Fold to an vector of integers with same size as our FP type.
169 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000170 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000171 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
172 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000173 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000174
Chandler Carruthef860a22013-01-02 09:10:48 +0000175 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000176 return ConstantExpr::getBitCast(C, DestTy);
177 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000178
Chris Lattner9d051242009-10-25 06:08:26 +0000179 // Okay, we know the destination is integer, if the input is FP, convert
180 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000181 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000182 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000183 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000184 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000185 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000186 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000187 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000188 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
189 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000190 return C;
191 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000192
Chris Lattner9d051242009-10-25 06:08:26 +0000193 // Now we know that the input and output vectors are both integer vectors
194 // of the same size, and that their #elements is not the same. Do the
195 // conversion here, which depends on whether the input or output has
196 // more elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000197 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000198
Chris Lattner9d051242009-10-25 06:08:26 +0000199 SmallVector<Constant*, 32> Result;
200 if (NumDstElt < NumSrcElt) {
201 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
202 Constant *Zero = Constant::getNullValue(DstEltTy);
203 unsigned Ratio = NumSrcElt/NumDstElt;
204 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
205 unsigned SrcElt = 0;
206 for (unsigned i = 0; i != NumDstElt; ++i) {
207 // Build each element of the result.
208 Constant *Elt = Zero;
209 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
210 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemere4218cf2016-07-29 04:06:09 +0000211 Constant *Src = C->getAggregateElement(SrcElt++);
212 if (Src && isa<UndefValue>(Src))
David Majnemer718da3d2016-07-29 18:48:27 +0000213 Src = Constant::getNullValue(C->getType()->getVectorElementType());
David Majnemere4218cf2016-07-29 04:06:09 +0000214 else
215 Src = dyn_cast_or_null<ConstantInt>(Src);
Chris Lattner9d051242009-10-25 06:08:26 +0000216 if (!Src) // Reject constantexpr elements.
217 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000218
Chris Lattner9d051242009-10-25 06:08:26 +0000219 // Zero extend the element to the right size.
220 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000221
Chris Lattner9d051242009-10-25 06:08:26 +0000222 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000223 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000224 ConstantInt::get(Src->getType(), ShiftAmt));
225 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000226
Chris Lattner9d051242009-10-25 06:08:26 +0000227 // Mix it in.
228 Elt = ConstantExpr::getOr(Elt, Src);
229 }
230 Result.push_back(Elt);
231 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000232 return ConstantVector::get(Result);
233 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000234
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000235 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
236 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000238
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000239 // Loop over each source value, expanding into multiple results.
240 for (unsigned i = 0; i != NumSrcElt; ++i) {
Andrea Di Biagio7277afe2016-09-13 14:50:47 +0000241 auto *Element = C->getAggregateElement(i);
242
243 if (!Element) // Reject constantexpr elements.
244 return ConstantExpr::getBitCast(C, DestTy);
245
246 if (isa<UndefValue>(Element)) {
247 // Correctly Propagate undef values.
248 Result.append(Ratio, UndefValue::get(DstEltTy));
249 continue;
250 }
251
252 auto *Src = dyn_cast<ConstantInt>(Element);
253 if (!Src)
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000254 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000255
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000256 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
257 for (unsigned j = 0; j != Ratio; ++j) {
258 // Shift the piece of the value into the right place, depending on
259 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000260 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000261 ConstantInt::get(Src->getType(), ShiftAmt));
262 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000263
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000264 // Truncate the element to an integer with the same pointer size and
265 // convert the element back to a pointer using a inttoptr.
266 if (DstEltTy->isPointerTy()) {
267 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
268 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
269 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
270 continue;
271 }
272
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000273 // Truncate and remember this piece.
274 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000275 }
276 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000277
Chris Lattner69229312011-02-15 00:14:00 +0000278 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000279}
280
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000281} // end anonymous namespace
282
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000283/// If this constant is a constant offset from a global, return the global and
284/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000285bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
286 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000287 // Trivial case, constant is the global.
288 if ((GV = dyn_cast<GlobalValue>(C))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000290 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000291 return true;
292 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000293
Chris Lattner44d68b92007-01-31 00:51:48 +0000294 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000295 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000296 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000297
Chris Lattner44d68b92007-01-31 00:51:48 +0000298 // Look through ptr->int and ptr->ptr casts.
299 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000300 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000301 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000302
303 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000304 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000305 if (!GEP)
306 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000307
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000308 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000309 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000310
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000311 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000312 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000313 return false;
314
315 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000317 return false;
318
319 Offset = TmpOffset;
320 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000321}
322
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000323namespace {
324
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000325/// Recursive helper to read bits out of global. C is the constant being copied
326/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
327/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000328/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000329bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
330 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000331 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000332 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000333
Chris Lattner3db7bd22009-10-24 05:27:19 +0000334 // If this element is zero or undefined, we can just return since *CurPtr is
335 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000336 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
337 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000338
David Majnemer90a97042016-07-13 04:22:12 +0000339 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000340 if (CI->getBitWidth() > 64 ||
341 (CI->getBitWidth() & 7) != 0)
342 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000343
Chris Lattnered00b802009-10-23 06:23:49 +0000344 uint64_t Val = CI->getZExtValue();
345 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000346
Chris Lattnered00b802009-10-23 06:23:49 +0000347 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000348 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000349 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000350 n = IntBytes - n - 1;
351 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000352 ++ByteOffset;
353 }
354 return true;
355 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000356
David Majnemer90a97042016-07-13 04:22:12 +0000357 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000358 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000359 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
360 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000361 }
362 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000363 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
364 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000365 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000366 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000367 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
368 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000369 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000370 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000371 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000372
David Majnemer90a97042016-07-13 04:22:12 +0000373 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000374 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000375 unsigned Index = SL->getElementContainingOffset(ByteOffset);
376 uint64_t CurEltOffset = SL->getElementOffset(Index);
377 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000378
Eugene Zelenko1804a772016-08-25 00:45:04 +0000379 while (true) {
Chris Lattnered00b802009-10-23 06:23:49 +0000380 // If the element access is to the element itself and not to tail padding,
381 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000382 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000383
384 if (ByteOffset < EltSize &&
385 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000386 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000387 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000388
Chris Lattnered00b802009-10-23 06:23:49 +0000389 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000390
Chris Lattnered00b802009-10-23 06:23:49 +0000391 // Check to see if we read from the last struct element, if so we're done.
392 if (Index == CS->getType()->getNumElements())
393 return true;
394
395 // If we read all of the bytes we needed from this element we're done.
396 uint64_t NextEltOffset = SL->getElementOffset(Index);
397
Matt Arsenault8c789092013-08-12 23:15:58 +0000398 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000399 return true;
400
401 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000402 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
403 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000404 ByteOffset = 0;
405 CurEltOffset = NextEltOffset;
406 }
407 // not reached.
408 }
409
Chris Lattner67058832012-01-25 06:48:06 +0000410 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
411 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000412 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000413 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000414 uint64_t Index = ByteOffset / EltSize;
415 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000416 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000417 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000418 NumElts = AT->getNumElements();
419 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000420 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000421
Chris Lattner67058832012-01-25 06:48:06 +0000422 for (; Index != NumElts; ++Index) {
423 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000424 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000425 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000426
427 uint64_t BytesWritten = EltSize - Offset;
428 assert(BytesWritten <= EltSize && "Not indexing into this element?");
429 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000430 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000431
Chris Lattner67058832012-01-25 06:48:06 +0000432 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000433 BytesLeft -= BytesWritten;
434 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000435 }
436 return true;
437 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000438
David Majnemer90a97042016-07-13 04:22:12 +0000439 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000440 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000441 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000442 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000443 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000444 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000445 }
446
Chris Lattnered00b802009-10-23 06:23:49 +0000447 // Otherwise, unknown initializer type.
448 return false;
449}
450
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000451Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
452 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000453 auto *PTy = cast<PointerType>(C->getType());
454 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000455
Chris Lattnered00b802009-10-23 06:23:49 +0000456 // If this isn't an integer load we can't fold it directly.
457 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000458 unsigned AS = PTy->getAddressSpace();
459
Chris Lattnered00b802009-10-23 06:23:49 +0000460 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000461 // and then bitcast the result. This can be useful for union cases. Note
462 // that address spaces don't matter here since we're not going to result in
463 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000464 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000465 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000466 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000467 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000468 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000469 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000470 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000471 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000472 MapTy = PointerType::getIntNTy(C->getContext(),
473 DL.getTypeAllocSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000474 } else
Craig Topper9f008862014-04-15 04:59:12 +0000475 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000476
Eduard Burtescu14239212016-01-22 01:17:26 +0000477 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
478 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000479 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000480 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000481 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000482
Chris Lattnered00b802009-10-23 06:23:49 +0000483 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000484 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000485 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000486
Chris Lattnered00b802009-10-23 06:23:49 +0000487 GlobalValue *GVal;
David Majnemerf89660a2016-07-13 23:33:07 +0000488 APInt OffsetAI;
489 if (!IsConstantOffsetFromGlobal(C, GVal, OffsetAI, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000490 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000491
David Majnemer90a97042016-07-13 04:22:12 +0000492 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000493 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000494 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000495 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000496
David Majnemerf89660a2016-07-13 23:33:07 +0000497 int64_t Offset = OffsetAI.getSExtValue();
498 int64_t InitializerSize = DL.getTypeAllocSize(GV->getInitializer()->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000499
Chris Lattnered00b802009-10-23 06:23:49 +0000500 // If we're not accessing anything in this constant, the result is undefined.
David Majnemerf89660a2016-07-13 23:33:07 +0000501 if (Offset + BytesLoaded <= 0)
502 return UndefValue::get(IntType);
503
504 // If we're not accessing anything in this constant, the result is undefined.
505 if (Offset >= InitializerSize)
Chris Lattnered00b802009-10-23 06:23:49 +0000506 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000507
Chris Lattner59f94c02009-10-23 06:50:36 +0000508 unsigned char RawBytes[32] = {0};
David Majnemerf89660a2016-07-13 23:33:07 +0000509 unsigned char *CurPtr = RawBytes;
510 unsigned BytesLeft = BytesLoaded;
511
512 // If we're loading off the beginning of the global, some bytes may be valid.
513 if (Offset < 0) {
514 CurPtr += -Offset;
515 BytesLeft += Offset;
516 Offset = 0;
517 }
518
519 if (!ReadDataFromGlobal(GV->getInitializer(), Offset, CurPtr, BytesLeft, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000520 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000521
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000522 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000523 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000524 ResultVal = RawBytes[BytesLoaded - 1];
525 for (unsigned i = 1; i != BytesLoaded; ++i) {
526 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000527 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000528 }
529 } else {
530 ResultVal = RawBytes[0];
531 for (unsigned i = 1; i != BytesLoaded; ++i) {
532 ResultVal <<= 8;
533 ResultVal |= RawBytes[i];
534 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000535 }
Chris Lattnered00b802009-10-23 06:23:49 +0000536
Chris Lattner59f94c02009-10-23 06:50:36 +0000537 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000538}
539
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000540Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
541 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000542 auto *SrcPtr = CE->getOperand(0);
543 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
544 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000545 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000546 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000547
Eduard Burtescu14239212016-01-22 01:17:26 +0000548 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000549 if (!C)
550 return nullptr;
551
552 do {
553 Type *SrcTy = C->getType();
554
555 // If the type sizes are the same and a cast is legal, just directly
556 // cast the constant.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000557 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
Chandler Carrutha0e56952014-05-15 09:56:28 +0000558 Instruction::CastOps Cast = Instruction::BitCast;
559 // If we are going from a pointer to int or vice versa, we spell the cast
560 // differently.
561 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
562 Cast = Instruction::IntToPtr;
563 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
564 Cast = Instruction::PtrToInt;
565
566 if (CastInst::castIsValid(Cast, C, DestTy))
567 return ConstantExpr::getCast(Cast, C, DestTy);
568 }
569
570 // If this isn't an aggregate type, there is nothing we can do to drill down
571 // and find a bitcastable constant.
572 if (!SrcTy->isAggregateType())
573 return nullptr;
574
575 // We're simulating a load through a pointer that was bitcast to point to
576 // a different type, so we can try to walk down through the initial
577 // elements of an aggregate to see if some part of th e aggregate is
578 // castable to implement the "load" semantic model.
579 C = C->getAggregateElement(0u);
580 } while (C);
581
582 return nullptr;
583}
584
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000585} // end anonymous namespace
586
Eduard Burtescu14239212016-01-22 01:17:26 +0000587Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000588 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000589 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000590 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000591 if (GV->isConstant() && GV->hasDefinitiveInitializer())
592 return GV->getInitializer();
593
David Majnemered9abe12015-07-22 22:29:30 +0000594 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000595 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000596 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000597
Chris Lattnercf7e8942009-10-22 06:44:07 +0000598 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000599 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000600 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000601 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000602
Chris Lattnercf7e8942009-10-22 06:44:07 +0000603 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000604 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000605 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000606 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000607 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
608 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000609 }
610 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000611 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000612
Chandler Carrutha0e56952014-05-15 09:56:28 +0000613 if (CE->getOpcode() == Instruction::BitCast)
Eduard Burtescu14239212016-01-22 01:17:26 +0000614 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000615 return LoadedC;
616
Chris Lattnercf7e8942009-10-22 06:44:07 +0000617 // Instead of loading constant c string, use corresponding integer value
618 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000619 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000620 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000621 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000622 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000623 // Replace load with immediate integer if the result is an integer or fp
624 // value.
625 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000626 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000627 APInt StrVal(NumBits, 0);
628 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000629 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000630 for (unsigned char C : reverse(Str.bytes())) {
631 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000632 StrVal = (StrVal << 8) | SingleChar;
633 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000634 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000635 for (unsigned char C : Str.bytes()) {
636 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000637 StrVal = (StrVal << 8) | SingleChar;
638 }
639 // Append NULL at the end.
640 SingleChar = 0;
641 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000642 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000643
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000644 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
645 if (Ty->isFloatingPointTy())
646 Res = ConstantExpr::getBitCast(Res, Ty);
647 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000648 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000649 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000650
Chris Lattnercf7e8942009-10-22 06:44:07 +0000651 // If this load comes from anywhere in a constant global, and if the global
652 // is all undef or zero, we know what it loads.
David Majnemer90a97042016-07-13 04:22:12 +0000653 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000654 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000655 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000656 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000657 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000658 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000659 }
660 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000661
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000662 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000663 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000664}
665
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000666namespace {
667
668Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000669 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000670
David Majnemer90a97042016-07-13 04:22:12 +0000671 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000672 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000673
Craig Topper9f008862014-04-15 04:59:12 +0000674 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000675}
Chris Lattner44d68b92007-01-31 00:51:48 +0000676
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000677/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000678/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000679/// these together. If target data info is available, it is provided as DL,
680/// otherwise DL is null.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000681Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
682 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000683 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000684
Chris Lattner44d68b92007-01-31 00:51:48 +0000685 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
686 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
687 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000688
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000689 if (Opc == Instruction::And) {
Craig Topper8205a1a2017-05-24 16:53:07 +0000690 KnownBits Known0 = computeKnownBits(Op0, DL);
691 KnownBits Known1 = computeKnownBits(Op1, DL);
Craig Topperb45eabc2017-04-26 16:39:58 +0000692 if ((Known1.One | Known0.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-02-14 03:23:37 +0000693 // All the bits of Op0 that the 'and' could be masking are already zero.
694 return Op0;
695 }
Craig Topperb45eabc2017-04-26 16:39:58 +0000696 if ((Known0.One | Known1.Zero).isAllOnesValue()) {
Nick Lewycky06417742013-02-14 03:23:37 +0000697 // All the bits of Op1 that the 'and' could be masking are already zero.
698 return Op1;
699 }
700
Craig Topper8189a872017-05-03 23:12:29 +0000701 Known0.Zero |= Known1.Zero;
702 Known0.One &= Known1.One;
703 if (Known0.isConstant())
704 return ConstantInt::get(Op0->getType(), Known0.getConstant());
Nick Lewycky06417742013-02-14 03:23:37 +0000705 }
706
Chris Lattner44d68b92007-01-31 00:51:48 +0000707 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
708 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000709 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000710 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000711 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000712
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000713 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
714 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
715 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000716
Chris Lattner44d68b92007-01-31 00:51:48 +0000717 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000718 // PtrToInt may change the bitwidth so we have convert to the right size
719 // first.
720 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
721 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000722 }
723 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000724
Craig Topper9f008862014-04-15 04:59:12 +0000725 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000726}
727
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000728/// If array indices are not pointer-sized integers, explicitly cast them so
729/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000730Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
Peter Collingbourned93620b2016-11-10 22:34:55 +0000731 Type *ResultTy, Optional<unsigned> InRangeIndex,
732 const DataLayout &DL, const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000733 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Keno Fischerdc091192016-12-08 17:22:35 +0000734 Type *IntPtrScalarTy = IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000735
736 bool Any = false;
737 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000738 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000739 if ((i == 1 ||
Keno Fischerdc091192016-12-08 17:22:35 +0000740 !isa<StructType>(GetElementPtrInst::getIndexedType(
741 SrcElemTy, Ops.slice(1, i - 1)))) &&
Michael Kupersteindd92c782016-12-21 17:34:21 +0000742 Ops[i]->getType()->getScalarType() != IntPtrScalarTy) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000743 Any = true;
Michael Kupersteindd92c782016-12-21 17:34:21 +0000744 Type *NewType = Ops[i]->getType()->isVectorTy()
745 ? IntPtrTy
746 : IntPtrTy->getScalarType();
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000747 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
748 true,
Michael Kupersteindd92c782016-12-21 17:34:21 +0000749 NewType,
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000750 true),
Michael Kupersteindd92c782016-12-21 17:34:21 +0000751 Ops[i], NewType));
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000752 } else
753 NewIdxs.push_back(Ops[i]);
754 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000755
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000756 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000757 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000758
Peter Collingbourned93620b2016-11-10 22:34:55 +0000759 Constant *C = ConstantExpr::getGetElementPtr(
760 SrcElemTy, Ops[0], NewIdxs, /*InBounds=*/false, InRangeIndex);
David Majnemerd536f232016-07-29 03:27:26 +0000761 if (Constant *Folded = ConstantFoldConstant(C, DL, TLI))
762 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000763
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000764 return C;
765}
766
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000767/// Strip the pointer casts, but preserve the address space information.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000768Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000769 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000770 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000771 Ptr = Ptr->stripPointerCasts();
David Majnemer90a97042016-07-13 04:22:12 +0000772 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000773
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000774 ElemTy = NewPtrTy->getPointerElementType();
775
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000776 // Preserve the address space number of the pointer.
777 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000778 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000779 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000780 }
781 return Ptr;
782}
783
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000784/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000785Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
786 ArrayRef<Constant *> Ops,
787 const DataLayout &DL,
788 const TargetLibraryInfo *TLI) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000789 const GEPOperator *InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000790 bool InBounds = GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000791
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000792 Type *SrcElemTy = GEP->getSourceElementType();
793 Type *ResElemTy = GEP->getResultElementType();
794 Type *ResTy = GEP->getType();
795 if (!SrcElemTy->isSized())
796 return nullptr;
797
Peter Collingbourned93620b2016-11-10 22:34:55 +0000798 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy,
799 GEP->getInRangeIndex(), DL, TLI))
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000800 return C;
801
Chris Lattner44d68b92007-01-31 00:51:48 +0000802 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000803 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000804 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000805
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000806 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000807
808 // If this is a constant expr gep that is effectively computing an
809 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000810 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000811 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000812
Chris Lattner5858e092011-01-06 06:19:46 +0000813 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
814 // "inttoptr (sub (ptrtoint Ptr), V)"
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000815 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
David Majnemer90a97042016-07-13 04:22:12 +0000816 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000817 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000818 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000819 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000820 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000821 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
822 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000823 Res = ConstantExpr::getIntToPtr(Res, ResTy);
David Majnemerd536f232016-07-29 03:27:26 +0000824 if (auto *FoldedRes = ConstantFoldConstant(Res, DL, TLI))
825 Res = FoldedRes;
Chris Lattner5858e092011-01-06 06:19:46 +0000826 return Res;
827 }
828 }
Craig Topper9f008862014-04-15 04:59:12 +0000829 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000830 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000831
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000832 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000833 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000834 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000835 DL.getIndexedOffsetInType(
836 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000837 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000838 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000839
840 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000841 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Peter Collingbourned93620b2016-11-10 22:34:55 +0000842 InnermostGEP = GEP;
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000843 InBounds &= GEP->isInBounds();
Peter Collingbourned93620b2016-11-10 22:34:55 +0000844
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000845 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000846
847 // Do not try the incorporate the sub-GEP if some index is not a number.
848 bool AllConstantInt = true;
David Majnemer90a97042016-07-13 04:22:12 +0000849 for (Value *NestedOp : NestedOps)
850 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000851 AllConstantInt = false;
852 break;
853 }
854 if (!AllConstantInt)
855 break;
856
Dan Gohman474e488c2010-03-10 19:31:51 +0000857 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000858 SrcElemTy = GEP->getSourceElementType();
859 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000860 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000861 }
862
Dan Gohman81ce8422009-08-19 18:18:36 +0000863 // If the base value for this address is a literal integer value, fold the
864 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000865 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000866 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000867 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000868 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000869 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000870 }
871 }
872
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000873 auto *PTy = cast<PointerType>(Ptr->getType());
874 if ((Ptr->isNullValue() || BasePtr != 0) &&
875 !DL.isNonIntegralPointerType(PTy)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000876 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000877 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-08-19 18:18:36 +0000878 }
879
880 // Otherwise form a regular getelementptr. Recompute the indices so that
881 // we eliminate over-indexing of the notional static type array bounds.
882 // This makes it easy to determine if the getelementptr is "inbounds".
883 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Sanjoy Das6fa08aa2016-08-05 19:23:29 +0000884 Type *Ty = PTy;
Matt Arsenault7a960a82013-08-20 21:20:04 +0000885 SmallVector<Constant *, 32> NewIdxs;
886
Dan Gohmanc59ba422009-08-19 22:46:59 +0000887 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000888 if (!Ty->isStructTy()) {
889 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000890 // The only pointer indexing we'll do is on the first index of the GEP.
891 if (!NewIdxs.empty())
892 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000893
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000894 Ty = SrcElemTy;
895
Chris Lattner77c36d62009-12-03 01:05:45 +0000896 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000897 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000898 return nullptr;
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000899 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
900 Ty = ATy->getElementType();
901 } else {
902 // We've reached some non-indexable type.
903 break;
Chris Lattner77c36d62009-12-03 01:05:45 +0000904 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000905
Dan Gohman81ce8422009-08-19 18:18:36 +0000906 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000907 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
David Majnemer1b3db332016-07-13 05:16:16 +0000908 if (ElemSize == 0) {
Chris Lattner6ce03802010-11-21 08:39:01 +0000909 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000910 // index for this level and proceed to the next level to see if it can
911 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000912 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
David Majnemer1b3db332016-07-13 05:16:16 +0000913 } else {
Chris Lattner6ce03802010-11-21 08:39:01 +0000914 // The element size is non-zero divide the offset by the element
915 // size (rounding down), to compute the index at this level.
David Majnemer4cff2f82016-07-13 15:53:46 +0000916 bool Overflow;
917 APInt NewIdx = Offset.sdiv_ov(ElemSize, Overflow);
918 if (Overflow)
919 break;
Chris Lattner6ce03802010-11-21 08:39:01 +0000920 Offset -= NewIdx * ElemSize;
921 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
922 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000923 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000924 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000925 // If we end up with an offset that isn't valid for this struct type, we
926 // can't re-form this GEP in a regular form, so bail out. The pointer
927 // operand likely went through casts that are necessary to make the GEP
928 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000929 const StructLayout &SL = *DL.getStructLayout(STy);
David Majnemer1b3db332016-07-13 05:16:16 +0000930 if (Offset.isNegative() || Offset.uge(SL.getSizeInBytes()))
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000931 break;
932
933 // Determine which field of the struct the offset points into. The
934 // getZExtValue is fine as we've already ensured that the offset is
935 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000936 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000937 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
938 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000939 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000940 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000941 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000942 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000943
944 // If we haven't used up the entire offset by descending the static
945 // type, then the offset is pointing into the middle of an indivisible
946 // member, so we can't simplify it.
947 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000948 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000949
Peter Collingbourned93620b2016-11-10 22:34:55 +0000950 // Preserve the inrange index from the innermost GEP if possible. We must
951 // have calculated the same indices up to and including the inrange index.
952 Optional<unsigned> InRangeIndex;
953 if (Optional<unsigned> LastIRIndex = InnermostGEP->getInRangeIndex())
954 if (SrcElemTy == InnermostGEP->getSourceElementType() &&
955 NewIdxs.size() > *LastIRIndex) {
956 InRangeIndex = LastIRIndex;
957 for (unsigned I = 0; I <= *LastIRIndex; ++I)
958 if (NewIdxs[I] != InnermostGEP->getOperand(I + 1)) {
959 InRangeIndex = None;
960 break;
961 }
962 }
963
Dan Gohman21c62162009-09-11 00:04:14 +0000964 // Create a GEP.
Peter Collingbourne0a4fc462016-11-22 01:03:40 +0000965 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs,
966 InBounds, InRangeIndex);
Matt Arsenault8c789092013-08-12 23:15:58 +0000967 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000968 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000969
Dan Gohmanc59ba422009-08-19 22:46:59 +0000970 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000971 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000972 if (Ty != ResElemTy)
973 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000974
975 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000976}
977
Manuel Jacobe9024592016-01-21 06:33:22 +0000978/// Attempt to constant fold an instruction with the
979/// specified opcode and operands. If successful, the constant result is
980/// returned, if not, null is returned. Note that this function can fail when
981/// attempting to fold instructions like loads and stores, which have no
982/// constant expression form.
983///
Peter Collingbourned93620b2016-11-10 22:34:55 +0000984/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/inrange
985/// etc information, due to only being passed an opcode and operands. Constant
Manuel Jacobe9024592016-01-21 06:33:22 +0000986/// folding using this function strips this information.
987///
David Majnemera926b3e2016-07-29 03:27:33 +0000988Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, unsigned Opcode,
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000989 ArrayRef<Constant *> Ops,
990 const DataLayout &DL,
991 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +0000992 Type *DestTy = InstOrCE->getType();
993
Manuel Jacobe9024592016-01-21 06:33:22 +0000994 // Handle easy binops first.
995 if (Instruction::isBinaryOp(Opcode))
996 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
997
998 if (Instruction::isCast(Opcode))
999 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
1000
David Majnemer17bdf442016-07-13 03:42:38 +00001001 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001002 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
1003 return C;
1004
Peter Collingbourned93620b2016-11-10 22:34:55 +00001005 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), Ops[0],
1006 Ops.slice(1), GEP->isInBounds(),
1007 GEP->getInRangeIndex());
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001008 }
1009
David Majnemer57b94c82016-07-29 03:27:31 +00001010 if (auto *CE = dyn_cast<ConstantExpr>(InstOrCE))
1011 return CE->getWithOperands(Ops);
1012
Manuel Jacobe9024592016-01-21 06:33:22 +00001013 switch (Opcode) {
1014 default: return nullptr;
1015 case Instruction::ICmp:
1016 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
1017 case Instruction::Call:
Andrew Kaylor647025f2017-06-09 23:18:11 +00001018 if (auto *F = dyn_cast<Function>(Ops.back())) {
1019 ImmutableCallSite CS(cast<CallInst>(InstOrCE));
1020 if (canConstantFoldCallTo(CS, F))
1021 return ConstantFoldCall(CS, F, Ops.slice(0, Ops.size() - 1), TLI);
1022 }
Manuel Jacobe9024592016-01-21 06:33:22 +00001023 return nullptr;
1024 case Instruction::Select:
1025 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
1026 case Instruction::ExtractElement:
1027 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
1028 case Instruction::InsertElement:
1029 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
1030 case Instruction::ShuffleVector:
1031 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +00001032 }
1033}
1034
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001035} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +00001036
1037//===----------------------------------------------------------------------===//
1038// Constant Folding public APIs
1039//===----------------------------------------------------------------------===//
1040
David Majnemerd536f232016-07-29 03:27:26 +00001041namespace {
1042
1043Constant *
1044ConstantFoldConstantImpl(const Constant *C, const DataLayout &DL,
1045 const TargetLibraryInfo *TLI,
1046 SmallDenseMap<Constant *, Constant *> &FoldedOps) {
1047 if (!isa<ConstantVector>(C) && !isa<ConstantExpr>(C))
1048 return nullptr;
1049
1050 SmallVector<Constant *, 8> Ops;
1051 for (const Use &NewU : C->operands()) {
1052 auto *NewC = cast<Constant>(&NewU);
1053 // Recursively fold the ConstantExpr's operands. If we have already folded
1054 // a ConstantExpr, we don't have to process it again.
1055 if (isa<ConstantVector>(NewC) || isa<ConstantExpr>(NewC)) {
1056 auto It = FoldedOps.find(NewC);
1057 if (It == FoldedOps.end()) {
1058 if (auto *FoldedC =
1059 ConstantFoldConstantImpl(NewC, DL, TLI, FoldedOps)) {
David Majnemerd536f232016-07-29 03:27:26 +00001060 FoldedOps.insert({NewC, FoldedC});
David Greenda211702017-03-21 10:17:39 +00001061 NewC = FoldedC;
David Majnemerd536f232016-07-29 03:27:26 +00001062 } else {
1063 FoldedOps.insert({NewC, NewC});
1064 }
1065 } else {
1066 NewC = It->second;
1067 }
1068 }
1069 Ops.push_back(NewC);
1070 }
1071
1072 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1073 if (CE->isCompare())
1074 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
1075 DL, TLI);
1076
David Majnemera926b3e2016-07-29 03:27:33 +00001077 return ConstantFoldInstOperandsImpl(CE, CE->getOpcode(), Ops, DL, TLI);
David Majnemerd536f232016-07-29 03:27:26 +00001078 }
1079
1080 assert(isa<ConstantVector>(C));
1081 return ConstantVector::get(Ops);
1082}
1083
1084} // end anonymous namespace
1085
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001086Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001087 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +00001088 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +00001089 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +00001090 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +00001091
David Majnemerd536f232016-07-29 03:27:26 +00001092 SmallDenseMap<Constant *, Constant *> FoldedOps;
Pete Cooper833f34d2015-05-12 20:05:31 +00001093 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +00001094 // If the incoming value is undef then skip it. Note that while we could
1095 // skip the value if it is equal to the phi node itself we choose not to
1096 // because that would break the rule that constant folding only applies if
1097 // all operands are constants.
1098 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +00001099 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001100 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +00001101 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001102 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +00001103 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001104 // Fold the PHI's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001105 if (auto *FoldedC = ConstantFoldConstantImpl(C, DL, TLI, FoldedOps))
1106 C = FoldedC;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001107 // If the incoming value is a different constant to
1108 // the one we saw previously, then give up.
1109 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +00001110 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +00001111 CommonValue = C;
1112 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001113
Duncan Sands1d27f0122010-11-14 12:53:18 +00001114 // If we reach here, all incoming values are the same constant or undef.
1115 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +00001116 }
1117
1118 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +00001119 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001120 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
1121 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +00001122
David Majnemerd536f232016-07-29 03:27:26 +00001123 SmallDenseMap<Constant *, Constant *> FoldedOps;
Fiona Glaser2e5c0c22016-03-13 05:36:15 +00001124 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001125 for (const Use &OpU : I->operands()) {
1126 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001127 // Fold the Instruction's operands.
David Majnemerd536f232016-07-29 03:27:26 +00001128 if (auto *FoldedOp = ConstantFoldConstantImpl(Op, DL, TLI, FoldedOps))
1129 Op = FoldedOp;
Dan Gohman1ccecdb2012-04-27 17:50:22 +00001130
1131 Ops.push_back(Op);
1132 }
1133
David Majnemer90a97042016-07-13 04:22:12 +00001134 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001135 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001136 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001137
David Majnemer90a97042016-07-13 04:22:12 +00001138 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001139 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001140
David Majnemer90a97042016-07-13 04:22:12 +00001141 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001142 return ConstantExpr::getInsertValue(
1143 cast<Constant>(IVI->getAggregateOperand()),
1144 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001145 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001146 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001147
David Majnemer90a97042016-07-13 04:22:12 +00001148 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001149 return ConstantExpr::getExtractValue(
1150 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001151 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001152 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001153
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001154 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001155}
1156
David Majnemerd536f232016-07-29 03:27:26 +00001157Constant *llvm::ConstantFoldConstant(const Constant *C, const DataLayout &DL,
1158 const TargetLibraryInfo *TLI) {
1159 SmallDenseMap<Constant *, Constant *> FoldedOps;
1160 return ConstantFoldConstantImpl(C, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001161}
1162
Manuel Jacobe9024592016-01-21 06:33:22 +00001163Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001164 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001165 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001166 const TargetLibraryInfo *TLI) {
David Majnemera926b3e2016-07-29 03:27:33 +00001167 return ConstantFoldInstOperandsImpl(I, I->getOpcode(), Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001168}
1169
Chris Lattnerd2265b42007-12-10 22:53:04 +00001170Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001171 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001172 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001173 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001174 // fold: icmp (inttoptr x), null -> icmp x, 0
Craig Topperb23e7c72017-06-02 16:17:32 +00001175 // fold: icmp null, (inttoptr x) -> icmp 0, x
Chris Lattnerd2265b42007-12-10 22:53:04 +00001176 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Craig Topperb23e7c72017-06-02 16:17:32 +00001177 // fold: icmp 0, (ptrtoint x) -> icmp null, x
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001178 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001179 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1180 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001181 // FIXME: The following comment is out of data and the DataLayout is here now.
1182 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001183 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001184 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001185 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001186 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001187 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001188 // Convert the integer value to the right size to ensure we get the
1189 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001190 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001191 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001192 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001193 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001194 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001195
Chris Lattnerd2265b42007-12-10 22:53:04 +00001196 // Only do this transformation if the int is intptrty in size, otherwise
1197 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001198 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001199 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001200 if (CE0->getType() == IntPtrTy) {
1201 Constant *C = CE0->getOperand(0);
1202 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001203 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001204 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001205 }
1206 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001207
David Majnemer90a97042016-07-13 04:22:12 +00001208 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001209 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001210 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001211 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001212
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001213 // Convert the integer value to the right size to ensure we get the
1214 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001215 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001216 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001217 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001218 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001219 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001220 }
1221
Chandler Carruth7ec50852012-11-01 08:07:29 +00001222 // Only do this transformation if the int is intptrty in size, otherwise
1223 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001224 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001225 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001226 if (CE0->getType() == IntPtrTy &&
1227 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001228 return ConstantFoldCompareInstOperands(
1229 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001230 }
1231 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001232 }
1233 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001234
Chris Lattner8fb74c62010-01-02 01:22:23 +00001235 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1236 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1237 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1238 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001239 Constant *LHS = ConstantFoldCompareInstOperands(
1240 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1241 Constant *RHS = ConstantFoldCompareInstOperands(
1242 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001243 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001244 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001245 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001246 }
Craig Topperb23e7c72017-06-02 16:17:32 +00001247 } else if (isa<ConstantExpr>(Ops1)) {
1248 // If RHS is a constant expression, but the left side isn't, swap the
1249 // operands and try again.
1250 Predicate = ICmpInst::getSwappedPredicate((ICmpInst::Predicate)Predicate);
1251 return ConstantFoldCompareInstOperands(Predicate, Ops1, Ops0, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001252 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001253
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001254 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001255}
1256
Manuel Jacoba61ca372016-01-21 06:26:35 +00001257Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1258 Constant *RHS,
1259 const DataLayout &DL) {
1260 assert(Instruction::isBinaryOp(Opcode));
1261 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1262 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1263 return C;
1264
1265 return ConstantExpr::get(Opcode, LHS, RHS);
1266}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001267
Manuel Jacob925d0292016-01-21 06:31:08 +00001268Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1269 Type *DestTy, const DataLayout &DL) {
1270 assert(Instruction::isCast(Opcode));
1271 switch (Opcode) {
1272 default:
1273 llvm_unreachable("Missing case");
1274 case Instruction::PtrToInt:
1275 // If the input is a inttoptr, eliminate the pair. This requires knowing
1276 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001277 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001278 if (CE->getOpcode() == Instruction::IntToPtr) {
1279 Constant *Input = CE->getOperand(0);
1280 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1281 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1282 if (PtrWidth < InWidth) {
1283 Constant *Mask =
1284 ConstantInt::get(CE->getContext(),
1285 APInt::getLowBitsSet(InWidth, PtrWidth));
1286 Input = ConstantExpr::getAnd(Input, Mask);
1287 }
1288 // Do a zext or trunc to get to the dest size.
1289 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1290 }
1291 }
1292 return ConstantExpr::getCast(Opcode, C, DestTy);
1293 case Instruction::IntToPtr:
1294 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1295 // the int size is >= the ptr size and the address spaces are the same.
1296 // This requires knowing the width of a pointer, so it can't be done in
1297 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001298 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001299 if (CE->getOpcode() == Instruction::PtrToInt) {
1300 Constant *SrcPtr = CE->getOperand(0);
1301 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1302 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1303
1304 if (MidIntSize >= SrcPtrSize) {
1305 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1306 if (SrcAS == DestTy->getPointerAddressSpace())
1307 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1308 }
1309 }
1310 }
1311
1312 return ConstantExpr::getCast(Opcode, C, DestTy);
1313 case Instruction::Trunc:
1314 case Instruction::ZExt:
1315 case Instruction::SExt:
1316 case Instruction::FPTrunc:
1317 case Instruction::FPExt:
1318 case Instruction::UIToFP:
1319 case Instruction::SIToFP:
1320 case Instruction::FPToUI:
1321 case Instruction::FPToSI:
1322 case Instruction::AddrSpaceCast:
1323 return ConstantExpr::getCast(Opcode, C, DestTy);
1324 case Instruction::BitCast:
1325 return FoldBitCast(C, DestTy, DL);
1326 }
1327}
1328
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001329Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001330 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001331 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001332 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001333
1334 // Loop over all of the operands, tracking down which value we are
1335 // addressing.
1336 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1337 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001338 if (!C)
1339 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001340 }
1341 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001342}
1343
David Majnemer90a97042016-07-13 04:22:12 +00001344Constant *
1345llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1346 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001347 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001348 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001349 for (Constant *Index : Indices) {
1350 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001351 if (!C)
1352 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001353 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001354 return C;
1355}
1356
Chris Lattner2ae054a2007-01-30 23:45:45 +00001357//===----------------------------------------------------------------------===//
1358// Constant Folding for Calls
1359//
John Criswell970af112005-10-27 16:00:10 +00001360
Andrew Kaylor647025f2017-06-09 23:18:11 +00001361bool llvm::canConstantFoldCallTo(ImmutableCallSite CS, const Function *F) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00001362 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00001363 return false;
John Criswell970af112005-10-27 16:00:10 +00001364 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001365 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001366 case Intrinsic::minnum:
1367 case Intrinsic::maxnum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001368 case Intrinsic::log:
1369 case Intrinsic::log2:
1370 case Intrinsic::log10:
1371 case Intrinsic::exp:
1372 case Intrinsic::exp2:
1373 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001374 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001375 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001376 case Intrinsic::sin:
1377 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001378 case Intrinsic::trunc:
1379 case Intrinsic::rint:
1380 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001381 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001382 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001383 case Intrinsic::bswap:
1384 case Intrinsic::ctpop:
1385 case Intrinsic::ctlz:
1386 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001387 case Intrinsic::fma:
1388 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001389 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001390 case Intrinsic::round:
David Majnemer7f781ab2016-07-14 00:29:50 +00001391 case Intrinsic::masked_load:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001392 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001393 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001394 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001395 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001396 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001397 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001398 case Intrinsic::convert_from_fp16:
1399 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001400 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001401 case Intrinsic::x86_sse_cvtss2si:
1402 case Intrinsic::x86_sse_cvtss2si64:
1403 case Intrinsic::x86_sse_cvttss2si:
1404 case Intrinsic::x86_sse_cvttss2si64:
1405 case Intrinsic::x86_sse2_cvtsd2si:
1406 case Intrinsic::x86_sse2_cvtsd2si64:
1407 case Intrinsic::x86_sse2_cvttsd2si:
1408 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001409 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001410 default:
1411 return false;
Craig Topper492db482017-04-07 21:36:32 +00001412 case Intrinsic::not_intrinsic: break;
John Criswell970af112005-10-27 16:00:10 +00001413 }
1414
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001415 if (!F->hasName())
1416 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001417 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001418
Chris Lattner785f9982007-08-08 06:55:43 +00001419 // In these cases, the check of the length is required. We don't want to
1420 // return true for a name like "cos\0blah" which strcmp would return equal to
1421 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001422 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001423 default:
1424 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001425 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001426 return Name == "acos" || Name == "asin" || Name == "atan" ||
1427 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1428 Name == "atanf" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001429 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001430 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1431 Name == "ceilf" || Name == "cosf" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001432 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001433 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001434 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001435 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1436 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001437 case 'l':
Xin Tongc063c3f2017-10-01 00:09:53 +00001438 return Name == "log" || Name == "log10" || Name == "logf" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001439 Name == "log10f";
Chris Lattner785f9982007-08-08 06:55:43 +00001440 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001441 return Name == "pow" || Name == "powf";
Bryant Wongb5e03b62016-12-26 14:29:29 +00001442 case 'r':
1443 return Name == "round" || Name == "roundf";
Chris Lattner785f9982007-08-08 06:55:43 +00001444 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001445 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001446 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001447 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001448 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001449 case '_':
1450
1451 // Check for various function names that get used for the math functions
1452 // when the header files are preprocessed with the macro
1453 // __FINITE_MATH_ONLY__ enabled.
1454 // The '12' here is the length of the shortest name that can match.
1455 // We need to check the size before looking at Name[1] and Name[2]
1456 // so we may as well check a limit that will eliminate mismatches.
1457 if (Name.size() < 12 || Name[1] != '_')
1458 return false;
1459 switch (Name[2]) {
1460 default:
1461 return false;
1462 case 'a':
1463 return Name == "__acos_finite" || Name == "__acosf_finite" ||
1464 Name == "__asin_finite" || Name == "__asinf_finite" ||
1465 Name == "__atan2_finite" || Name == "__atan2f_finite";
1466 case 'c':
1467 return Name == "__cosh_finite" || Name == "__coshf_finite";
1468 case 'e':
1469 return Name == "__exp_finite" || Name == "__expf_finite" ||
1470 Name == "__exp2_finite" || Name == "__exp2f_finite";
1471 case 'l':
1472 return Name == "__log_finite" || Name == "__logf_finite" ||
1473 Name == "__log10_finite" || Name == "__log10f_finite";
1474 case 'p':
1475 return Name == "__pow_finite" || Name == "__powf_finite";
1476 case 's':
1477 return Name == "__sinh_finite" || Name == "__sinhf_finite";
1478 }
John Criswell970af112005-10-27 16:00:10 +00001479 }
1480}
1481
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001482namespace {
1483
1484Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001485 if (Ty->isHalfTy()) {
1486 APFloat APF(V);
1487 bool unused;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001488 APF.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &unused);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001489 return ConstantFP::get(Ty->getContext(), APF);
1490 }
Chris Lattner351534f2009-10-05 05:06:24 +00001491 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001492 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001493 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001494 return ConstantFP::get(Ty->getContext(), APFloat(V));
Xin Tongc063c3f2017-10-01 00:09:53 +00001495 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001496}
1497
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001498/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001499inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001500#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001501 feclearexcept(FE_ALL_EXCEPT);
1502#endif
1503 errno = 0;
1504}
1505
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001506/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001507inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001508 int errno_val = errno;
1509 if (errno_val == ERANGE || errno_val == EDOM)
1510 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001511#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001512 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1513 return true;
1514#endif
1515 return false;
1516}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001517
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001518Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001519 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001520 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001521 if (llvm_fenv_testexcept()) {
1522 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001523 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001524 }
1525
1526 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001527}
1528
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001529Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1530 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001531 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001532 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001533 if (llvm_fenv_testexcept()) {
1534 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001535 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001536 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001537
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001538 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001539}
1540
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001541/// Attempt to fold an SSE floating point to integer conversion of a constant
1542/// floating point. If roundTowardZero is false, the default IEEE rounding is
1543/// used (toward nearest, ties to even). This matches the behavior of the
1544/// non-truncating SSE instructions in the default rounding mode. The desired
1545/// integer type Ty is used to select how many bits are available for the
1546/// result. Returns null if the conversion cannot be performed, otherwise
1547/// returns the Constant value resulting from the conversion.
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001548Constant *ConstantFoldSSEConvertToInt(const APFloat &Val, bool roundTowardZero,
1549 Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001550 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001551 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001552 assert(ResultWidth <= 64 &&
1553 "Can only constant fold conversions to 64 and 32 bit ints");
1554
1555 uint64_t UIntVal;
1556 bool isExact = false;
1557 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1558 : APFloat::rmNearestTiesToEven;
Simon Pilgrim00b34992017-03-20 14:40:12 +00001559 APFloat::opStatus status =
1560 Val.convertToInteger(makeMutableArrayRef(UIntVal), ResultWidth,
1561 /*isSigned=*/true, mode, &isExact);
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001562 if (status != APFloat::opOK &&
1563 (!roundTowardZero || status != APFloat::opInexact))
Craig Topper9f008862014-04-15 04:59:12 +00001564 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001565 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1566}
1567
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001568double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001569 Type *Ty = Op->getType();
1570
1571 if (Ty->isFloatTy())
1572 return Op->getValueAPF().convertToFloat();
1573
1574 if (Ty->isDoubleTy())
1575 return Op->getValueAPF().convertToDouble();
1576
1577 bool unused;
1578 APFloat APF = Op->getValueAPF();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001579 APF.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &unused);
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001580 return APF.convertToDouble();
1581}
1582
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001583Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1584 ArrayRef<Constant *> Operands,
1585 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001586 if (Operands.size() == 1) {
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001587 if (isa<UndefValue>(Operands[0])) {
1588 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1589 if (IntrinsicID == Intrinsic::cos)
1590 return Constant::getNullValue(Ty);
Craig Topperd470d732017-06-04 08:21:53 +00001591 if (IntrinsicID == Intrinsic::bswap ||
1592 IntrinsicID == Intrinsic::bitreverse)
1593 return Operands[0];
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001594 }
David Majnemer90a97042016-07-13 04:22:12 +00001595 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001596 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001597 APFloat Val(Op->getValueAPF());
1598
1599 bool lost = false;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001600 Val.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001601
Benjamin Kramer061d1472014-03-05 19:41:48 +00001602 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001603 }
1604
Xin Tongc063c3f2017-10-01 00:09:53 +00001605 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001606 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001607
Karthik Bhatb67688a2014-03-07 04:36:21 +00001608 if (IntrinsicID == Intrinsic::round) {
1609 APFloat V = Op->getValueAPF();
1610 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1611 return ConstantFP::get(Ty->getContext(), V);
1612 }
1613
Karthik Bhatd818e382015-07-21 08:52:23 +00001614 if (IntrinsicID == Intrinsic::floor) {
1615 APFloat V = Op->getValueAPF();
1616 V.roundToIntegral(APFloat::rmTowardNegative);
1617 return ConstantFP::get(Ty->getContext(), V);
1618 }
1619
1620 if (IntrinsicID == Intrinsic::ceil) {
1621 APFloat V = Op->getValueAPF();
1622 V.roundToIntegral(APFloat::rmTowardPositive);
1623 return ConstantFP::get(Ty->getContext(), V);
1624 }
1625
1626 if (IntrinsicID == Intrinsic::trunc) {
1627 APFloat V = Op->getValueAPF();
1628 V.roundToIntegral(APFloat::rmTowardZero);
1629 return ConstantFP::get(Ty->getContext(), V);
1630 }
1631
1632 if (IntrinsicID == Intrinsic::rint) {
1633 APFloat V = Op->getValueAPF();
1634 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1635 return ConstantFP::get(Ty->getContext(), V);
1636 }
1637
1638 if (IntrinsicID == Intrinsic::nearbyint) {
1639 APFloat V = Op->getValueAPF();
1640 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1641 return ConstantFP::get(Ty->getContext(), V);
1642 }
1643
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001644 /// We only fold functions with finite arguments. Folding NaN and inf is
1645 /// likely to be aborted with an exception anyway, and some host libms
1646 /// have known errors raising exceptions.
1647 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001648 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001649
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001650 /// Currently APFloat versions of these functions do not exist, so we use
1651 /// the host native double versions. Float versions are not called
1652 /// directly but for all these it is true (float)(f((double)arg)) ==
1653 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001654 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001655
Benjamin Kramer061d1472014-03-05 19:41:48 +00001656 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001657 default: break;
1658 case Intrinsic::fabs:
1659 return ConstantFoldFP(fabs, V, Ty);
1660 case Intrinsic::log2:
Vince Harrond5281122015-05-07 00:05:26 +00001661 return ConstantFoldFP(Log2, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001662 case Intrinsic::log:
1663 return ConstantFoldFP(log, V, Ty);
1664 case Intrinsic::log10:
1665 return ConstantFoldFP(log10, V, Ty);
1666 case Intrinsic::exp:
1667 return ConstantFoldFP(exp, V, Ty);
1668 case Intrinsic::exp2:
1669 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001670 case Intrinsic::sin:
1671 return ConstantFoldFP(sin, V, Ty);
1672 case Intrinsic::cos:
1673 return ConstantFoldFP(cos, V, Ty);
Justin Lebar8b18a342017-01-21 00:59:57 +00001674 case Intrinsic::sqrt:
1675 return ConstantFoldFP(sqrt, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001676 }
1677
Benjamin Kramer061d1472014-03-05 19:41:48 +00001678 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001679 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001680
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001681 char NameKeyChar = Name[0];
1682 if (Name[0] == '_' && Name.size() > 2 && Name[1] == '_')
1683 NameKeyChar = Name[2];
1684
1685 switch (NameKeyChar) {
Chris Lattner785f9982007-08-08 06:55:43 +00001686 case 'a':
David L. Jonesd21529f2017-01-23 23:16:46 +00001687 if ((Name == "acos" && TLI->has(LibFunc_acos)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001688 (Name == "acosf" && TLI->has(LibFunc_acosf)) ||
1689 (Name == "__acos_finite" && TLI->has(LibFunc_acos_finite)) ||
1690 (Name == "__acosf_finite" && TLI->has(LibFunc_acosf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001691 return ConstantFoldFP(acos, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001692 else if ((Name == "asin" && TLI->has(LibFunc_asin)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001693 (Name == "asinf" && TLI->has(LibFunc_asinf)) ||
1694 (Name == "__asin_finite" && TLI->has(LibFunc_asin_finite)) ||
1695 (Name == "__asinf_finite" && TLI->has(LibFunc_asinf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001696 return ConstantFoldFP(asin, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001697 else if ((Name == "atan" && TLI->has(LibFunc_atan)) ||
1698 (Name == "atanf" && TLI->has(LibFunc_atanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001699 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001700 break;
1701 case 'c':
David L. Jonesd21529f2017-01-23 23:16:46 +00001702 if ((Name == "ceil" && TLI->has(LibFunc_ceil)) ||
1703 (Name == "ceilf" && TLI->has(LibFunc_ceilf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001704 return ConstantFoldFP(ceil, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001705 else if ((Name == "cos" && TLI->has(LibFunc_cos)) ||
1706 (Name == "cosf" && TLI->has(LibFunc_cosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001707 return ConstantFoldFP(cos, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001708 else if ((Name == "cosh" && TLI->has(LibFunc_cosh)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001709 (Name == "coshf" && TLI->has(LibFunc_coshf)) ||
1710 (Name == "__cosh_finite" && TLI->has(LibFunc_cosh_finite)) ||
1711 (Name == "__coshf_finite" && TLI->has(LibFunc_coshf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001712 return ConstantFoldFP(cosh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001713 break;
1714 case 'e':
David L. Jonesd21529f2017-01-23 23:16:46 +00001715 if ((Name == "exp" && TLI->has(LibFunc_exp)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001716 (Name == "expf" && TLI->has(LibFunc_expf)) ||
1717 (Name == "__exp_finite" && TLI->has(LibFunc_exp_finite)) ||
1718 (Name == "__expf_finite" && TLI->has(LibFunc_expf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001719 return ConstantFoldFP(exp, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001720 if ((Name == "exp2" && TLI->has(LibFunc_exp2)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001721 (Name == "exp2f" && TLI->has(LibFunc_exp2f)) ||
1722 (Name == "__exp2_finite" && TLI->has(LibFunc_exp2_finite)) ||
1723 (Name == "__exp2f_finite" && TLI->has(LibFunc_exp2f_finite)))
Chris Lattner713d5232011-05-22 22:22:35 +00001724 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1725 // C99 library.
1726 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001727 break;
1728 case 'f':
David L. Jonesd21529f2017-01-23 23:16:46 +00001729 if ((Name == "fabs" && TLI->has(LibFunc_fabs)) ||
1730 (Name == "fabsf" && TLI->has(LibFunc_fabsf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001731 return ConstantFoldFP(fabs, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001732 else if ((Name == "floor" && TLI->has(LibFunc_floor)) ||
1733 (Name == "floorf" && TLI->has(LibFunc_floorf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001734 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001735 break;
1736 case 'l':
David L. Jonesd21529f2017-01-23 23:16:46 +00001737 if ((Name == "log" && V > 0 && TLI->has(LibFunc_log)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001738 (Name == "logf" && V > 0 && TLI->has(LibFunc_logf)) ||
1739 (Name == "__log_finite" && V > 0 &&
1740 TLI->has(LibFunc_log_finite)) ||
1741 (Name == "__logf_finite" && V > 0 &&
1742 TLI->has(LibFunc_logf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001743 return ConstantFoldFP(log, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001744 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc_log10)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001745 (Name == "log10f" && V > 0 && TLI->has(LibFunc_log10f)) ||
1746 (Name == "__log10_finite" && V > 0 &&
1747 TLI->has(LibFunc_log10_finite)) ||
1748 (Name == "__log10f_finite" && V > 0 &&
1749 TLI->has(LibFunc_log10f_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001750 return ConstantFoldFP(log10, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001751 break;
Bryant Wongb5e03b62016-12-26 14:29:29 +00001752 case 'r':
David L. Jonesd21529f2017-01-23 23:16:46 +00001753 if ((Name == "round" && TLI->has(LibFunc_round)) ||
1754 (Name == "roundf" && TLI->has(LibFunc_roundf)))
Bryant Wongb5e03b62016-12-26 14:29:29 +00001755 return ConstantFoldFP(round, V, Ty);
Galina Kistanovac2b642d2017-05-31 20:25:13 +00001756 break;
Chris Lattner785f9982007-08-08 06:55:43 +00001757 case 's':
David L. Jonesd21529f2017-01-23 23:16:46 +00001758 if ((Name == "sin" && TLI->has(LibFunc_sin)) ||
1759 (Name == "sinf" && TLI->has(LibFunc_sinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001760 return ConstantFoldFP(sin, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001761 else if ((Name == "sinh" && TLI->has(LibFunc_sinh)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001762 (Name == "sinhf" && TLI->has(LibFunc_sinhf)) ||
1763 (Name == "__sinh_finite" && TLI->has(LibFunc_sinh_finite)) ||
1764 (Name == "__sinhf_finite" && TLI->has(LibFunc_sinhf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001765 return ConstantFoldFP(sinh, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001766 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc_sqrt)) ||
1767 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc_sqrtf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001768 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001769 break;
1770 case 't':
David L. Jonesd21529f2017-01-23 23:16:46 +00001771 if ((Name == "tan" && TLI->has(LibFunc_tan)) ||
1772 (Name == "tanf" && TLI->has(LibFunc_tanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001773 return ConstantFoldFP(tan, V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001774 else if ((Name == "tanh" && TLI->has(LibFunc_tanh)) ||
1775 (Name == "tanhf" && TLI->has(LibFunc_tanhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001776 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001777 break;
1778 default:
1779 break;
John Criswell970af112005-10-27 16:00:10 +00001780 }
Craig Topper9f008862014-04-15 04:59:12 +00001781 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001782 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001783
David Majnemer90a97042016-07-13 04:22:12 +00001784 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001785 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001786 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001787 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001788 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001789 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Matt Arsenault155dda92016-03-21 15:00:35 +00001790 case Intrinsic::bitreverse:
1791 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001792 case Intrinsic::convert_from_fp16: {
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001793 APFloat Val(APFloat::IEEEhalf(), Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001794
1795 bool lost = false;
Andrea Di Biagio29059992015-05-14 18:01:48 +00001796 APFloat::opStatus status = Val.convert(
1797 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001798
1799 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001800 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001801 assert(status == APFloat::opOK && !lost &&
1802 "Precision lost during fp16 constfolding");
1803
Benjamin Kramer061d1472014-03-05 19:41:48 +00001804 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001805 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001806 default:
Craig Topper9f008862014-04-15 04:59:12 +00001807 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001808 }
John Criswell970af112005-10-27 16:00:10 +00001809 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001810
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001811 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001812 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001813 isa<ConstantDataVector>(Operands[0])) {
David Majnemer90a97042016-07-13 04:22:12 +00001814 auto *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001815 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001816 default: break;
1817 case Intrinsic::x86_sse_cvtss2si:
1818 case Intrinsic::x86_sse_cvtss2si64:
1819 case Intrinsic::x86_sse2_cvtsd2si:
1820 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001821 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001822 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1823 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1824 /*roundTowardZero=*/false, Ty);
Craig Topper0dd29e22017-06-04 08:21:51 +00001825 break;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001826 case Intrinsic::x86_sse_cvttss2si:
1827 case Intrinsic::x86_sse_cvttss2si64:
1828 case Intrinsic::x86_sse2_cvttsd2si:
1829 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001830 if (ConstantFP *FPOp =
Simon Pilgrim0ea8d272016-07-19 15:07:43 +00001831 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1832 return ConstantFoldSSEConvertToInt(FPOp->getValueAPF(),
1833 /*roundTowardZero=*/true, Ty);
Craig Topper0dd29e22017-06-04 08:21:51 +00001834 break;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001835 }
1836 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001837
Craig Topper9f008862014-04-15 04:59:12 +00001838 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001839 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001840
Jay Foadf4b14a22011-07-19 13:32:40 +00001841 if (Operands.size() == 2) {
David Majnemer90a97042016-07-13 04:22:12 +00001842 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001843 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001844 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001845 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001846
David Majnemer90a97042016-07-13 04:22:12 +00001847 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001848 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001849 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001850
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001851 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001852 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001853 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1854 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001855 if (IntrinsicID == Intrinsic::copysign) {
1856 APFloat V1 = Op1->getValueAPF();
Benjamin Kramer8f59adb2016-02-13 16:54:14 +00001857 const APFloat &V2 = Op2->getValueAPF();
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001858 V1.copySign(V2);
1859 return ConstantFP::get(Ty->getContext(), V1);
1860 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001861
1862 if (IntrinsicID == Intrinsic::minnum) {
1863 const APFloat &C1 = Op1->getValueAPF();
1864 const APFloat &C2 = Op2->getValueAPF();
1865 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1866 }
1867
1868 if (IntrinsicID == Intrinsic::maxnum) {
1869 const APFloat &C1 = Op1->getValueAPF();
1870 const APFloat &C2 = Op2->getValueAPF();
1871 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1872 }
1873
Chad Rosier0155a632011-12-03 00:00:03 +00001874 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001875 return nullptr;
David L. Jonesd21529f2017-01-23 23:16:46 +00001876 if ((Name == "pow" && TLI->has(LibFunc_pow)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001877 (Name == "powf" && TLI->has(LibFunc_powf)) ||
1878 (Name == "__pow_finite" && TLI->has(LibFunc_pow_finite)) ||
1879 (Name == "__powf_finite" && TLI->has(LibFunc_powf_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001880 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001881 if ((Name == "fmod" && TLI->has(LibFunc_fmod)) ||
1882 (Name == "fmodf" && TLI->has(LibFunc_fmodf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001883 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
David L. Jonesd21529f2017-01-23 23:16:46 +00001884 if ((Name == "atan2" && TLI->has(LibFunc_atan2)) ||
Andrew Kaylorf7c864f2017-05-12 22:11:20 +00001885 (Name == "atan2f" && TLI->has(LibFunc_atan2f)) ||
1886 (Name == "__atan2_finite" && TLI->has(LibFunc_atan2_finite)) ||
1887 (Name == "__atan2f_finite" && TLI->has(LibFunc_atan2f_finite)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001888 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
David Majnemer90a97042016-07-13 04:22:12 +00001889 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001890 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1891 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001892 APFloat((float)std::pow((float)Op1V,
1893 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001894 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1895 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001896 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001897 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001898 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1899 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001900 APFloat((double)std::pow((double)Op1V,
1901 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001902 }
Craig Topper9f008862014-04-15 04:59:12 +00001903 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001904 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001905
David Majnemer90a97042016-07-13 04:22:12 +00001906 if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1907 if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001908 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001909 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001910 case Intrinsic::sadd_with_overflow:
1911 case Intrinsic::uadd_with_overflow:
1912 case Intrinsic::ssub_with_overflow:
1913 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001914 case Intrinsic::smul_with_overflow:
1915 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001916 APInt Res;
1917 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001918 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001919 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001920 case Intrinsic::sadd_with_overflow:
1921 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1922 break;
1923 case Intrinsic::uadd_with_overflow:
1924 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1925 break;
1926 case Intrinsic::ssub_with_overflow:
1927 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1928 break;
1929 case Intrinsic::usub_with_overflow:
1930 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1931 break;
1932 case Intrinsic::smul_with_overflow:
1933 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1934 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001935 case Intrinsic::umul_with_overflow:
1936 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1937 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001938 }
Chris Lattner59d93982009-10-05 05:26:04 +00001939 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001940 ConstantInt::get(Ty->getContext(), Res),
1941 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001942 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001943 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001944 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001945 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001946 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1947 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001948 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1949 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001950 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1951 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001952 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001953 }
1954 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001955
Craig Topper9f008862014-04-15 04:59:12 +00001956 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001957 }
Craig Topper9f008862014-04-15 04:59:12 +00001958 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001959 }
Matt Arsenault83778582014-03-05 00:02:00 +00001960
1961 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001962 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001963
David Majnemer90a97042016-07-13 04:22:12 +00001964 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1965 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1966 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001967 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001968 default: break;
1969 case Intrinsic::fma:
1970 case Intrinsic::fmuladd: {
1971 APFloat V = Op1->getValueAPF();
1972 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1973 Op3->getValueAPF(),
1974 APFloat::rmNearestTiesToEven);
1975 if (s != APFloat::opInvalidOp)
1976 return ConstantFP::get(Ty->getContext(), V);
1977
Craig Topper9f008862014-04-15 04:59:12 +00001978 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001979 }
1980 }
1981 }
1982 }
1983 }
1984
Craig Topper9f008862014-04-15 04:59:12 +00001985 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001986}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001987
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001988Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1989 VectorType *VTy, ArrayRef<Constant *> Operands,
David Majnemer7f781ab2016-07-14 00:29:50 +00001990 const DataLayout &DL,
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001991 const TargetLibraryInfo *TLI) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001992 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1993 SmallVector<Constant *, 4> Lane(Operands.size());
1994 Type *Ty = VTy->getElementType();
1995
David Majnemer7f781ab2016-07-14 00:29:50 +00001996 if (IntrinsicID == Intrinsic::masked_load) {
1997 auto *SrcPtr = Operands[0];
1998 auto *Mask = Operands[2];
1999 auto *Passthru = Operands[3];
David Majnemer17a95aa2016-07-14 06:58:37 +00002000
David Majnemer7f781ab2016-07-14 00:29:50 +00002001 Constant *VecData = ConstantFoldLoadFromConstPtr(SrcPtr, VTy, DL);
David Majnemer7f781ab2016-07-14 00:29:50 +00002002
2003 SmallVector<Constant *, 32> NewElements;
2004 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
David Majnemer17a95aa2016-07-14 06:58:37 +00002005 auto *MaskElt = Mask->getAggregateElement(I);
David Majnemer7f781ab2016-07-14 00:29:50 +00002006 if (!MaskElt)
2007 break;
David Majnemer17a95aa2016-07-14 06:58:37 +00002008 auto *PassthruElt = Passthru->getAggregateElement(I);
2009 auto *VecElt = VecData ? VecData->getAggregateElement(I) : nullptr;
2010 if (isa<UndefValue>(MaskElt)) {
2011 if (PassthruElt)
2012 NewElements.push_back(PassthruElt);
2013 else if (VecElt)
2014 NewElements.push_back(VecElt);
2015 else
2016 return nullptr;
2017 }
2018 if (MaskElt->isNullValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002019 if (!PassthruElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002020 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002021 NewElements.push_back(PassthruElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002022 } else if (MaskElt->isOneValue()) {
David Majnemer7f781ab2016-07-14 00:29:50 +00002023 if (!VecElt)
David Majnemer17a95aa2016-07-14 06:58:37 +00002024 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002025 NewElements.push_back(VecElt);
David Majnemer17a95aa2016-07-14 06:58:37 +00002026 } else {
2027 return nullptr;
David Majnemer7f781ab2016-07-14 00:29:50 +00002028 }
2029 }
David Majnemer17a95aa2016-07-14 06:58:37 +00002030 if (NewElements.size() != VTy->getNumElements())
2031 return nullptr;
2032 return ConstantVector::get(NewElements);
David Majnemer7f781ab2016-07-14 00:29:50 +00002033 }
2034
Benjamin Kramer061d1472014-03-05 19:41:48 +00002035 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
2036 // Gather a column of constants.
2037 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
Craig Topper7c553ed2017-06-03 18:50:29 +00002038 // These intrinsics use a scalar type for their second argument.
2039 if (J == 1 &&
Craig Topperfe9ad822017-06-04 07:30:28 +00002040 (IntrinsicID == Intrinsic::cttz || IntrinsicID == Intrinsic::ctlz ||
2041 IntrinsicID == Intrinsic::powi)) {
Craig Topper7c553ed2017-06-03 18:50:29 +00002042 Lane[J] = Operands[J];
2043 continue;
2044 }
2045
Benjamin Kramer061d1472014-03-05 19:41:48 +00002046 Constant *Agg = Operands[J]->getAggregateElement(I);
2047 if (!Agg)
2048 return nullptr;
2049
2050 Lane[J] = Agg;
2051 }
2052
2053 // Use the regular scalar folding to simplify this column.
2054 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
2055 if (!Folded)
2056 return nullptr;
2057 Result[I] = Folded;
2058 }
2059
2060 return ConstantVector::get(Result);
2061}
2062
Eugene Zelenko35623fb2016-03-28 17:40:08 +00002063} // end anonymous namespace
2064
Benjamin Kramer061d1472014-03-05 19:41:48 +00002065Constant *
Andrew Kaylor647025f2017-06-09 23:18:11 +00002066llvm::ConstantFoldCall(ImmutableCallSite CS, Function *F,
2067 ArrayRef<Constant *> Operands,
Benjamin Kramer061d1472014-03-05 19:41:48 +00002068 const TargetLibraryInfo *TLI) {
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002069 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002070 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002071 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00002072 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00002073 StringRef Name = F->getName();
2074
2075 Type *Ty = F->getReturnType();
2076
David Majnemer90a97042016-07-13 04:22:12 +00002077 if (auto *VTy = dyn_cast<VectorType>(Ty))
David Majnemer7f781ab2016-07-14 00:29:50 +00002078 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands,
2079 F->getParent()->getDataLayout(), TLI);
Benjamin Kramer061d1472014-03-05 19:41:48 +00002080
2081 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
2082}
Eli Friedmanb6befc32016-11-02 20:48:11 +00002083
2084bool llvm::isMathLibCallNoop(CallSite CS, const TargetLibraryInfo *TLI) {
2085 // FIXME: Refactor this code; this duplicates logic in LibCallsShrinkWrap
2086 // (and to some extent ConstantFoldScalarCall).
Andrew Kaylor53a5fbb2017-08-14 21:15:13 +00002087 if (CS.isNoBuiltin() || CS.isStrictFP())
Andrew Kaylor647025f2017-06-09 23:18:11 +00002088 return false;
Eli Friedmanb6befc32016-11-02 20:48:11 +00002089 Function *F = CS.getCalledFunction();
2090 if (!F)
2091 return false;
2092
David L. Jonesd21529f2017-01-23 23:16:46 +00002093 LibFunc Func;
Eli Friedmanb6befc32016-11-02 20:48:11 +00002094 if (!TLI || !TLI->getLibFunc(*F, Func))
2095 return false;
2096
2097 if (CS.getNumArgOperands() == 1) {
2098 if (ConstantFP *OpC = dyn_cast<ConstantFP>(CS.getArgOperand(0))) {
2099 const APFloat &Op = OpC->getValueAPF();
2100 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002101 case LibFunc_logl:
2102 case LibFunc_log:
2103 case LibFunc_logf:
2104 case LibFunc_log2l:
2105 case LibFunc_log2:
2106 case LibFunc_log2f:
2107 case LibFunc_log10l:
2108 case LibFunc_log10:
2109 case LibFunc_log10f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002110 return Op.isNaN() || (!Op.isZero() && !Op.isNegative());
2111
David L. Jonesd21529f2017-01-23 23:16:46 +00002112 case LibFunc_expl:
2113 case LibFunc_exp:
2114 case LibFunc_expf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002115 // FIXME: These boundaries are slightly conservative.
2116 if (OpC->getType()->isDoubleTy())
2117 return Op.compare(APFloat(-745.0)) != APFloat::cmpLessThan &&
2118 Op.compare(APFloat(709.0)) != APFloat::cmpGreaterThan;
2119 if (OpC->getType()->isFloatTy())
2120 return Op.compare(APFloat(-103.0f)) != APFloat::cmpLessThan &&
2121 Op.compare(APFloat(88.0f)) != APFloat::cmpGreaterThan;
2122 break;
2123
David L. Jonesd21529f2017-01-23 23:16:46 +00002124 case LibFunc_exp2l:
2125 case LibFunc_exp2:
2126 case LibFunc_exp2f:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002127 // FIXME: These boundaries are slightly conservative.
2128 if (OpC->getType()->isDoubleTy())
2129 return Op.compare(APFloat(-1074.0)) != APFloat::cmpLessThan &&
2130 Op.compare(APFloat(1023.0)) != APFloat::cmpGreaterThan;
2131 if (OpC->getType()->isFloatTy())
2132 return Op.compare(APFloat(-149.0f)) != APFloat::cmpLessThan &&
2133 Op.compare(APFloat(127.0f)) != APFloat::cmpGreaterThan;
2134 break;
2135
David L. Jonesd21529f2017-01-23 23:16:46 +00002136 case LibFunc_sinl:
2137 case LibFunc_sin:
2138 case LibFunc_sinf:
2139 case LibFunc_cosl:
2140 case LibFunc_cos:
2141 case LibFunc_cosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002142 return !Op.isInfinity();
2143
David L. Jonesd21529f2017-01-23 23:16:46 +00002144 case LibFunc_tanl:
2145 case LibFunc_tan:
2146 case LibFunc_tanf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002147 // FIXME: Stop using the host math library.
2148 // FIXME: The computation isn't done in the right precision.
2149 Type *Ty = OpC->getType();
2150 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2151 double OpV = getValueAsDouble(OpC);
2152 return ConstantFoldFP(tan, OpV, Ty) != nullptr;
2153 }
2154 break;
2155 }
2156
David L. Jonesd21529f2017-01-23 23:16:46 +00002157 case LibFunc_asinl:
2158 case LibFunc_asin:
2159 case LibFunc_asinf:
2160 case LibFunc_acosl:
2161 case LibFunc_acos:
2162 case LibFunc_acosf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002163 return Op.compare(APFloat(Op.getSemantics(), "-1")) !=
2164 APFloat::cmpLessThan &&
2165 Op.compare(APFloat(Op.getSemantics(), "1")) !=
2166 APFloat::cmpGreaterThan;
2167
David L. Jonesd21529f2017-01-23 23:16:46 +00002168 case LibFunc_sinh:
2169 case LibFunc_cosh:
2170 case LibFunc_sinhf:
2171 case LibFunc_coshf:
2172 case LibFunc_sinhl:
2173 case LibFunc_coshl:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002174 // FIXME: These boundaries are slightly conservative.
2175 if (OpC->getType()->isDoubleTy())
2176 return Op.compare(APFloat(-710.0)) != APFloat::cmpLessThan &&
2177 Op.compare(APFloat(710.0)) != APFloat::cmpGreaterThan;
2178 if (OpC->getType()->isFloatTy())
2179 return Op.compare(APFloat(-89.0f)) != APFloat::cmpLessThan &&
2180 Op.compare(APFloat(89.0f)) != APFloat::cmpGreaterThan;
2181 break;
2182
David L. Jonesd21529f2017-01-23 23:16:46 +00002183 case LibFunc_sqrtl:
2184 case LibFunc_sqrt:
2185 case LibFunc_sqrtf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002186 return Op.isNaN() || Op.isZero() || !Op.isNegative();
2187
2188 // FIXME: Add more functions: sqrt_finite, atanh, expm1, log1p,
2189 // maybe others?
2190 default:
2191 break;
2192 }
2193 }
2194 }
2195
2196 if (CS.getNumArgOperands() == 2) {
2197 ConstantFP *Op0C = dyn_cast<ConstantFP>(CS.getArgOperand(0));
2198 ConstantFP *Op1C = dyn_cast<ConstantFP>(CS.getArgOperand(1));
2199 if (Op0C && Op1C) {
2200 const APFloat &Op0 = Op0C->getValueAPF();
2201 const APFloat &Op1 = Op1C->getValueAPF();
2202
2203 switch (Func) {
David L. Jonesd21529f2017-01-23 23:16:46 +00002204 case LibFunc_powl:
2205 case LibFunc_pow:
2206 case LibFunc_powf: {
Eli Friedmanb6befc32016-11-02 20:48:11 +00002207 // FIXME: Stop using the host math library.
2208 // FIXME: The computation isn't done in the right precision.
2209 Type *Ty = Op0C->getType();
2210 if (Ty->isDoubleTy() || Ty->isFloatTy() || Ty->isHalfTy()) {
2211 if (Ty == Op1C->getType()) {
2212 double Op0V = getValueAsDouble(Op0C);
2213 double Op1V = getValueAsDouble(Op1C);
2214 return ConstantFoldBinaryFP(pow, Op0V, Op1V, Ty) != nullptr;
2215 }
2216 }
2217 break;
2218 }
2219
David L. Jonesd21529f2017-01-23 23:16:46 +00002220 case LibFunc_fmodl:
2221 case LibFunc_fmod:
2222 case LibFunc_fmodf:
Eli Friedmanb6befc32016-11-02 20:48:11 +00002223 return Op0.isNaN() || Op1.isNaN() ||
2224 (!Op0.isInfinity() && !Op1.isZero());
2225
2226 default:
2227 break;
2228 }
2229 }
2230 }
2231
2232 return false;
2233}