blob: bf0cb3e1a18ab7ea7e5d8214c4aafb5f2ec926ab [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"
David Majnemere61e4bf2016-06-21 05:10:24 +000020#include "llvm/ADT/STLExtras.h"
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +000021#include "llvm/ADT/SmallPtrSet.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000022#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringMap.h"
Chandler Carruth62d42152015-01-15 02:16:27 +000024#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000025#include "llvm/Analysis/ValueTracking.h"
Alp Tokerc817d6a2014-06-09 18:28:53 +000026#include "llvm/Config/config.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
Chandler Carruth03eb0de2014-03-04 10:40:04 +000031#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000032#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/Intrinsics.h"
35#include "llvm/IR/Operator.h"
Torok Edwin56d06592009-07-11 20:10:48 +000036#include "llvm/Support/ErrorHandling.h"
John Criswell970af112005-10-27 16:00:10 +000037#include "llvm/Support/MathExtras.h"
Eugene Zelenko35623fb2016-03-28 17:40:08 +000038#include <cassert>
John Criswell970af112005-10-27 16:00:10 +000039#include <cerrno>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000040#include <cfenv>
Jeff Cohencc08c832006-12-02 02:22:01 +000041#include <cmath>
Eugene Zelenko35623fb2016-03-28 17:40:08 +000042#include <limits>
Alp Tokerc817d6a2014-06-09 18:28:53 +000043
John Criswell970af112005-10-27 16:00:10 +000044using namespace llvm;
45
Eugene Zelenko35623fb2016-03-28 17:40:08 +000046namespace {
47
Chris Lattner44d68b92007-01-31 00:51:48 +000048//===----------------------------------------------------------------------===//
49// Constant Folding internal helper functions
50//===----------------------------------------------------------------------===//
51
Sanjay Patel0d7dee62014-10-02 15:13:22 +000052/// Constant fold bitcast, symbolically evaluating it with DataLayout.
53/// This always returns a non-null constant, but it may be a
Chris Lattner9d051242009-10-25 06:08:26 +000054/// ConstantExpr if unfoldable.
Eugene Zelenko35623fb2016-03-28 17:40:08 +000055Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
Nadav Rotem365af6f2011-08-24 20:18:38 +000056 // Catch the obvious splat cases.
57 if (C->isNullValue() && !DestTy->isX86_MMXTy())
58 return Constant::getNullValue(DestTy);
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +000059 if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
60 !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
Nadav Rotem365af6f2011-08-24 20:18:38 +000061 return Constant::getAllOnesValue(DestTy);
62
Rafael Espindolabb893fe2012-01-27 23:33:07 +000063 // Handle a vector->integer cast.
David Majnemer90a97042016-07-13 04:22:12 +000064 if (auto *IT = dyn_cast<IntegerType>(DestTy)) {
65 auto *VTy = dyn_cast<VectorType>(C->getType());
Craig Topper9f008862014-04-15 04:59:12 +000066 if (!VTy)
Rafael Espindolabb893fe2012-01-27 23:33:07 +000067 return ConstantExpr::getBitCast(C, DestTy);
68
Michael Ilsemana7b93c12013-02-26 22:51:07 +000069 unsigned NumSrcElts = VTy->getNumElements();
70 Type *SrcEltTy = VTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +000071
Rafael Espindolabb893fe2012-01-27 23:33:07 +000072 // If the vector is a vector of floating point, convert it to vector of int
73 // to simplify things.
Chris Lattner8213c8a2012-02-06 21:56:39 +000074 if (SrcEltTy->isFloatingPointTy()) {
75 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Rafael Espindolabb893fe2012-01-27 23:33:07 +000076 Type *SrcIVTy =
77 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
Chandler Carruthef860a22013-01-02 09:10:48 +000078 // Ask IR to do the conversion now that #elts line up.
Rafael Espindolabb893fe2012-01-27 23:33:07 +000079 C = ConstantExpr::getBitCast(C, SrcIVTy);
80 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +000081
Rafael Espindolabb893fe2012-01-27 23:33:07 +000082 // Now that we know that the input value is a vector of integers, just shift
83 // and insert them into our result.
Igor Breger73578492016-06-27 06:42:54 +000084 unsigned BitShift = DL.getTypeSizeInBits(SrcEltTy);
Rafael Espindolabb893fe2012-01-27 23:33:07 +000085 APInt Result(IT->getBitWidth(), 0);
86 for (unsigned i = 0; i != NumSrcElts; ++i) {
David Majnemer3918cdd2016-05-04 06:13:33 +000087 Constant *Element;
Mehdi Aminia28d91d2015-03-10 02:37:25 +000088 if (DL.isLittleEndian())
David Majnemer3918cdd2016-05-04 06:13:33 +000089 Element = C->getAggregateElement(NumSrcElts-i-1);
Chris Lattner8213c8a2012-02-06 21:56:39 +000090 else
David Majnemer3918cdd2016-05-04 06:13:33 +000091 Element = C->getAggregateElement(i);
92
93 auto *ElementCI = dyn_cast_or_null<ConstantInt>(Element);
94 if (!ElementCI)
95 return ConstantExpr::getBitCast(C, DestTy);
96
97 Result <<= BitShift;
98 Result |= ElementCI->getValue().zextOrSelf(IT->getBitWidth());
Rafael Espindolabb893fe2012-01-27 23:33:07 +000099 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000100
Rafael Espindolabb893fe2012-01-27 23:33:07 +0000101 return ConstantInt::get(IT, Result);
102 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000103
Nadav Rotemad4a70a2011-08-20 14:02:29 +0000104 // The code below only handles casts to vectors currently.
David Majnemer90a97042016-07-13 04:22:12 +0000105 auto *DestVTy = dyn_cast<VectorType>(DestTy);
Craig Topper9f008862014-04-15 04:59:12 +0000106 if (!DestVTy)
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000107 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000108
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000109 // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
110 // vector so the code below can handle it uniformly.
111 if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
112 Constant *Ops = C; // don't take the address of C!
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000113 return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
Chris Lattnerd8e8fb42009-10-25 06:15:37 +0000114 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000115
Chris Lattner9d051242009-10-25 06:08:26 +0000116 // If this is a bitcast from constant vector -> vector, fold it.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000117 if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000118 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000119
Chandler Carruthef860a22013-01-02 09:10:48 +0000120 // If the element types match, IR can fold it.
Chris Lattner9d051242009-10-25 06:08:26 +0000121 unsigned NumDstElt = DestVTy->getNumElements();
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000122 unsigned NumSrcElt = C->getType()->getVectorNumElements();
Chris Lattner9d051242009-10-25 06:08:26 +0000123 if (NumDstElt == NumSrcElt)
124 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000125
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000126 Type *SrcEltTy = C->getType()->getVectorElementType();
Chris Lattner229907c2011-07-18 04:54:35 +0000127 Type *DstEltTy = DestVTy->getElementType();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000128
129 // Otherwise, we're changing the number of elements in a vector, which
Chris Lattner9d051242009-10-25 06:08:26 +0000130 // requires endianness information to do the right thing. For example,
131 // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
132 // folds to (little endian):
133 // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
134 // and to (big endian):
135 // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000136
Chris Lattner9d051242009-10-25 06:08:26 +0000137 // First thing is first. We only want to think about integer here, so if
138 // we have something in FP form, recast it as integer.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000139 if (DstEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000140 // Fold to an vector of integers with same size as our FP type.
141 unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000142 Type *DestIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000143 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
144 // Recursively handle this integer conversion, if possible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000145 C = FoldBitCast(C, DestIVTy, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000146
Chandler Carruthef860a22013-01-02 09:10:48 +0000147 // Finally, IR can handle this now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000148 return ConstantExpr::getBitCast(C, DestTy);
149 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000150
Chris Lattner9d051242009-10-25 06:08:26 +0000151 // Okay, we know the destination is integer, if the input is FP, convert
152 // it to integer first.
Duncan Sands9dff9be2010-02-15 16:12:20 +0000153 if (SrcEltTy->isFloatingPointTy()) {
Chris Lattner9d051242009-10-25 06:08:26 +0000154 unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
Chris Lattner229907c2011-07-18 04:54:35 +0000155 Type *SrcIVTy =
Chris Lattner9d051242009-10-25 06:08:26 +0000156 VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
Chandler Carruthef860a22013-01-02 09:10:48 +0000157 // Ask IR to do the conversion now that #elts line up.
Chris Lattner9d051242009-10-25 06:08:26 +0000158 C = ConstantExpr::getBitCast(C, SrcIVTy);
Chandler Carruthef860a22013-01-02 09:10:48 +0000159 // If IR wasn't able to fold it, bail out.
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000160 if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
161 !isa<ConstantDataVector>(C))
Chris Lattner9d051242009-10-25 06:08:26 +0000162 return C;
163 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000164
Chris Lattner9d051242009-10-25 06:08:26 +0000165 // Now we know that the input and output vectors are both integer vectors
166 // of the same size, and that their #elements is not the same. Do the
167 // conversion here, which depends on whether the input or output has
168 // more elements.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000169 bool isLittleEndian = DL.isLittleEndian();
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000170
Chris Lattner9d051242009-10-25 06:08:26 +0000171 SmallVector<Constant*, 32> Result;
172 if (NumDstElt < NumSrcElt) {
173 // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
174 Constant *Zero = Constant::getNullValue(DstEltTy);
175 unsigned Ratio = NumSrcElt/NumDstElt;
176 unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
177 unsigned SrcElt = 0;
178 for (unsigned i = 0; i != NumDstElt; ++i) {
179 // Build each element of the result.
180 Constant *Elt = Zero;
181 unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
182 for (unsigned j = 0; j != Ratio; ++j) {
David Majnemer90a97042016-07-13 04:22:12 +0000183 Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
Chris Lattner9d051242009-10-25 06:08:26 +0000184 if (!Src) // Reject constantexpr elements.
185 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000186
Chris Lattner9d051242009-10-25 06:08:26 +0000187 // Zero extend the element to the right size.
188 Src = ConstantExpr::getZExt(Src, Elt->getType());
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000189
Chris Lattner9d051242009-10-25 06:08:26 +0000190 // Shift it to the right place, depending on endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000191 Src = ConstantExpr::getShl(Src,
Chris Lattner9d051242009-10-25 06:08:26 +0000192 ConstantInt::get(Src->getType(), ShiftAmt));
193 ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000194
Chris Lattner9d051242009-10-25 06:08:26 +0000195 // Mix it in.
196 Elt = ConstantExpr::getOr(Elt, Src);
197 }
198 Result.push_back(Elt);
199 }
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000200 return ConstantVector::get(Result);
201 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000202
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000203 // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
204 unsigned Ratio = NumDstElt/NumSrcElt;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000205 unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000206
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000207 // Loop over each source value, expanding into multiple results.
208 for (unsigned i = 0; i != NumSrcElt; ++i) {
David Majnemer90a97042016-07-13 04:22:12 +0000209 auto *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000210 if (!Src) // Reject constantexpr elements.
211 return ConstantExpr::getBitCast(C, DestTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000212
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000213 unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
214 for (unsigned j = 0; j != Ratio; ++j) {
215 // Shift the piece of the value into the right place, depending on
216 // endianness.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000217 Constant *Elt = ConstantExpr::getLShr(Src,
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000218 ConstantInt::get(Src->getType(), ShiftAmt));
219 ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000220
Bruno Cardoso Lopesc29520c2014-10-22 12:18:48 +0000221 // Truncate the element to an integer with the same pointer size and
222 // convert the element back to a pointer using a inttoptr.
223 if (DstEltTy->isPointerTy()) {
224 IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
225 Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
226 Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
227 continue;
228 }
229
Chris Lattner61a1d6c2012-01-26 21:37:55 +0000230 // Truncate and remember this piece.
231 Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
Chris Lattner9d051242009-10-25 06:08:26 +0000232 }
233 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000234
Chris Lattner69229312011-02-15 00:14:00 +0000235 return ConstantVector::get(Result);
Chris Lattner9d051242009-10-25 06:08:26 +0000236}
237
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000238} // end anonymous namespace
239
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000240/// If this constant is a constant offset from a global, return the global and
241/// the constant. Because of constantexprs, this function is recursive.
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000242bool llvm::IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
243 APInt &Offset, const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000244 // Trivial case, constant is the global.
245 if ((GV = dyn_cast<GlobalValue>(C))) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000246 unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000247 Offset = APInt(BitWidth, 0);
Chris Lattner44d68b92007-01-31 00:51:48 +0000248 return true;
249 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000250
Chris Lattner44d68b92007-01-31 00:51:48 +0000251 // Otherwise, if this isn't a constant expr, bail out.
David Majnemer90a97042016-07-13 04:22:12 +0000252 auto *CE = dyn_cast<ConstantExpr>(C);
Chris Lattner44d68b92007-01-31 00:51:48 +0000253 if (!CE) return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000254
Chris Lattner44d68b92007-01-31 00:51:48 +0000255 // Look through ptr->int and ptr->ptr casts.
256 if (CE->getOpcode() == Instruction::PtrToInt ||
Matt Arsenault95365ca2015-07-27 18:31:03 +0000257 CE->getOpcode() == Instruction::BitCast)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000258 return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000259
260 // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
David Majnemer90a97042016-07-13 04:22:12 +0000261 auto *GEP = dyn_cast<GEPOperator>(CE);
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000262 if (!GEP)
263 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000264
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000265 unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000266 APInt TmpOffset(BitWidth, 0);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000267
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000268 // If the base isn't a global+constant, we aren't either.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000269 if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000270 return false;
271
272 // Otherwise, add any offset that our operands provide.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000273 if (!GEP->accumulateConstantOffset(DL, TmpOffset))
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000274 return false;
275
276 Offset = TmpOffset;
277 return true;
Chris Lattner44d68b92007-01-31 00:51:48 +0000278}
279
Peter Collingbourne265ebd72016-04-22 20:40:10 +0000280namespace {
281
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000282/// Recursive helper to read bits out of global. C is the constant being copied
283/// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
284/// results into and BytesLeft is the number of bytes left in
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000285/// the CurPtr buffer. DL is the DataLayout.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000286bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset, unsigned char *CurPtr,
287 unsigned BytesLeft, const DataLayout &DL) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000288 assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
Chris Lattnered00b802009-10-23 06:23:49 +0000289 "Out of range access");
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000290
Chris Lattner3db7bd22009-10-24 05:27:19 +0000291 // If this element is zero or undefined, we can just return since *CurPtr is
292 // zero initialized.
Chris Lattnered00b802009-10-23 06:23:49 +0000293 if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
294 return true;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000295
David Majnemer90a97042016-07-13 04:22:12 +0000296 if (auto *CI = dyn_cast<ConstantInt>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000297 if (CI->getBitWidth() > 64 ||
298 (CI->getBitWidth() & 7) != 0)
299 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000300
Chris Lattnered00b802009-10-23 06:23:49 +0000301 uint64_t Val = CI->getZExtValue();
302 unsigned IntBytes = unsigned(CI->getBitWidth()/8);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000303
Chris Lattnered00b802009-10-23 06:23:49 +0000304 for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000305 int n = ByteOffset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000306 if (!DL.isLittleEndian())
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000307 n = IntBytes - n - 1;
308 CurPtr[i] = (unsigned char)(Val >> (n * 8));
Chris Lattnered00b802009-10-23 06:23:49 +0000309 ++ByteOffset;
310 }
311 return true;
312 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000313
David Majnemer90a97042016-07-13 04:22:12 +0000314 if (auto *CFP = dyn_cast<ConstantFP>(C)) {
Chris Lattnered00b802009-10-23 06:23:49 +0000315 if (CFP->getType()->isDoubleTy()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000316 C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
317 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000318 }
319 if (CFP->getType()->isFloatTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000320 C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
321 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000322 }
Owen Andersond4ebfd82013-02-06 22:43:31 +0000323 if (CFP->getType()->isHalfTy()){
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000324 C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
325 return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
Owen Andersond4ebfd82013-02-06 22:43:31 +0000326 }
Chris Lattner3db7bd22009-10-24 05:27:19 +0000327 return false;
Chris Lattnered00b802009-10-23 06:23:49 +0000328 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000329
David Majnemer90a97042016-07-13 04:22:12 +0000330 if (auto *CS = dyn_cast<ConstantStruct>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000331 const StructLayout *SL = DL.getStructLayout(CS->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000332 unsigned Index = SL->getElementContainingOffset(ByteOffset);
333 uint64_t CurEltOffset = SL->getElementOffset(Index);
334 ByteOffset -= CurEltOffset;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000335
Chris Lattnered00b802009-10-23 06:23:49 +0000336 while (1) {
337 // If the element access is to the element itself and not to tail padding,
338 // read the bytes from the element.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000339 uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
Chris Lattnered00b802009-10-23 06:23:49 +0000340
341 if (ByteOffset < EltSize &&
342 !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000343 BytesLeft, DL))
Chris Lattnered00b802009-10-23 06:23:49 +0000344 return false;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000345
Chris Lattnered00b802009-10-23 06:23:49 +0000346 ++Index;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000347
Chris Lattnered00b802009-10-23 06:23:49 +0000348 // Check to see if we read from the last struct element, if so we're done.
349 if (Index == CS->getType()->getNumElements())
350 return true;
351
352 // If we read all of the bytes we needed from this element we're done.
353 uint64_t NextEltOffset = SL->getElementOffset(Index);
354
Matt Arsenault8c789092013-08-12 23:15:58 +0000355 if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
Chris Lattnered00b802009-10-23 06:23:49 +0000356 return true;
357
358 // Move to the next element of the struct.
Matt Arsenault8c789092013-08-12 23:15:58 +0000359 CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
360 BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
Chris Lattnered00b802009-10-23 06:23:49 +0000361 ByteOffset = 0;
362 CurEltOffset = NextEltOffset;
363 }
364 // not reached.
365 }
366
Chris Lattner67058832012-01-25 06:48:06 +0000367 if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
368 isa<ConstantDataSequential>(C)) {
Matt Arsenault8c789092013-08-12 23:15:58 +0000369 Type *EltTy = C->getType()->getSequentialElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000370 uint64_t EltSize = DL.getTypeAllocSize(EltTy);
Chris Lattnered00b802009-10-23 06:23:49 +0000371 uint64_t Index = ByteOffset / EltSize;
372 uint64_t Offset = ByteOffset - Index * EltSize;
Chris Lattner67058832012-01-25 06:48:06 +0000373 uint64_t NumElts;
David Majnemer90a97042016-07-13 04:22:12 +0000374 if (auto *AT = dyn_cast<ArrayType>(C->getType()))
Chris Lattner67058832012-01-25 06:48:06 +0000375 NumElts = AT->getNumElements();
376 else
Matt Arsenault8c789092013-08-12 23:15:58 +0000377 NumElts = C->getType()->getVectorNumElements();
Duncan Sands0b875a02012-07-25 09:14:54 +0000378
Chris Lattner67058832012-01-25 06:48:06 +0000379 for (; Index != NumElts; ++Index) {
380 if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000381 BytesLeft, DL))
Chris Lattner67058832012-01-25 06:48:06 +0000382 return false;
Duncan Sands0b875a02012-07-25 09:14:54 +0000383
384 uint64_t BytesWritten = EltSize - Offset;
385 assert(BytesWritten <= EltSize && "Not indexing into this element?");
386 if (BytesWritten >= BytesLeft)
Chris Lattner67058832012-01-25 06:48:06 +0000387 return true;
Duncan Sands0b875a02012-07-25 09:14:54 +0000388
Chris Lattner67058832012-01-25 06:48:06 +0000389 Offset = 0;
Duncan Sands0b875a02012-07-25 09:14:54 +0000390 BytesLeft -= BytesWritten;
391 CurPtr += BytesWritten;
Chris Lattner67058832012-01-25 06:48:06 +0000392 }
393 return true;
394 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000395
David Majnemer90a97042016-07-13 04:22:12 +0000396 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Anders Carlssonecf8e152011-02-06 20:22:49 +0000397 if (CE->getOpcode() == Instruction::IntToPtr &&
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000398 CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000399 return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000400 BytesLeft, DL);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000401 }
Anders Carlssond21b06a2011-02-06 20:11:56 +0000402 }
403
Chris Lattnered00b802009-10-23 06:23:49 +0000404 // Otherwise, unknown initializer type.
405 return false;
406}
407
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000408Constant *FoldReinterpretLoadFromConstPtr(Constant *C, Type *LoadTy,
409 const DataLayout &DL) {
David Majnemer90a97042016-07-13 04:22:12 +0000410 auto *PTy = cast<PointerType>(C->getType());
411 auto *IntType = dyn_cast<IntegerType>(LoadTy);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000412
Chris Lattnered00b802009-10-23 06:23:49 +0000413 // If this isn't an integer load we can't fold it directly.
414 if (!IntType) {
Matt Arsenault7a960a82013-08-20 21:20:04 +0000415 unsigned AS = PTy->getAddressSpace();
416
Chris Lattnered00b802009-10-23 06:23:49 +0000417 // If this is a float/double load, we can try folding it as an int32/64 load
Chris Lattnerccf1e842009-10-23 06:57:37 +0000418 // and then bitcast the result. This can be useful for union cases. Note
419 // that address spaces don't matter here since we're not going to result in
420 // an actual new load.
Chris Lattner229907c2011-07-18 04:54:35 +0000421 Type *MapTy;
Owen Andersond4ebfd82013-02-06 22:43:31 +0000422 if (LoadTy->isHalfTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000423 MapTy = Type::getInt16Ty(C->getContext());
Owen Andersond4ebfd82013-02-06 22:43:31 +0000424 else if (LoadTy->isFloatTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000425 MapTy = Type::getInt32Ty(C->getContext());
Chris Lattnerccf1e842009-10-23 06:57:37 +0000426 else if (LoadTy->isDoubleTy())
Eduard Burtescu14239212016-01-22 01:17:26 +0000427 MapTy = Type::getInt64Ty(C->getContext());
Duncan Sands19d0b472010-02-16 11:11:14 +0000428 else if (LoadTy->isVectorTy()) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000429 MapTy = PointerType::getIntNTy(C->getContext(),
430 DL.getTypeAllocSizeInBits(LoadTy));
Chris Lattnerccf1e842009-10-23 06:57:37 +0000431 } else
Craig Topper9f008862014-04-15 04:59:12 +0000432 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000433
Eduard Burtescu14239212016-01-22 01:17:26 +0000434 C = FoldBitCast(C, MapTy->getPointerTo(AS), DL);
435 if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, MapTy, DL))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000436 return FoldBitCast(Res, LoadTy, DL);
Craig Topper9f008862014-04-15 04:59:12 +0000437 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000438 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000439
Chris Lattnered00b802009-10-23 06:23:49 +0000440 unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
Matt Arsenault8c789092013-08-12 23:15:58 +0000441 if (BytesLoaded > 32 || BytesLoaded == 0)
Craig Topper9f008862014-04-15 04:59:12 +0000442 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000443
Chris Lattnered00b802009-10-23 06:23:49 +0000444 GlobalValue *GVal;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000445 APInt Offset;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000446 if (!IsConstantOffsetFromGlobal(C, GVal, Offset, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000447 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000448
David Majnemer90a97042016-07-13 04:22:12 +0000449 auto *GV = dyn_cast<GlobalVariable>(GVal);
Chris Lattner3db7bd22009-10-24 05:27:19 +0000450 if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
Chris Lattnered00b802009-10-23 06:23:49 +0000451 !GV->getInitializer()->getType()->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000452 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000453
454 // If we're loading off the beginning of the global, some bytes may be valid,
455 // but we don't try to handle this.
Matt Arsenault8c789092013-08-12 23:15:58 +0000456 if (Offset.isNegative())
Craig Topper9f008862014-04-15 04:59:12 +0000457 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000458
Chris Lattnered00b802009-10-23 06:23:49 +0000459 // If we're not accessing anything in this constant, the result is undefined.
Benjamin Kramer546bb562013-01-23 21:21:24 +0000460 if (Offset.getZExtValue() >=
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000461 DL.getTypeAllocSize(GV->getInitializer()->getType()))
Chris Lattnered00b802009-10-23 06:23:49 +0000462 return UndefValue::get(IntType);
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000463
Chris Lattner59f94c02009-10-23 06:50:36 +0000464 unsigned char RawBytes[32] = {0};
Benjamin Kramer546bb562013-01-23 21:21:24 +0000465 if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000466 BytesLoaded, DL))
Craig Topper9f008862014-04-15 04:59:12 +0000467 return nullptr;
Chris Lattnered00b802009-10-23 06:23:49 +0000468
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000469 APInt ResultVal = APInt(IntType->getBitWidth(), 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000470 if (DL.isLittleEndian()) {
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000471 ResultVal = RawBytes[BytesLoaded - 1];
472 for (unsigned i = 1; i != BytesLoaded; ++i) {
473 ResultVal <<= 8;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000474 ResultVal |= RawBytes[BytesLoaded - 1 - i];
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000475 }
476 } else {
477 ResultVal = RawBytes[0];
478 for (unsigned i = 1; i != BytesLoaded; ++i) {
479 ResultVal <<= 8;
480 ResultVal |= RawBytes[i];
481 }
Chris Lattner59f94c02009-10-23 06:50:36 +0000482 }
Chris Lattnered00b802009-10-23 06:23:49 +0000483
Chris Lattner59f94c02009-10-23 06:50:36 +0000484 return ConstantInt::get(IntType->getContext(), ResultVal);
Chris Lattnered00b802009-10-23 06:23:49 +0000485}
486
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000487Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE, Type *DestTy,
488 const DataLayout &DL) {
Eduard Burtescu14239212016-01-22 01:17:26 +0000489 auto *SrcPtr = CE->getOperand(0);
490 auto *SrcPtrTy = dyn_cast<PointerType>(SrcPtr->getType());
491 if (!SrcPtrTy)
Chandler Carrutha0e56952014-05-15 09:56:28 +0000492 return nullptr;
Eduard Burtescu14239212016-01-22 01:17:26 +0000493 Type *SrcTy = SrcPtrTy->getPointerElementType();
Chandler Carrutha0e56952014-05-15 09:56:28 +0000494
Eduard Burtescu14239212016-01-22 01:17:26 +0000495 Constant *C = ConstantFoldLoadFromConstPtr(SrcPtr, SrcTy, DL);
Chandler Carrutha0e56952014-05-15 09:56:28 +0000496 if (!C)
497 return nullptr;
498
499 do {
500 Type *SrcTy = C->getType();
501
502 // If the type sizes are the same and a cast is legal, just directly
503 // cast the constant.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000504 if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
Chandler Carrutha0e56952014-05-15 09:56:28 +0000505 Instruction::CastOps Cast = Instruction::BitCast;
506 // If we are going from a pointer to int or vice versa, we spell the cast
507 // differently.
508 if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
509 Cast = Instruction::IntToPtr;
510 else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
511 Cast = Instruction::PtrToInt;
512
513 if (CastInst::castIsValid(Cast, C, DestTy))
514 return ConstantExpr::getCast(Cast, C, DestTy);
515 }
516
517 // If this isn't an aggregate type, there is nothing we can do to drill down
518 // and find a bitcastable constant.
519 if (!SrcTy->isAggregateType())
520 return nullptr;
521
522 // We're simulating a load through a pointer that was bitcast to point to
523 // a different type, so we can try to walk down through the initial
524 // elements of an aggregate to see if some part of th e aggregate is
525 // castable to implement the "load" semantic model.
526 C = C->getAggregateElement(0u);
527 } while (C);
528
529 return nullptr;
530}
531
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000532} // end anonymous namespace
533
Eduard Burtescu14239212016-01-22 01:17:26 +0000534Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C, Type *Ty,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000535 const DataLayout &DL) {
Chris Lattner1664a4f2009-10-22 06:25:11 +0000536 // First, try the easy cases:
David Majnemer90a97042016-07-13 04:22:12 +0000537 if (auto *GV = dyn_cast<GlobalVariable>(C))
Chris Lattner1664a4f2009-10-22 06:25:11 +0000538 if (GV->isConstant() && GV->hasDefinitiveInitializer())
539 return GV->getInitializer();
540
David Majnemered9abe12015-07-22 22:29:30 +0000541 if (auto *GA = dyn_cast<GlobalAlias>(C))
Sanjoy Das5ce32722016-04-08 00:48:30 +0000542 if (GA->getAliasee() && !GA->isInterposable())
Eduard Burtescu14239212016-01-22 01:17:26 +0000543 return ConstantFoldLoadFromConstPtr(GA->getAliasee(), Ty, DL);
David Majnemered9abe12015-07-22 22:29:30 +0000544
Chris Lattnercf7e8942009-10-22 06:44:07 +0000545 // If the loaded value isn't a constant expr, we can't handle it.
David Majnemer90a97042016-07-13 04:22:12 +0000546 auto *CE = dyn_cast<ConstantExpr>(C);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000547 if (!CE)
Craig Topper9f008862014-04-15 04:59:12 +0000548 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000549
Chris Lattnercf7e8942009-10-22 06:44:07 +0000550 if (CE->getOpcode() == Instruction::GetElementPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000551 if (auto *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000552 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000553 if (Constant *V =
Chris Lattnercf7e8942009-10-22 06:44:07 +0000554 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
555 return V;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000556 }
557 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000558 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000559
Chandler Carrutha0e56952014-05-15 09:56:28 +0000560 if (CE->getOpcode() == Instruction::BitCast)
Eduard Burtescu14239212016-01-22 01:17:26 +0000561 if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, Ty, DL))
Chandler Carrutha0e56952014-05-15 09:56:28 +0000562 return LoadedC;
563
Chris Lattnercf7e8942009-10-22 06:44:07 +0000564 // Instead of loading constant c string, use corresponding integer value
565 // directly if string length is small enough.
Chris Lattnercf9e8f62012-02-05 02:29:43 +0000566 StringRef Str;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000567 if (getConstantStringInfo(CE, Str) && !Str.empty()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000568 size_t StrLen = Str.size();
Chris Lattnered00b802009-10-23 06:23:49 +0000569 unsigned NumBits = Ty->getPrimitiveSizeInBits();
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000570 // Replace load with immediate integer if the result is an integer or fp
571 // value.
572 if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
Chandler Carruth57041d82010-07-12 06:47:05 +0000573 (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
Chris Lattnered00b802009-10-23 06:23:49 +0000574 APInt StrVal(NumBits, 0);
575 APInt SingleChar(NumBits, 0);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000576 if (DL.isLittleEndian()) {
David Majnemere61e4bf2016-06-21 05:10:24 +0000577 for (unsigned char C : reverse(Str.bytes())) {
578 SingleChar = static_cast<uint64_t>(C);
Chris Lattner51d2f702009-10-22 06:38:35 +0000579 StrVal = (StrVal << 8) | SingleChar;
580 }
Chris Lattnercf7e8942009-10-22 06:44:07 +0000581 } else {
David Majnemere61e4bf2016-06-21 05:10:24 +0000582 for (unsigned char C : Str.bytes()) {
583 SingleChar = static_cast<uint64_t>(C);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000584 StrVal = (StrVal << 8) | SingleChar;
585 }
586 // Append NULL at the end.
587 SingleChar = 0;
588 StrVal = (StrVal << 8) | SingleChar;
Chris Lattner51d2f702009-10-22 06:38:35 +0000589 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000590
Chris Lattnerfd4a09f2010-07-12 00:22:51 +0000591 Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
592 if (Ty->isFloatingPointTy())
593 Res = ConstantExpr::getBitCast(Res, Ty);
594 return Res;
Chris Lattner51d2f702009-10-22 06:38:35 +0000595 }
Chris Lattner1664a4f2009-10-22 06:25:11 +0000596 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000597
Chris Lattnercf7e8942009-10-22 06:44:07 +0000598 // If this load comes from anywhere in a constant global, and if the global
599 // is all undef or zero, we know what it loads.
David Majnemer90a97042016-07-13 04:22:12 +0000600 if (auto *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000601 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattnercf7e8942009-10-22 06:44:07 +0000602 if (GV->getInitializer()->isNullValue())
Eduard Burtescu14239212016-01-22 01:17:26 +0000603 return Constant::getNullValue(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000604 if (isa<UndefValue>(GV->getInitializer()))
Eduard Burtescu14239212016-01-22 01:17:26 +0000605 return UndefValue::get(Ty);
Chris Lattnercf7e8942009-10-22 06:44:07 +0000606 }
607 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000608
NAKAMURA Takumi43ab4ef2012-11-08 20:34:25 +0000609 // Try hard to fold loads from bitcasted strange and non-type-safe things.
Eduard Burtescu14239212016-01-22 01:17:26 +0000610 return FoldReinterpretLoadFromConstPtr(CE, Ty, DL);
Chris Lattner1664a4f2009-10-22 06:25:11 +0000611}
612
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000613namespace {
614
615Constant *ConstantFoldLoadInst(const LoadInst *LI, const DataLayout &DL) {
Craig Topper9f008862014-04-15 04:59:12 +0000616 if (LI->isVolatile()) return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000617
David Majnemer90a97042016-07-13 04:22:12 +0000618 if (auto *C = dyn_cast<Constant>(LI->getOperand(0)))
Eduard Burtescu14239212016-01-22 01:17:26 +0000619 return ConstantFoldLoadFromConstPtr(C, LI->getType(), DL);
Chris Lattnered00b802009-10-23 06:23:49 +0000620
Craig Topper9f008862014-04-15 04:59:12 +0000621 return nullptr;
Chris Lattner1664a4f2009-10-22 06:25:11 +0000622}
Chris Lattner44d68b92007-01-31 00:51:48 +0000623
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000624/// One of Op0/Op1 is a constant expression.
Nick Lewyckye88d3882008-12-15 01:35:36 +0000625/// Attempt to symbolically evaluate the result of a binary operator merging
Nick Lewycky06417742013-02-14 03:23:37 +0000626/// these together. If target data info is available, it is provided as DL,
627/// otherwise DL is null.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000628Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0, Constant *Op1,
629 const DataLayout &DL) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000630 // SROA
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000631
Chris Lattner44d68b92007-01-31 00:51:48 +0000632 // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
633 // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
634 // bits.
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000635
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000636 if (Opc == Instruction::And) {
637 unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
Nick Lewycky06417742013-02-14 03:23:37 +0000638 APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
639 APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
Jay Foada0653a32014-05-14 21:14:37 +0000640 computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
641 computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
Nick Lewycky06417742013-02-14 03:23:37 +0000642 if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
643 // All the bits of Op0 that the 'and' could be masking are already zero.
644 return Op0;
645 }
646 if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
647 // All the bits of Op1 that the 'and' could be masking are already zero.
648 return Op1;
649 }
650
651 APInt KnownZero = KnownZero0 | KnownZero1;
652 APInt KnownOne = KnownOne0 & KnownOne1;
653 if ((KnownZero | KnownOne).isAllOnesValue()) {
654 return ConstantInt::get(Op0->getType(), KnownOne);
655 }
656 }
657
Chris Lattner44d68b92007-01-31 00:51:48 +0000658 // If the constant expr is something like &A[123] - &A[4].f, fold this into a
659 // constant. This happens frequently when iterating over a global array.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000660 if (Opc == Instruction::Sub) {
Chris Lattner44d68b92007-01-31 00:51:48 +0000661 GlobalValue *GV1, *GV2;
Matt Arsenaulta8e89442013-11-04 20:46:52 +0000662 APInt Offs1, Offs2;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000663
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000664 if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
665 if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
666 unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
Matt Arsenaultbed5bf22013-09-12 01:07:58 +0000667
Chris Lattner44d68b92007-01-31 00:51:48 +0000668 // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
Benjamin Kramera5a9ec52013-02-05 19:04:36 +0000669 // PtrToInt may change the bitwidth so we have convert to the right size
670 // first.
671 return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
672 Offs2.zextOrTrunc(OpSize));
Chris Lattner44d68b92007-01-31 00:51:48 +0000673 }
674 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000675
Craig Topper9f008862014-04-15 04:59:12 +0000676 return nullptr;
Chris Lattner44d68b92007-01-31 00:51:48 +0000677}
678
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000679/// If array indices are not pointer-sized integers, explicitly cast them so
680/// that they aren't implicitly casted by the getelementptr.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000681Constant *CastGEPIndices(Type *SrcElemTy, ArrayRef<Constant *> Ops,
682 Type *ResultTy, const DataLayout &DL,
683 const TargetLibraryInfo *TLI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000684 Type *IntPtrTy = DL.getIntPtrType(ResultTy);
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000685
686 bool Any = false;
687 SmallVector<Constant*, 32> NewIdxs;
Jay Foadf4b14a22011-07-19 13:32:40 +0000688 for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000689 if ((i == 1 ||
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000690 !isa<StructType>(GetElementPtrInst::getIndexedType(SrcElemTy,
David Blaikied288fb82015-03-30 21:41:43 +0000691 Ops.slice(1, i - 1)))) &&
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000692 Ops[i]->getType() != IntPtrTy) {
693 Any = true;
694 NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
695 true,
696 IntPtrTy,
697 true),
698 Ops[i], IntPtrTy));
699 } else
700 NewIdxs.push_back(Ops[i]);
701 }
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000702
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000703 if (!Any)
Craig Topper9f008862014-04-15 04:59:12 +0000704 return nullptr;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000705
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000706 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ops[0], NewIdxs);
David Majnemer90a97042016-07-13 04:22:12 +0000707 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000708 if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000709 C = Folded;
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000710 }
711
Dan Gohmane5e1b7b2010-02-01 18:27:38 +0000712 return C;
713}
714
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000715/// Strip the pointer casts, but preserve the address space information.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000716Constant* StripPtrCastKeepAS(Constant* Ptr, Type *&ElemTy) {
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000717 assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
David Majnemer90a97042016-07-13 04:22:12 +0000718 auto *OldPtrTy = cast<PointerType>(Ptr->getType());
Rafael Espindola78598d92014-06-04 19:01:48 +0000719 Ptr = Ptr->stripPointerCasts();
David Majnemer90a97042016-07-13 04:22:12 +0000720 auto *NewPtrTy = cast<PointerType>(Ptr->getType());
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000721
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000722 ElemTy = NewPtrTy->getPointerElementType();
723
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000724 // Preserve the address space number of the pointer.
725 if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000726 NewPtrTy = ElemTy->getPointerTo(OldPtrTy->getAddressSpace());
Matt Arsenaultb03bd4d2013-11-15 01:34:59 +0000727 Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000728 }
729 return Ptr;
730}
731
Sanjay Patel0d7dee62014-10-02 15:13:22 +0000732/// If we can symbolically evaluate the GEP constant expression, do so.
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000733Constant *SymbolicallyEvaluateGEP(const GEPOperator *GEP,
734 ArrayRef<Constant *> Ops,
735 const DataLayout &DL,
736 const TargetLibraryInfo *TLI) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000737 Type *SrcElemTy = GEP->getSourceElementType();
738 Type *ResElemTy = GEP->getResultElementType();
739 Type *ResTy = GEP->getType();
740 if (!SrcElemTy->isSized())
741 return nullptr;
742
743 if (Constant *C = CastGEPIndices(SrcElemTy, Ops, ResTy, DL, TLI))
744 return C;
745
Chris Lattner44d68b92007-01-31 00:51:48 +0000746 Constant *Ptr = Ops[0];
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000747 if (!Ptr->getType()->isPointerTy())
Craig Topper9f008862014-04-15 04:59:12 +0000748 return nullptr;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000749
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000750 Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
Chris Lattnerf4b42f52008-05-08 04:54:43 +0000751
752 // If this is a constant expr gep that is effectively computing an
753 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
Jay Foadf4b14a22011-07-19 13:32:40 +0000754 for (unsigned i = 1, e = Ops.size(); i != e; ++i)
Chris Lattner5858e092011-01-06 06:19:46 +0000755 if (!isa<ConstantInt>(Ops[i])) {
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000756
Chris Lattner5858e092011-01-06 06:19:46 +0000757 // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
758 // "inttoptr (sub (ptrtoint Ptr), V)"
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000759 if (Ops.size() == 2 && ResElemTy->isIntegerTy(8)) {
David Majnemer90a97042016-07-13 04:22:12 +0000760 auto *CE = dyn_cast<ConstantExpr>(Ops[1]);
Craig Topper9f008862014-04-15 04:59:12 +0000761 assert((!CE || CE->getType() == IntPtrTy) &&
Chris Lattner171608e2011-01-06 22:24:29 +0000762 "CastGEPIndices didn't canonicalize index types!");
Chris Lattner5858e092011-01-06 06:19:46 +0000763 if (CE && CE->getOpcode() == Instruction::Sub &&
Chris Lattner171608e2011-01-06 22:24:29 +0000764 CE->getOperand(0)->isNullValue()) {
Chris Lattner5858e092011-01-06 06:19:46 +0000765 Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
766 Res = ConstantExpr::getSub(Res, CE->getOperand(1));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000767 Res = ConstantExpr::getIntToPtr(Res, ResTy);
David Majnemer90a97042016-07-13 04:22:12 +0000768 if (auto *ResCE = dyn_cast<ConstantExpr>(Res))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000769 Res = ConstantFoldConstantExpression(ResCE, DL, TLI);
Chris Lattner5858e092011-01-06 06:19:46 +0000770 return Res;
771 }
772 }
Craig Topper9f008862014-04-15 04:59:12 +0000773 return nullptr;
Chris Lattner5858e092011-01-06 06:19:46 +0000774 }
Nadav Rotem77f1b9c2012-07-30 07:25:20 +0000775
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000776 unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
Jay Foadbf904772011-07-19 14:01:37 +0000777 APInt Offset =
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000778 APInt(BitWidth,
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000779 DL.getIndexedOffsetInType(
780 SrcElemTy,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000781 makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000782 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000783
784 // If this is a GEP of a GEP, fold it all into a single GEP.
David Majnemer90a97042016-07-13 04:22:12 +0000785 while (auto *GEP = dyn_cast<GEPOperator>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000786 SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
Duncan Sands8c355062010-03-12 17:55:20 +0000787
788 // Do not try the incorporate the sub-GEP if some index is not a number.
789 bool AllConstantInt = true;
David Majnemer90a97042016-07-13 04:22:12 +0000790 for (Value *NestedOp : NestedOps)
791 if (!isa<ConstantInt>(NestedOp)) {
Duncan Sands8c355062010-03-12 17:55:20 +0000792 AllConstantInt = false;
793 break;
794 }
795 if (!AllConstantInt)
796 break;
797
Dan Gohman474e488c2010-03-10 19:31:51 +0000798 Ptr = cast<Constant>(GEP->getOperand(0));
Eduard Burtescu68e7f492016-01-22 03:08:27 +0000799 SrcElemTy = GEP->getSourceElementType();
800 Offset += APInt(BitWidth, DL.getIndexedOffsetInType(SrcElemTy, NestedOps));
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000801 Ptr = StripPtrCastKeepAS(Ptr, SrcElemTy);
Dan Gohman474e488c2010-03-10 19:31:51 +0000802 }
803
Dan Gohman81ce8422009-08-19 18:18:36 +0000804 // If the base value for this address is a literal integer value, fold the
805 // getelementptr to the resulting integer value casted to the pointer type.
Dan Gohmana5ca5782010-03-18 19:34:33 +0000806 APInt BasePtr(BitWidth, 0);
David Majnemer90a97042016-07-13 04:22:12 +0000807 if (auto *CE = dyn_cast<ConstantExpr>(Ptr)) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000808 if (CE->getOpcode() == Instruction::IntToPtr) {
David Majnemer90a97042016-07-13 04:22:12 +0000809 if (auto *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
Jay Foad583abbc2010-12-07 08:25:19 +0000810 BasePtr = Base->getValue().zextOrTrunc(BitWidth);
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000811 }
812 }
813
Dan Gohmana5ca5782010-03-18 19:34:33 +0000814 if (Ptr->isNullValue() || BasePtr != 0) {
Matt Arsenaulta5e56982013-08-12 22:56:15 +0000815 Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000816 return ConstantExpr::getIntToPtr(C, ResTy);
Dan Gohman81ce8422009-08-19 18:18:36 +0000817 }
818
819 // Otherwise form a regular getelementptr. Recompute the indices so that
820 // we eliminate over-indexing of the notional static type array bounds.
821 // This makes it easy to determine if the getelementptr is "inbounds".
822 // Also, this helps GlobalOpt do SROA on GlobalVariables.
Chris Lattner229907c2011-07-18 04:54:35 +0000823 Type *Ty = Ptr->getType();
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000824 assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
Matt Arsenault7a960a82013-08-20 21:20:04 +0000825 SmallVector<Constant *, 32> NewIdxs;
826
Dan Gohmanc59ba422009-08-19 22:46:59 +0000827 do {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000828 if (!Ty->isStructTy()) {
829 if (Ty->isPointerTy()) {
Chris Lattner77c36d62009-12-03 01:05:45 +0000830 // The only pointer indexing we'll do is on the first index of the GEP.
831 if (!NewIdxs.empty())
832 break;
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000833
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000834 Ty = SrcElemTy;
835
Chris Lattner77c36d62009-12-03 01:05:45 +0000836 // Only handle pointers to sized types, not pointers to functions.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000837 if (!Ty->isSized())
Craig Topper9f008862014-04-15 04:59:12 +0000838 return nullptr;
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000839 } else if (auto *ATy = dyn_cast<SequentialType>(Ty)) {
840 Ty = ATy->getElementType();
841 } else {
842 // We've reached some non-indexable type.
843 break;
Chris Lattner77c36d62009-12-03 01:05:45 +0000844 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +0000845
Dan Gohman81ce8422009-08-19 18:18:36 +0000846 // Determine which element of the array the offset points into.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000847 APInt ElemSize(BitWidth, DL.getTypeAllocSize(Ty));
Dan Gohman81ce8422009-08-19 18:18:36 +0000848 if (ElemSize == 0)
Chris Lattner6ce03802010-11-21 08:39:01 +0000849 // The element size is 0. This may be [0 x Ty]*, so just use a zero
Duncan Sands1f86be92010-11-21 12:43:13 +0000850 // index for this level and proceed to the next level to see if it can
851 // accommodate the offset.
Chris Lattner6ce03802010-11-21 08:39:01 +0000852 NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
853 else {
854 // The element size is non-zero divide the offset by the element
855 // size (rounding down), to compute the index at this level.
856 APInt NewIdx = Offset.udiv(ElemSize);
857 Offset -= NewIdx * ElemSize;
858 NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
859 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000860 } else {
David Majnemer90a97042016-07-13 04:22:12 +0000861 auto *STy = cast<StructType>(Ty);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000862 // If we end up with an offset that isn't valid for this struct type, we
863 // can't re-form this GEP in a regular form, so bail out. The pointer
864 // operand likely went through casts that are necessary to make the GEP
865 // sensible.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000866 const StructLayout &SL = *DL.getStructLayout(STy);
Chandler Carruthaacb8a52012-04-24 18:42:47 +0000867 if (Offset.uge(SL.getSizeInBytes()))
868 break;
869
870 // Determine which field of the struct the offset points into. The
871 // getZExtValue is fine as we've already ensured that the offset is
872 // within the range representable by the StructLayout API.
Dan Gohman23e62c52009-08-21 16:52:54 +0000873 unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
Chris Lattner46b5c642009-11-06 04:27:31 +0000874 NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
875 ElIdx));
Dan Gohman23e62c52009-08-21 16:52:54 +0000876 Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
Dan Gohman81ce8422009-08-19 18:18:36 +0000877 Ty = STy->getTypeAtIndex(ElIdx);
Dan Gohman81ce8422009-08-19 18:18:36 +0000878 }
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000879 } while (Ty != ResElemTy);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000880
881 // If we haven't used up the entire offset by descending the static
882 // type, then the offset is pointing into the middle of an indivisible
883 // member, so we can't simplify it.
884 if (Offset != 0)
Craig Topper9f008862014-04-15 04:59:12 +0000885 return nullptr;
Dan Gohman81ce8422009-08-19 18:18:36 +0000886
Dan Gohman21c62162009-09-11 00:04:14 +0000887 // Create a GEP.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000888 Constant *C = ConstantExpr::getGetElementPtr(SrcElemTy, Ptr, NewIdxs);
Matt Arsenault8c789092013-08-12 23:15:58 +0000889 assert(C->getType()->getPointerElementType() == Ty &&
Dan Gohmane4ca02d2009-09-03 23:34:49 +0000890 "Computed GetElementPtr has unexpected type!");
Dan Gohman81ce8422009-08-19 18:18:36 +0000891
Dan Gohmanc59ba422009-08-19 22:46:59 +0000892 // If we ended up indexing a member with a type that doesn't match
Dan Gohman8a8ad7d2009-08-20 16:42:55 +0000893 // the type of what the original indices indexed, add a cast.
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000894 if (Ty != ResElemTy)
895 C = FoldBitCast(C, ResTy, DL);
Dan Gohmanc59ba422009-08-19 22:46:59 +0000896
897 return C;
Chris Lattner44d68b92007-01-31 00:51:48 +0000898}
899
Manuel Jacobe9024592016-01-21 06:33:22 +0000900/// Attempt to constant fold an instruction with the
901/// specified opcode and operands. If successful, the constant result is
902/// returned, if not, null is returned. Note that this function can fail when
903/// attempting to fold instructions like loads and stores, which have no
904/// constant expression form.
905///
906/// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
907/// information, due to only being passed an opcode and operands. Constant
908/// folding using this function strips this information.
909///
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000910Constant *ConstantFoldInstOperandsImpl(const Value *InstOrCE, Type *DestTy,
911 unsigned Opcode,
912 ArrayRef<Constant *> Ops,
913 const DataLayout &DL,
914 const TargetLibraryInfo *TLI) {
Manuel Jacobe9024592016-01-21 06:33:22 +0000915 // Handle easy binops first.
916 if (Instruction::isBinaryOp(Opcode))
917 return ConstantFoldBinaryOpOperands(Opcode, Ops[0], Ops[1], DL);
918
919 if (Instruction::isCast(Opcode))
920 return ConstantFoldCastOperand(Opcode, Ops[0], DestTy, DL);
921
David Majnemer17bdf442016-07-13 03:42:38 +0000922 if (auto *GEP = dyn_cast<GEPOperator>(InstOrCE)) {
Eduard Burtescu2f4758b2016-01-21 23:42:06 +0000923 if (Constant *C = SymbolicallyEvaluateGEP(GEP, Ops, DL, TLI))
924 return C;
925
926 return ConstantExpr::getGetElementPtr(GEP->getSourceElementType(),
927 Ops[0], Ops.slice(1));
928 }
929
Manuel Jacobe9024592016-01-21 06:33:22 +0000930 switch (Opcode) {
931 default: return nullptr;
932 case Instruction::ICmp:
933 case Instruction::FCmp: llvm_unreachable("Invalid for compares");
934 case Instruction::Call:
David Majnemer90a97042016-07-13 04:22:12 +0000935 if (auto *F = dyn_cast<Function>(Ops.back()))
Manuel Jacobe9024592016-01-21 06:33:22 +0000936 if (canConstantFoldCallTo(F))
937 return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
938 return nullptr;
939 case Instruction::Select:
940 return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
941 case Instruction::ExtractElement:
942 return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
943 case Instruction::InsertElement:
944 return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
945 case Instruction::ShuffleVector:
946 return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
Manuel Jacobe9024592016-01-21 06:33:22 +0000947 }
948}
949
Eugene Zelenko35623fb2016-03-28 17:40:08 +0000950} // end anonymous namespace
Chris Lattner44d68b92007-01-31 00:51:48 +0000951
952//===----------------------------------------------------------------------===//
953// Constant Folding public APIs
954//===----------------------------------------------------------------------===//
955
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000956Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +0000957 const TargetLibraryInfo *TLI) {
Duncan Sands763dec02010-11-23 10:16:18 +0000958 // Handle PHI nodes quickly here...
David Majnemer90a97042016-07-13 04:22:12 +0000959 if (auto *PN = dyn_cast<PHINode>(I)) {
Craig Topper9f008862014-04-15 04:59:12 +0000960 Constant *CommonValue = nullptr;
John Criswell970af112005-10-27 16:00:10 +0000961
Pete Cooper833f34d2015-05-12 20:05:31 +0000962 for (Value *Incoming : PN->incoming_values()) {
Duncan Sands763dec02010-11-23 10:16:18 +0000963 // If the incoming value is undef then skip it. Note that while we could
964 // skip the value if it is equal to the phi node itself we choose not to
965 // because that would break the rule that constant folding only applies if
966 // all operands are constants.
967 if (isa<UndefValue>(Incoming))
Duncan Sands1d27f0122010-11-14 12:53:18 +0000968 continue;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000969 // If the incoming value is not a constant, then give up.
David Majnemer90a97042016-07-13 04:22:12 +0000970 auto *C = dyn_cast<Constant>(Incoming);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000971 if (!C)
Craig Topper9f008862014-04-15 04:59:12 +0000972 return nullptr;
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000973 // Fold the PHI's operands.
David Majnemer90a97042016-07-13 04:22:12 +0000974 if (auto *NewC = dyn_cast<ConstantExpr>(C))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000975 C = ConstantFoldConstantExpression(NewC, DL, TLI);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000976 // If the incoming value is a different constant to
977 // the one we saw previously, then give up.
978 if (CommonValue && C != CommonValue)
Craig Topper9f008862014-04-15 04:59:12 +0000979 return nullptr;
Duncan Sands1d27f0122010-11-14 12:53:18 +0000980 CommonValue = C;
981 }
Chris Lattner2ae054a2007-01-30 23:45:45 +0000982
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000983
Duncan Sands1d27f0122010-11-14 12:53:18 +0000984 // If we reach here, all incoming values are the same constant or undef.
985 return CommonValue ? CommonValue : UndefValue::get(PN->getType());
Chris Lattner2ae054a2007-01-30 23:45:45 +0000986 }
987
988 // Scan the operand list, checking to see if they are all constants, if so,
Manuel Jacobe9024592016-01-21 06:33:22 +0000989 // hand off to ConstantFoldInstOperandsImpl.
Fiona Glaser2e5c0c22016-03-13 05:36:15 +0000990 if (!all_of(I->operands(), [](Use &U) { return isa<Constant>(U); }))
991 return nullptr;
Chris Lattner2ae054a2007-01-30 23:45:45 +0000992
Fiona Glaser2e5c0c22016-03-13 05:36:15 +0000993 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +0000994 for (const Use &OpU : I->operands()) {
995 auto *Op = cast<Constant>(&OpU);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000996 // Fold the Instruction's operands.
David Majnemer90a97042016-07-13 04:22:12 +0000997 if (auto *NewCE = dyn_cast<ConstantExpr>(Op))
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000998 Op = ConstantFoldConstantExpression(NewCE, DL, TLI);
Dan Gohman1ccecdb2012-04-27 17:50:22 +0000999
1000 Ops.push_back(Op);
1001 }
1002
David Majnemer90a97042016-07-13 04:22:12 +00001003 if (const auto *CI = dyn_cast<CmpInst>(I))
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001004 return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001005 DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001006
David Majnemer90a97042016-07-13 04:22:12 +00001007 if (const auto *LI = dyn_cast<LoadInst>(I))
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001008 return ConstantFoldLoadInst(LI, DL);
Frits van Bommela98214d2010-11-29 20:36:52 +00001009
David Majnemer90a97042016-07-13 04:22:12 +00001010 if (auto *IVI = dyn_cast<InsertValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001011 return ConstantExpr::getInsertValue(
1012 cast<Constant>(IVI->getAggregateOperand()),
1013 cast<Constant>(IVI->getInsertedValueOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001014 IVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001015 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001016
David Majnemer90a97042016-07-13 04:22:12 +00001017 if (auto *EVI = dyn_cast<ExtractValueInst>(I)) {
Frits van Bommela98214d2010-11-29 20:36:52 +00001018 return ConstantExpr::getExtractValue(
1019 cast<Constant>(EVI->getAggregateOperand()),
Jay Foad57aa6362011-07-13 10:26:04 +00001020 EVI->getIndices());
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001021 }
Frits van Bommela98214d2010-11-29 20:36:52 +00001022
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001023 return ConstantFoldInstOperands(I, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001024}
1025
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001026namespace {
1027
1028Constant *
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001029ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout &DL,
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001030 const TargetLibraryInfo *TLI,
Craig Topper71b7b682014-08-21 05:55:13 +00001031 SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001032 SmallVector<Constant *, 8> Ops;
David Majnemer90a97042016-07-13 04:22:12 +00001033 for (const Use &NewU : CE->operands()) {
1034 auto *NewC = cast<Constant>(&NewU);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001035 // Recursively fold the ConstantExpr's operands. If we have already folded
1036 // a ConstantExpr, we don't have to process it again.
David Majnemer90a97042016-07-13 04:22:12 +00001037 if (auto *NewCE = dyn_cast<ConstantExpr>(NewC)) {
David Blaikie70573dc2014-11-19 07:49:26 +00001038 if (FoldedOps.insert(NewCE).second)
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001039 NewC = ConstantFoldConstantExpressionImpl(NewCE, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001040 }
Dan Gohman580b80d2009-11-23 16:22:21 +00001041 Ops.push_back(NewC);
1042 }
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001043
1044 if (CE->isCompare())
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001045 return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001046 DL, TLI);
Eduard Burtescu2f4758b2016-01-21 23:42:06 +00001047
Manuel Jacob6be35592016-03-14 22:34:17 +00001048 return ConstantFoldInstOperandsImpl(CE, CE->getType(), CE->getOpcode(), Ops,
1049 DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001050}
1051
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001052} // end anonymous namespace
1053
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001054Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001055 const DataLayout &DL,
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001056 const TargetLibraryInfo *TLI) {
1057 SmallPtrSet<ConstantExpr *, 4> FoldedOps;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001058 return ConstantFoldConstantExpressionImpl(CE, DL, TLI, FoldedOps);
Benjamin Kramer89ca4bc2013-04-13 12:53:18 +00001059}
1060
Manuel Jacobe9024592016-01-21 06:33:22 +00001061Constant *llvm::ConstantFoldInstOperands(Instruction *I,
Jay Foadf4b14a22011-07-19 13:32:40 +00001062 ArrayRef<Constant *> Ops,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001063 const DataLayout &DL,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001064 const TargetLibraryInfo *TLI) {
Manuel Jacob6be35592016-03-14 22:34:17 +00001065 return ConstantFoldInstOperandsImpl(I, I->getType(), I->getOpcode(), Ops, DL,
1066 TLI);
1067}
1068
1069Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
1070 ArrayRef<Constant *> Ops,
1071 const DataLayout &DL,
1072 const TargetLibraryInfo *TLI) {
1073 assert(Opcode != Instruction::GetElementPtr && "Invalid for GEPs");
1074 return ConstantFoldInstOperandsImpl(nullptr, DestTy, Opcode, Ops, DL, TLI);
Chris Lattner2ae054a2007-01-30 23:45:45 +00001075}
1076
Chris Lattnerd2265b42007-12-10 22:53:04 +00001077Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001078 Constant *Ops0, Constant *Ops1,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001079 const DataLayout &DL,
Chad Rosierc24b86f2011-12-01 03:08:23 +00001080 const TargetLibraryInfo *TLI) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001081 // fold: icmp (inttoptr x), null -> icmp x, 0
1082 // fold: icmp (ptrtoint x), 0 -> icmp x, null
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001083 // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
Chris Lattnerd2265b42007-12-10 22:53:04 +00001084 // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
1085 //
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001086 // FIXME: The following comment is out of data and the DataLayout is here now.
1087 // ConstantExpr::getCompare cannot do this, because it doesn't have DL
Chris Lattnerd2265b42007-12-10 22:53:04 +00001088 // around to know if bit truncation is happening.
David Majnemer90a97042016-07-13 04:22:12 +00001089 if (auto *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001090 if (Ops1->isNullValue()) {
Chris Lattnerd2265b42007-12-10 22:53:04 +00001091 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001092 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Chris Lattnerd2265b42007-12-10 22:53:04 +00001093 // Convert the integer value to the right size to ensure we get the
1094 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001095 Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Chris Lattnerd2265b42007-12-10 22:53:04 +00001096 IntPtrTy, false);
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001097 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001098 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001099 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001100
Chris Lattnerd2265b42007-12-10 22:53:04 +00001101 // Only do this transformation if the int is intptrty in size, otherwise
1102 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001103 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001104 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001105 if (CE0->getType() == IntPtrTy) {
1106 Constant *C = CE0->getOperand(0);
1107 Constant *Null = Constant::getNullValue(C->getType());
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001108 return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001109 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001110 }
1111 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001112
David Majnemer90a97042016-07-13 04:22:12 +00001113 if (auto *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001114 if (CE0->getOpcode() == CE1->getOpcode()) {
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001115 if (CE0->getOpcode() == Instruction::IntToPtr) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001116 Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001117
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001118 // Convert the integer value to the right size to ensure we get the
1119 // proper extension or truncation.
Owen Anderson487375e2009-07-29 18:55:55 +00001120 Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001121 IntPtrTy, false);
Owen Anderson487375e2009-07-29 18:55:55 +00001122 Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001123 IntPtrTy, false);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001124 return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
Nick Lewyckyf6ccd252008-05-25 20:56:15 +00001125 }
1126
Chandler Carruth7ec50852012-11-01 08:07:29 +00001127 // Only do this transformation if the int is intptrty in size, otherwise
1128 // there is a truncation or extension that we aren't modeling.
Matt Arsenault7a960a82013-08-20 21:20:04 +00001129 if (CE0->getOpcode() == Instruction::PtrToInt) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001130 Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
Matt Arsenault7a960a82013-08-20 21:20:04 +00001131 if (CE0->getType() == IntPtrTy &&
1132 CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001133 return ConstantFoldCompareInstOperands(
1134 Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
Matt Arsenault7a960a82013-08-20 21:20:04 +00001135 }
1136 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001137 }
1138 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001139
Chris Lattner8fb74c62010-01-02 01:22:23 +00001140 // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
1141 // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
1142 if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
1143 CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001144 Constant *LHS = ConstantFoldCompareInstOperands(
1145 Predicate, CE0->getOperand(0), Ops1, DL, TLI);
1146 Constant *RHS = ConstantFoldCompareInstOperands(
1147 Predicate, CE0->getOperand(1), Ops1, DL, TLI);
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001148 unsigned OpC =
Chris Lattner8fb74c62010-01-02 01:22:23 +00001149 Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
Manuel Jacoba61ca372016-01-21 06:26:35 +00001150 return ConstantFoldBinaryOpOperands(OpC, LHS, RHS, DL);
Chris Lattner8fb74c62010-01-02 01:22:23 +00001151 }
Chris Lattnerd2265b42007-12-10 22:53:04 +00001152 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001153
Chris Lattnercdfb80d2009-11-09 23:06:58 +00001154 return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
Chris Lattnerd2265b42007-12-10 22:53:04 +00001155}
1156
Manuel Jacoba61ca372016-01-21 06:26:35 +00001157Constant *llvm::ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS,
1158 Constant *RHS,
1159 const DataLayout &DL) {
1160 assert(Instruction::isBinaryOp(Opcode));
1161 if (isa<ConstantExpr>(LHS) || isa<ConstantExpr>(RHS))
1162 if (Constant *C = SymbolicallyEvaluateBinop(Opcode, LHS, RHS, DL))
1163 return C;
1164
1165 return ConstantExpr::get(Opcode, LHS, RHS);
1166}
Chris Lattnerd2265b42007-12-10 22:53:04 +00001167
Manuel Jacob925d0292016-01-21 06:31:08 +00001168Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1169 Type *DestTy, const DataLayout &DL) {
1170 assert(Instruction::isCast(Opcode));
1171 switch (Opcode) {
1172 default:
1173 llvm_unreachable("Missing case");
1174 case Instruction::PtrToInt:
1175 // If the input is a inttoptr, eliminate the pair. This requires knowing
1176 // the width of a pointer, so it can't be done in ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001177 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001178 if (CE->getOpcode() == Instruction::IntToPtr) {
1179 Constant *Input = CE->getOperand(0);
1180 unsigned InWidth = Input->getType()->getScalarSizeInBits();
1181 unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
1182 if (PtrWidth < InWidth) {
1183 Constant *Mask =
1184 ConstantInt::get(CE->getContext(),
1185 APInt::getLowBitsSet(InWidth, PtrWidth));
1186 Input = ConstantExpr::getAnd(Input, Mask);
1187 }
1188 // Do a zext or trunc to get to the dest size.
1189 return ConstantExpr::getIntegerCast(Input, DestTy, false);
1190 }
1191 }
1192 return ConstantExpr::getCast(Opcode, C, DestTy);
1193 case Instruction::IntToPtr:
1194 // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
1195 // the int size is >= the ptr size and the address spaces are the same.
1196 // This requires knowing the width of a pointer, so it can't be done in
1197 // ConstantExpr::getCast.
David Majnemer90a97042016-07-13 04:22:12 +00001198 if (auto *CE = dyn_cast<ConstantExpr>(C)) {
Manuel Jacob925d0292016-01-21 06:31:08 +00001199 if (CE->getOpcode() == Instruction::PtrToInt) {
1200 Constant *SrcPtr = CE->getOperand(0);
1201 unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
1202 unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
1203
1204 if (MidIntSize >= SrcPtrSize) {
1205 unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
1206 if (SrcAS == DestTy->getPointerAddressSpace())
1207 return FoldBitCast(CE->getOperand(0), DestTy, DL);
1208 }
1209 }
1210 }
1211
1212 return ConstantExpr::getCast(Opcode, C, DestTy);
1213 case Instruction::Trunc:
1214 case Instruction::ZExt:
1215 case Instruction::SExt:
1216 case Instruction::FPTrunc:
1217 case Instruction::FPExt:
1218 case Instruction::UIToFP:
1219 case Instruction::SIToFP:
1220 case Instruction::FPToUI:
1221 case Instruction::FPToSI:
1222 case Instruction::AddrSpaceCast:
1223 return ConstantExpr::getCast(Opcode, C, DestTy);
1224 case Instruction::BitCast:
1225 return FoldBitCast(C, DestTy, DL);
1226 }
1227}
1228
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001229Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
Dan Gohmane525d9d2009-10-05 16:36:26 +00001230 ConstantExpr *CE) {
Chris Lattnerf488b352012-01-24 05:43:50 +00001231 if (!CE->getOperand(1)->isNullValue())
Craig Topper9f008862014-04-15 04:59:12 +00001232 return nullptr; // Do not allow stepping over the value!
Chris Lattner67058832012-01-25 06:48:06 +00001233
1234 // Loop over all of the operands, tracking down which value we are
1235 // addressing.
1236 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
1237 C = C->getAggregateElement(CE->getOperand(i));
Craig Topper9f008862014-04-15 04:59:12 +00001238 if (!C)
1239 return nullptr;
Chris Lattner67058832012-01-25 06:48:06 +00001240 }
1241 return C;
Chris Lattnerf488b352012-01-24 05:43:50 +00001242}
1243
David Majnemer90a97042016-07-13 04:22:12 +00001244Constant *
1245llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
1246 ArrayRef<Constant *> Indices) {
Chris Lattner2ae054a2007-01-30 23:45:45 +00001247 // Loop over all of the operands, tracking down which value we are
Chris Lattnerf488b352012-01-24 05:43:50 +00001248 // addressing.
David Majnemer90a97042016-07-13 04:22:12 +00001249 for (Constant *Index : Indices) {
1250 C = C->getAggregateElement(Index);
Craig Topper9f008862014-04-15 04:59:12 +00001251 if (!C)
1252 return nullptr;
Chris Lattnerf488b352012-01-24 05:43:50 +00001253 }
Chris Lattner2ae054a2007-01-30 23:45:45 +00001254 return C;
1255}
1256
Chris Lattner2ae054a2007-01-30 23:45:45 +00001257//===----------------------------------------------------------------------===//
1258// Constant Folding for Calls
1259//
John Criswell970af112005-10-27 16:00:10 +00001260
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001261bool llvm::canConstantFoldCallTo(const Function *F) {
John Criswell970af112005-10-27 16:00:10 +00001262 switch (F->getIntrinsicID()) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001263 case Intrinsic::fabs:
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001264 case Intrinsic::minnum:
1265 case Intrinsic::maxnum:
Owen Andersond4ebfd82013-02-06 22:43:31 +00001266 case Intrinsic::log:
1267 case Intrinsic::log2:
1268 case Intrinsic::log10:
1269 case Intrinsic::exp:
1270 case Intrinsic::exp2:
1271 case Intrinsic::floor:
Karthik Bhat195e9dd2014-03-24 04:36:06 +00001272 case Intrinsic::ceil:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001273 case Intrinsic::sqrt:
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001274 case Intrinsic::sin:
1275 case Intrinsic::cos:
Karthik Bhatd818e382015-07-21 08:52:23 +00001276 case Intrinsic::trunc:
1277 case Intrinsic::rint:
1278 case Intrinsic::nearbyint:
Chad Rosier0155a632011-12-03 00:00:03 +00001279 case Intrinsic::pow:
Dale Johannesen4d4e77a2007-10-02 17:43:59 +00001280 case Intrinsic::powi:
Reid Spencer6bba6c82007-04-01 07:35:23 +00001281 case Intrinsic::bswap:
1282 case Intrinsic::ctpop:
1283 case Intrinsic::ctlz:
1284 case Intrinsic::cttz:
Matt Arsenault83778582014-03-05 00:02:00 +00001285 case Intrinsic::fma:
1286 case Intrinsic::fmuladd:
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001287 case Intrinsic::copysign:
Karthik Bhatb67688a2014-03-07 04:36:21 +00001288 case Intrinsic::round:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001289 case Intrinsic::sadd_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001290 case Intrinsic::uadd_with_overflow:
Evan Phoenix44e5dbc2009-10-05 22:53:52 +00001291 case Intrinsic::ssub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001292 case Intrinsic::usub_with_overflow:
Chris Lattner698661c2010-10-14 00:05:07 +00001293 case Intrinsic::smul_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001294 case Intrinsic::umul_with_overflow:
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001295 case Intrinsic::convert_from_fp16:
1296 case Intrinsic::convert_to_fp16:
Matt Arsenault155dda92016-03-21 15:00:35 +00001297 case Intrinsic::bitreverse:
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001298 case Intrinsic::x86_sse_cvtss2si:
1299 case Intrinsic::x86_sse_cvtss2si64:
1300 case Intrinsic::x86_sse_cvttss2si:
1301 case Intrinsic::x86_sse_cvttss2si64:
1302 case Intrinsic::x86_sse2_cvtsd2si:
1303 case Intrinsic::x86_sse2_cvtsd2si64:
1304 case Intrinsic::x86_sse2_cvttsd2si:
1305 case Intrinsic::x86_sse2_cvttsd2si64:
John Criswell970af112005-10-27 16:00:10 +00001306 return true;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001307 default:
1308 return false;
1309 case 0: break;
John Criswell970af112005-10-27 16:00:10 +00001310 }
1311
Matt Arsenaulta5e56982013-08-12 22:56:15 +00001312 if (!F->hasName())
1313 return false;
Daniel Dunbarca414c72009-07-26 08:34:35 +00001314 StringRef Name = F->getName();
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001315
Chris Lattner785f9982007-08-08 06:55:43 +00001316 // In these cases, the check of the length is required. We don't want to
1317 // return true for a name like "cos\0blah" which strcmp would return equal to
1318 // "cos", but has length 8.
Daniel Dunbarca414c72009-07-26 08:34:35 +00001319 switch (Name[0]) {
Erik Schnetter5e93e282015-08-27 19:56:57 +00001320 default:
1321 return false;
Chris Lattner785f9982007-08-08 06:55:43 +00001322 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001323 return Name == "acos" || Name == "asin" || Name == "atan" ||
1324 Name == "atan2" || Name == "acosf" || Name == "asinf" ||
1325 Name == "atanf" || Name == "atan2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001326 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001327 return Name == "ceil" || Name == "cos" || Name == "cosh" ||
1328 Name == "ceilf" || Name == "cosf" || Name == "coshf";
Chris Lattner785f9982007-08-08 06:55:43 +00001329 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001330 return Name == "exp" || Name == "exp2" || Name == "expf" || Name == "exp2f";
Chris Lattner785f9982007-08-08 06:55:43 +00001331 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001332 return Name == "fabs" || Name == "floor" || Name == "fmod" ||
1333 Name == "fabsf" || Name == "floorf" || Name == "fmodf";
Chris Lattner785f9982007-08-08 06:55:43 +00001334 case 'l':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001335 return Name == "log" || Name == "log10" || Name == "logf" ||
1336 Name == "log10f";
Chris Lattner785f9982007-08-08 06:55:43 +00001337 case 'p':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001338 return Name == "pow" || Name == "powf";
Chris Lattner785f9982007-08-08 06:55:43 +00001339 case 's':
Daniel Dunbarca414c72009-07-26 08:34:35 +00001340 return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
Erik Schnetter5e93e282015-08-27 19:56:57 +00001341 Name == "sinf" || Name == "sinhf" || Name == "sqrtf";
Chris Lattner785f9982007-08-08 06:55:43 +00001342 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001343 return Name == "tan" || Name == "tanh" || Name == "tanf" || Name == "tanhf";
John Criswell970af112005-10-27 16:00:10 +00001344 }
1345}
1346
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001347namespace {
1348
1349Constant *GetConstantFoldFPValue(double V, Type *Ty) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001350 if (Ty->isHalfTy()) {
1351 APFloat APF(V);
1352 bool unused;
1353 APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
1354 return ConstantFP::get(Ty->getContext(), APF);
1355 }
Chris Lattner351534f2009-10-05 05:06:24 +00001356 if (Ty->isFloatTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001357 return ConstantFP::get(Ty->getContext(), APFloat((float)V));
Chris Lattner351534f2009-10-05 05:06:24 +00001358 if (Ty->isDoubleTy())
Chris Lattner46b5c642009-11-06 04:27:31 +00001359 return ConstantFP::get(Ty->getContext(), APFloat(V));
Owen Andersond4ebfd82013-02-06 22:43:31 +00001360 llvm_unreachable("Can only constant fold half/float/double");
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001361}
1362
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001363/// Clear the floating-point exception state.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001364inline void llvm_fenv_clearexcept() {
Alp Toker51420a82014-06-09 19:00:52 +00001365#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001366 feclearexcept(FE_ALL_EXCEPT);
1367#endif
1368 errno = 0;
1369}
1370
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001371/// Test if a floating-point exception was raised.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001372inline bool llvm_fenv_testexcept() {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001373 int errno_val = errno;
1374 if (errno_val == ERANGE || errno_val == EDOM)
1375 return true;
Alp Toker51420a82014-06-09 19:00:52 +00001376#if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
Alp Tokerc817d6a2014-06-09 18:28:53 +00001377 if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
1378 return true;
1379#endif
1380 return false;
1381}
Alp Tokerc817d6a2014-06-09 18:28:53 +00001382
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001383Constant *ConstantFoldFP(double (*NativeFP)(double), double V, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001384 llvm_fenv_clearexcept();
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001385 V = NativeFP(V);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001386 if (llvm_fenv_testexcept()) {
1387 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001388 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001389 }
1390
1391 return GetConstantFoldFPValue(V, Ty);
John Criswell970af112005-10-27 16:00:10 +00001392}
1393
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001394Constant *ConstantFoldBinaryFP(double (*NativeFP)(double, double), double V,
1395 double W, Type *Ty) {
Alp Tokerc817d6a2014-06-09 18:28:53 +00001396 llvm_fenv_clearexcept();
Dan Gohman72efc042007-07-16 15:26:22 +00001397 V = NativeFP(V, W);
Alp Tokerc817d6a2014-06-09 18:28:53 +00001398 if (llvm_fenv_testexcept()) {
1399 llvm_fenv_clearexcept();
Craig Topper9f008862014-04-15 04:59:12 +00001400 return nullptr;
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001401 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001402
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001403 return GetConstantFoldFPValue(V, Ty);
Dan Gohman72efc042007-07-16 15:26:22 +00001404}
1405
Sanjay Patel0d7dee62014-10-02 15:13:22 +00001406/// Attempt to fold an SSE floating point to integer conversion of a constant
1407/// floating point. If roundTowardZero is false, the default IEEE rounding is
1408/// used (toward nearest, ties to even). This matches the behavior of the
1409/// non-truncating SSE instructions in the default rounding mode. The desired
1410/// integer type Ty is used to select how many bits are available for the
1411/// result. Returns null if the conversion cannot be performed, otherwise
1412/// returns the Constant value resulting from the conversion.
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001413Constant *ConstantFoldConvertToInt(const APFloat &Val, bool roundTowardZero,
1414 Type *Ty) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001415 // All of these conversion intrinsics form an integer of at most 64bits.
Matt Arsenault8c789092013-08-12 23:15:58 +00001416 unsigned ResultWidth = Ty->getIntegerBitWidth();
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001417 assert(ResultWidth <= 64 &&
1418 "Can only constant fold conversions to 64 and 32 bit ints");
1419
1420 uint64_t UIntVal;
1421 bool isExact = false;
1422 APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
1423 : APFloat::rmNearestTiesToEven;
1424 APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
1425 /*isSigned=*/true, mode,
1426 &isExact);
1427 if (status != APFloat::opOK && status != APFloat::opInexact)
Craig Topper9f008862014-04-15 04:59:12 +00001428 return nullptr;
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001429 return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
1430}
1431
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001432double getValueAsDouble(ConstantFP *Op) {
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001433 Type *Ty = Op->getType();
1434
1435 if (Ty->isFloatTy())
1436 return Op->getValueAPF().convertToFloat();
1437
1438 if (Ty->isDoubleTy())
1439 return Op->getValueAPF().convertToDouble();
1440
1441 bool unused;
1442 APFloat APF = Op->getValueAPF();
1443 APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
1444 return APF.convertToDouble();
1445}
1446
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001447Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID, Type *Ty,
1448 ArrayRef<Constant *> Operands,
1449 const TargetLibraryInfo *TLI) {
Jay Foadf4b14a22011-07-19 13:32:40 +00001450 if (Operands.size() == 1) {
Sanjoy Das87b9e1b2016-04-08 18:21:11 +00001451 if (isa<UndefValue>(Operands[0])) {
1452 // cosine(arg) is between -1 and 1. cosine(invalid arg) is NaN
1453 if (IntrinsicID == Intrinsic::cos)
1454 return Constant::getNullValue(Ty);
1455 }
David Majnemer90a97042016-07-13 04:22:12 +00001456 if (auto *Op = dyn_cast<ConstantFP>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001457 if (IntrinsicID == Intrinsic::convert_to_fp16) {
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001458 APFloat Val(Op->getValueAPF());
1459
1460 bool lost = false;
1461 Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
1462
Benjamin Kramer061d1472014-03-05 19:41:48 +00001463 return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001464 }
1465
Owen Andersond4ebfd82013-02-06 22:43:31 +00001466 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001467 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001468
Karthik Bhatb67688a2014-03-07 04:36:21 +00001469 if (IntrinsicID == Intrinsic::round) {
1470 APFloat V = Op->getValueAPF();
1471 V.roundToIntegral(APFloat::rmNearestTiesToAway);
1472 return ConstantFP::get(Ty->getContext(), V);
1473 }
1474
Karthik Bhatd818e382015-07-21 08:52:23 +00001475 if (IntrinsicID == Intrinsic::floor) {
1476 APFloat V = Op->getValueAPF();
1477 V.roundToIntegral(APFloat::rmTowardNegative);
1478 return ConstantFP::get(Ty->getContext(), V);
1479 }
1480
1481 if (IntrinsicID == Intrinsic::ceil) {
1482 APFloat V = Op->getValueAPF();
1483 V.roundToIntegral(APFloat::rmTowardPositive);
1484 return ConstantFP::get(Ty->getContext(), V);
1485 }
1486
1487 if (IntrinsicID == Intrinsic::trunc) {
1488 APFloat V = Op->getValueAPF();
1489 V.roundToIntegral(APFloat::rmTowardZero);
1490 return ConstantFP::get(Ty->getContext(), V);
1491 }
1492
1493 if (IntrinsicID == Intrinsic::rint) {
1494 APFloat V = Op->getValueAPF();
1495 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1496 return ConstantFP::get(Ty->getContext(), V);
1497 }
1498
1499 if (IntrinsicID == Intrinsic::nearbyint) {
1500 APFloat V = Op->getValueAPF();
1501 V.roundToIntegral(APFloat::rmNearestTiesToEven);
1502 return ConstantFP::get(Ty->getContext(), V);
1503 }
1504
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001505 /// We only fold functions with finite arguments. Folding NaN and inf is
1506 /// likely to be aborted with an exception anyway, and some host libms
1507 /// have known errors raising exceptions.
1508 if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
Craig Topper9f008862014-04-15 04:59:12 +00001509 return nullptr;
Jakob Stoklund Olesen10835732010-09-27 21:29:20 +00001510
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001511 /// Currently APFloat versions of these functions do not exist, so we use
1512 /// the host native double versions. Float versions are not called
1513 /// directly but for all these it is true (float)(f((double)arg)) ==
1514 /// f(arg). Long double not supported yet.
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001515 double V = getValueAsDouble(Op);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001516
Benjamin Kramer061d1472014-03-05 19:41:48 +00001517 switch (IntrinsicID) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001518 default: break;
1519 case Intrinsic::fabs:
1520 return ConstantFoldFP(fabs, V, Ty);
1521 case Intrinsic::log2:
Vince Harrond5281122015-05-07 00:05:26 +00001522 return ConstantFoldFP(Log2, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001523 case Intrinsic::log:
1524 return ConstantFoldFP(log, V, Ty);
1525 case Intrinsic::log10:
1526 return ConstantFoldFP(log10, V, Ty);
1527 case Intrinsic::exp:
1528 return ConstantFoldFP(exp, V, Ty);
1529 case Intrinsic::exp2:
1530 return ConstantFoldFP(exp2, V, Ty);
Karthik Bhatd2bc0d82015-07-08 03:55:47 +00001531 case Intrinsic::sin:
1532 return ConstantFoldFP(sin, V, Ty);
1533 case Intrinsic::cos:
1534 return ConstantFoldFP(cos, V, Ty);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001535 }
1536
Benjamin Kramer061d1472014-03-05 19:41:48 +00001537 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001538 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001539
Daniel Dunbarca414c72009-07-26 08:34:35 +00001540 switch (Name[0]) {
Chris Lattner785f9982007-08-08 06:55:43 +00001541 case 'a':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001542 if ((Name == "acos" && TLI->has(LibFunc::acos)) ||
1543 (Name == "acosf" && TLI->has(LibFunc::acosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001544 return ConstantFoldFP(acos, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001545 else if ((Name == "asin" && TLI->has(LibFunc::asin)) ||
1546 (Name == "asinf" && TLI->has(LibFunc::asinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001547 return ConstantFoldFP(asin, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001548 else if ((Name == "atan" && TLI->has(LibFunc::atan)) ||
1549 (Name == "atanf" && TLI->has(LibFunc::atanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001550 return ConstantFoldFP(atan, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001551 break;
1552 case 'c':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001553 if ((Name == "ceil" && TLI->has(LibFunc::ceil)) ||
1554 (Name == "ceilf" && TLI->has(LibFunc::ceilf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001555 return ConstantFoldFP(ceil, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001556 else if ((Name == "cos" && TLI->has(LibFunc::cos)) ||
1557 (Name == "cosf" && TLI->has(LibFunc::cosf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001558 return ConstantFoldFP(cos, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001559 else if ((Name == "cosh" && TLI->has(LibFunc::cosh)) ||
1560 (Name == "coshf" && TLI->has(LibFunc::coshf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001561 return ConstantFoldFP(cosh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001562 break;
1563 case 'e':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001564 if ((Name == "exp" && TLI->has(LibFunc::exp)) ||
1565 (Name == "expf" && TLI->has(LibFunc::expf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001566 return ConstantFoldFP(exp, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001567 if ((Name == "exp2" && TLI->has(LibFunc::exp2)) ||
1568 (Name == "exp2f" && TLI->has(LibFunc::exp2f)))
Chris Lattner713d5232011-05-22 22:22:35 +00001569 // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
1570 // C99 library.
1571 return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001572 break;
1573 case 'f':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001574 if ((Name == "fabs" && TLI->has(LibFunc::fabs)) ||
1575 (Name == "fabsf" && TLI->has(LibFunc::fabsf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001576 return ConstantFoldFP(fabs, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001577 else if ((Name == "floor" && TLI->has(LibFunc::floor)) ||
1578 (Name == "floorf" && TLI->has(LibFunc::floorf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001579 return ConstantFoldFP(floor, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001580 break;
1581 case 'l':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001582 if ((Name == "log" && V > 0 && TLI->has(LibFunc::log)) ||
1583 (Name == "logf" && V > 0 && TLI->has(LibFunc::logf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001584 return ConstantFoldFP(log, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001585 else if ((Name == "log10" && V > 0 && TLI->has(LibFunc::log10)) ||
1586 (Name == "log10f" && V > 0 && TLI->has(LibFunc::log10f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001587 return ConstantFoldFP(log10, V, Ty);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001588 else if (IntrinsicID == Intrinsic::sqrt &&
Owen Andersond4ebfd82013-02-06 22:43:31 +00001589 (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
Chris Lattner785f9982007-08-08 06:55:43 +00001590 if (V >= -0.0)
Chris Lattner46b5c642009-11-06 04:27:31 +00001591 return ConstantFoldFP(sqrt, V, Ty);
Sanjay Patel7b2cd9a2014-10-01 20:36:33 +00001592 else {
1593 // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
1594 // all guarantee or favor returning NaN - the square root of a
1595 // negative number is not defined for the LLVM sqrt intrinsic.
1596 // This is because the intrinsic should only be emitted in place of
1597 // libm's sqrt function when using "no-nans-fp-math".
1598 return UndefValue::get(Ty);
1599 }
Chris Lattner785f9982007-08-08 06:55:43 +00001600 }
1601 break;
1602 case 's':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001603 if ((Name == "sin" && TLI->has(LibFunc::sin)) ||
1604 (Name == "sinf" && TLI->has(LibFunc::sinf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001605 return ConstantFoldFP(sin, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001606 else if ((Name == "sinh" && TLI->has(LibFunc::sinh)) ||
1607 (Name == "sinhf" && TLI->has(LibFunc::sinhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001608 return ConstantFoldFP(sinh, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001609 else if ((Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt)) ||
1610 (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001611 return ConstantFoldFP(sqrt, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001612 break;
1613 case 't':
Erik Schnetter5e93e282015-08-27 19:56:57 +00001614 if ((Name == "tan" && TLI->has(LibFunc::tan)) ||
1615 (Name == "tanf" && TLI->has(LibFunc::tanf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001616 return ConstantFoldFP(tan, V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001617 else if ((Name == "tanh" && TLI->has(LibFunc::tanh)) ||
1618 (Name == "tanhf" && TLI->has(LibFunc::tanhf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001619 return ConstantFoldFP(tanh, V, Ty);
Chris Lattner785f9982007-08-08 06:55:43 +00001620 break;
1621 default:
1622 break;
John Criswell970af112005-10-27 16:00:10 +00001623 }
Craig Topper9f008862014-04-15 04:59:12 +00001624 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001625 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001626
David Majnemer90a97042016-07-13 04:22:12 +00001627 if (auto *Op = dyn_cast<ConstantInt>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001628 switch (IntrinsicID) {
Chandler Carruth352d9b12011-01-10 09:02:58 +00001629 case Intrinsic::bswap:
Benjamin Kramer061d1472014-03-05 19:41:48 +00001630 return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001631 case Intrinsic::ctpop:
Owen Andersonedb4a702009-07-24 23:12:02 +00001632 return ConstantInt::get(Ty, Op->getValue().countPopulation());
Matt Arsenault155dda92016-03-21 15:00:35 +00001633 case Intrinsic::bitreverse:
1634 return ConstantInt::get(Ty->getContext(), Op->getValue().reverseBits());
Chandler Carruth352d9b12011-01-10 09:02:58 +00001635 case Intrinsic::convert_from_fp16: {
Tim Northover29178a32013-01-22 09:46:31 +00001636 APFloat Val(APFloat::IEEEhalf, Op->getValue());
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001637
1638 bool lost = false;
Andrea Di Biagio29059992015-05-14 18:01:48 +00001639 APFloat::opStatus status = Val.convert(
1640 Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001641
1642 // Conversion is always precise.
Jeffrey Yasskin9b43f332010-12-23 00:58:24 +00001643 (void)status;
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001644 assert(status == APFloat::opOK && !lost &&
1645 "Precision lost during fp16 constfolding");
1646
Benjamin Kramer061d1472014-03-05 19:41:48 +00001647 return ConstantFP::get(Ty->getContext(), Val);
Anton Korobeynikov065232f2010-03-19 00:36:35 +00001648 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001649 default:
Craig Topper9f008862014-04-15 04:59:12 +00001650 return nullptr;
Chandler Carruth352d9b12011-01-10 09:02:58 +00001651 }
John Criswell970af112005-10-27 16:00:10 +00001652 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001653
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001654 // Support ConstantVector in case we have an Undef in the top.
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001655 if (isa<ConstantVector>(Operands[0]) ||
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001656 isa<ConstantDataVector>(Operands[0])) {
David Majnemer90a97042016-07-13 04:22:12 +00001657 auto *Op = cast<Constant>(Operands[0]);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001658 switch (IntrinsicID) {
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001659 default: break;
1660 case Intrinsic::x86_sse_cvtss2si:
1661 case Intrinsic::x86_sse_cvtss2si64:
1662 case Intrinsic::x86_sse2_cvtsd2si:
1663 case Intrinsic::x86_sse2_cvtsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001664 if (ConstantFP *FPOp =
1665 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
1666 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
1667 /*roundTowardZero=*/false, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001668 case Intrinsic::x86_sse_cvttss2si:
1669 case Intrinsic::x86_sse_cvttss2si64:
1670 case Intrinsic::x86_sse2_cvttsd2si:
1671 case Intrinsic::x86_sse2_cvttsd2si64:
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001672 if (ConstantFP *FPOp =
1673 dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001674 return ConstantFoldConvertToInt(FPOp->getValueAPF(),
Chris Lattner61a1d6c2012-01-26 21:37:55 +00001675 /*roundTowardZero=*/true, Ty);
Chandler Carruthb1e7f552011-01-11 01:07:24 +00001676 }
1677 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001678
Dan Gohmancf39be32010-02-17 00:54:58 +00001679 if (isa<UndefValue>(Operands[0])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001680 if (IntrinsicID == Intrinsic::bswap)
Dan Gohmancf39be32010-02-17 00:54:58 +00001681 return Operands[0];
Craig Topper9f008862014-04-15 04:59:12 +00001682 return nullptr;
Dan Gohmancf39be32010-02-17 00:54:58 +00001683 }
1684
Craig Topper9f008862014-04-15 04:59:12 +00001685 return nullptr;
Chris Lattner9ca7c092009-10-05 05:00:35 +00001686 }
Chandler Carruth352d9b12011-01-10 09:02:58 +00001687
Jay Foadf4b14a22011-07-19 13:32:40 +00001688 if (Operands.size() == 2) {
David Majnemer90a97042016-07-13 04:22:12 +00001689 if (auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
Owen Andersond4ebfd82013-02-06 22:43:31 +00001690 if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
Craig Topper9f008862014-04-15 04:59:12 +00001691 return nullptr;
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001692 double Op1V = getValueAsDouble(Op1);
Owen Andersond4ebfd82013-02-06 22:43:31 +00001693
David Majnemer90a97042016-07-13 04:22:12 +00001694 if (auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
Chris Lattner351534f2009-10-05 05:06:24 +00001695 if (Op2->getType() != Op1->getType())
Craig Topper9f008862014-04-15 04:59:12 +00001696 return nullptr;
Chad Rosier576c0f82011-12-01 23:16:03 +00001697
Matt Arsenaultf8ecf9b2014-03-05 00:01:58 +00001698 double Op2V = getValueAsDouble(Op2);
Benjamin Kramer061d1472014-03-05 19:41:48 +00001699 if (IntrinsicID == Intrinsic::pow) {
Chad Rosier0155a632011-12-03 00:00:03 +00001700 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
1701 }
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001702 if (IntrinsicID == Intrinsic::copysign) {
1703 APFloat V1 = Op1->getValueAPF();
Benjamin Kramer8f59adb2016-02-13 16:54:14 +00001704 const APFloat &V2 = Op2->getValueAPF();
Karthik Bhatdaa8cd12014-03-06 05:32:52 +00001705 V1.copySign(V2);
1706 return ConstantFP::get(Ty->getContext(), V1);
1707 }
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001708
1709 if (IntrinsicID == Intrinsic::minnum) {
1710 const APFloat &C1 = Op1->getValueAPF();
1711 const APFloat &C2 = Op2->getValueAPF();
1712 return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
1713 }
1714
1715 if (IntrinsicID == Intrinsic::maxnum) {
1716 const APFloat &C1 = Op1->getValueAPF();
1717 const APFloat &C2 = Op2->getValueAPF();
1718 return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
1719 }
1720
Chad Rosier0155a632011-12-03 00:00:03 +00001721 if (!TLI)
Craig Topper9f008862014-04-15 04:59:12 +00001722 return nullptr;
Erik Schnetter5e93e282015-08-27 19:56:57 +00001723 if ((Name == "pow" && TLI->has(LibFunc::pow)) ||
1724 (Name == "powf" && TLI->has(LibFunc::powf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001725 return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001726 if ((Name == "fmod" && TLI->has(LibFunc::fmod)) ||
1727 (Name == "fmodf" && TLI->has(LibFunc::fmodf)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001728 return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
Erik Schnetter5e93e282015-08-27 19:56:57 +00001729 if ((Name == "atan2" && TLI->has(LibFunc::atan2)) ||
1730 (Name == "atan2f" && TLI->has(LibFunc::atan2f)))
Chris Lattner46b5c642009-11-06 04:27:31 +00001731 return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
David Majnemer90a97042016-07-13 04:22:12 +00001732 } else if (auto *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001733 if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
1734 return ConstantFP::get(Ty->getContext(),
Owen Andersond4ebfd82013-02-06 22:43:31 +00001735 APFloat((float)std::pow((float)Op1V,
1736 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001737 if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
1738 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001739 APFloat((float)std::pow((float)Op1V,
Chris Lattner3b187622008-04-20 00:41:09 +00001740 (int)Op2C->getZExtValue())));
Benjamin Kramer061d1472014-03-05 19:41:48 +00001741 if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
1742 return ConstantFP::get(Ty->getContext(),
Chris Lattner46b5c642009-11-06 04:27:31 +00001743 APFloat((double)std::pow((double)Op1V,
1744 (int)Op2C->getZExtValue())));
John Criswell970af112005-10-27 16:00:10 +00001745 }
Craig Topper9f008862014-04-15 04:59:12 +00001746 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001747 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001748
David Majnemer90a97042016-07-13 04:22:12 +00001749 if (auto *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
1750 if (auto *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001751 switch (IntrinsicID) {
Chris Lattner59d93982009-10-05 05:26:04 +00001752 default: break;
Chris Lattner698661c2010-10-14 00:05:07 +00001753 case Intrinsic::sadd_with_overflow:
1754 case Intrinsic::uadd_with_overflow:
1755 case Intrinsic::ssub_with_overflow:
1756 case Intrinsic::usub_with_overflow:
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001757 case Intrinsic::smul_with_overflow:
1758 case Intrinsic::umul_with_overflow: {
Chris Lattner698661c2010-10-14 00:05:07 +00001759 APInt Res;
1760 bool Overflow;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001761 switch (IntrinsicID) {
Craig Toppera2886c22012-02-07 05:05:23 +00001762 default: llvm_unreachable("Invalid case");
Chris Lattner698661c2010-10-14 00:05:07 +00001763 case Intrinsic::sadd_with_overflow:
1764 Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
1765 break;
1766 case Intrinsic::uadd_with_overflow:
1767 Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
1768 break;
1769 case Intrinsic::ssub_with_overflow:
1770 Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
1771 break;
1772 case Intrinsic::usub_with_overflow:
1773 Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
1774 break;
1775 case Intrinsic::smul_with_overflow:
1776 Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
1777 break;
Frits van Bommel0bb2ad22011-03-27 14:26:13 +00001778 case Intrinsic::umul_with_overflow:
1779 Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
1780 break;
Chris Lattner698661c2010-10-14 00:05:07 +00001781 }
Chris Lattner59d93982009-10-05 05:26:04 +00001782 Constant *Ops[] = {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001783 ConstantInt::get(Ty->getContext(), Res),
1784 ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
Chris Lattner59d93982009-10-05 05:26:04 +00001785 };
Benjamin Kramer061d1472014-03-05 19:41:48 +00001786 return ConstantStruct::get(cast<StructType>(Ty), Ops);
Chris Lattner59d93982009-10-05 05:26:04 +00001787 }
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001788 case Intrinsic::cttz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001789 if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
1790 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001791 return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
1792 case Intrinsic::ctlz:
Benjamin Kramer435eba02013-01-24 16:28:28 +00001793 if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
1794 return UndefValue::get(Ty);
Chandler Carruth58a71ed2011-12-12 04:26:04 +00001795 return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
Chris Lattner59d93982009-10-05 05:26:04 +00001796 }
1797 }
NAKAMURA Takumidce89992012-11-05 00:11:11 +00001798
Craig Topper9f008862014-04-15 04:59:12 +00001799 return nullptr;
Chris Lattner59d93982009-10-05 05:26:04 +00001800 }
Craig Topper9f008862014-04-15 04:59:12 +00001801 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001802 }
Matt Arsenault83778582014-03-05 00:02:00 +00001803
1804 if (Operands.size() != 3)
Craig Topper9f008862014-04-15 04:59:12 +00001805 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001806
David Majnemer90a97042016-07-13 04:22:12 +00001807 if (const auto *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
1808 if (const auto *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
1809 if (const auto *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001810 switch (IntrinsicID) {
Matt Arsenault83778582014-03-05 00:02:00 +00001811 default: break;
1812 case Intrinsic::fma:
1813 case Intrinsic::fmuladd: {
1814 APFloat V = Op1->getValueAPF();
1815 APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
1816 Op3->getValueAPF(),
1817 APFloat::rmNearestTiesToEven);
1818 if (s != APFloat::opInvalidOp)
1819 return ConstantFP::get(Ty->getContext(), V);
1820
Craig Topper9f008862014-04-15 04:59:12 +00001821 return nullptr;
Matt Arsenault83778582014-03-05 00:02:00 +00001822 }
1823 }
1824 }
1825 }
1826 }
1827
Craig Topper9f008862014-04-15 04:59:12 +00001828 return nullptr;
John Criswell970af112005-10-27 16:00:10 +00001829}
Benjamin Kramer061d1472014-03-05 19:41:48 +00001830
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001831Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
1832 VectorType *VTy, ArrayRef<Constant *> Operands,
1833 const TargetLibraryInfo *TLI) {
Benjamin Kramer061d1472014-03-05 19:41:48 +00001834 SmallVector<Constant *, 4> Result(VTy->getNumElements());
1835 SmallVector<Constant *, 4> Lane(Operands.size());
1836 Type *Ty = VTy->getElementType();
1837
1838 for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
1839 // Gather a column of constants.
1840 for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
1841 Constant *Agg = Operands[J]->getAggregateElement(I);
1842 if (!Agg)
1843 return nullptr;
1844
1845 Lane[J] = Agg;
1846 }
1847
1848 // Use the regular scalar folding to simplify this column.
1849 Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
1850 if (!Folded)
1851 return nullptr;
1852 Result[I] = Folded;
1853 }
1854
1855 return ConstantVector::get(Result);
1856}
1857
Eugene Zelenko35623fb2016-03-28 17:40:08 +00001858} // end anonymous namespace
1859
Benjamin Kramer061d1472014-03-05 19:41:48 +00001860Constant *
1861llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
1862 const TargetLibraryInfo *TLI) {
1863 if (!F->hasName())
Craig Topper9f008862014-04-15 04:59:12 +00001864 return nullptr;
Benjamin Kramer061d1472014-03-05 19:41:48 +00001865 StringRef Name = F->getName();
1866
1867 Type *Ty = F->getReturnType();
1868
David Majnemer90a97042016-07-13 04:22:12 +00001869 if (auto *VTy = dyn_cast<VectorType>(Ty))
Benjamin Kramer061d1472014-03-05 19:41:48 +00001870 return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
1871
1872 return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
1873}