blob: 25f4c768fcda1229c5fd65790559ecfd379e72ef [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Meador Ingee3f2b262012-11-30 04:05:06 +000015#include "llvm/ADT/Statistic.h"
David Majnemer15032582015-05-22 03:56:46 +000016#include "llvm/Analysis/InstructionSimplify.h"
Artur Pilipenko31bcca42016-02-24 12:49:04 +000017#include "llvm/Analysis/Loads.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000018#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000019#include "llvm/IR/CallSite.h"
Hal Finkel04a15612014-10-04 21:27:06 +000020#include "llvm/IR/Dominators.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000021#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000022#include "llvm/IR/Statepoint.h"
Eric Christophera7fb58f2010-03-06 10:50:38 +000023#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000024#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000025#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000026using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000027using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000028
Chandler Carruth964daaa2014-04-22 02:55:47 +000029#define DEBUG_TYPE "instcombine"
30
Meador Ingee3f2b262012-11-30 04:05:06 +000031STATISTIC(NumSimplified, "Number of library calls simplified");
32
Sanjay Patelcd4377c2016-01-20 22:24:38 +000033/// Return the specified type promoted as it would be to pass though a va_arg
34/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000035static Type *getPromotedType(Type *Ty) {
36 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000037 if (ITy->getBitWidth() < 32)
38 return Type::getInt32Ty(Ty->getContext());
39 }
40 return Ty;
41}
42
Sanjay Patelcd4377c2016-01-20 22:24:38 +000043/// Given an aggregate type which ultimately holds a single scalar element,
44/// like {{{type}}} or [1 x type], return type.
Dan Gohmand0080c42012-09-13 18:19:06 +000045static Type *reduceToSingleValueType(Type *T) {
46 while (!T->isSingleValueType()) {
47 if (StructType *STy = dyn_cast<StructType>(T)) {
48 if (STy->getNumElements() == 1)
49 T = STy->getElementType(0);
50 else
51 break;
52 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
53 if (ATy->getNumElements() == 1)
54 T = ATy->getElementType();
55 else
56 break;
57 } else
58 break;
59 }
60
61 return T;
62}
Chris Lattner7a9e47a2010-01-05 07:32:13 +000063
Sanjay Patel368ac5d2016-02-21 17:29:33 +000064/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000065/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000066static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
67 SmallVector<Constant *, 32> BoolVec;
68 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
69 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
70 Constant *Elt = V->getElementAsConstant(I);
71 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
72 "Unexpected constant data vector element type");
73 bool Sign = V->getElementType()->isIntegerTy()
74 ? cast<ConstantInt>(Elt)->isNegative()
75 : cast<ConstantFP>(Elt)->isNegative();
76 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
77 }
78 return ConstantVector::get(BoolVec);
79}
80
Pete Cooper67cf9a72015-11-19 05:56:52 +000081Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +000082 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, AC, DT);
83 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, AC, DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +000084 unsigned MinAlign = std::min(DstAlign, SrcAlign);
85 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +000086
Pete Cooper67cf9a72015-11-19 05:56:52 +000087 if (CopyAlign < MinAlign) {
88 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +000089 return MI;
90 }
Jim Grosbach7815f562012-02-03 00:07:04 +000091
Chris Lattner7a9e47a2010-01-05 07:32:13 +000092 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
93 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +000094 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +000095 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +000096
Chris Lattner7a9e47a2010-01-05 07:32:13 +000097 // Source and destination pointer types are always "i8*" for intrinsic. See
98 // if the size is something we can handle with a single primitive load/store.
99 // A single load+store correctly handles overlapping memory in the memmove
100 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000101 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000102 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000103
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000104 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000105 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000106
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000107 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000108 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000109 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000110 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000111 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000112
Chris Lattner229907c2011-07-18 04:54:35 +0000113 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000114 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
115 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000116
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000117 // Memcpy forces the use of i8* for the source and destination. That means
118 // that if you're using memcpy to move one double around, you'll get a cast
119 // from double* to i8*. We'd much rather use a double load+store rather than
120 // an i64 load+store, here because this improves the odds that the source or
121 // dest address will be promotable. See if we can find a better type than the
122 // integer datatype.
Gabor Greif589a0b92010-06-24 12:58:35 +0000123 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Craig Topperf40110f2014-04-25 05:29:35 +0000124 MDNode *CopyMD = nullptr;
Gabor Greif589a0b92010-06-24 12:58:35 +0000125 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000126 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000127 ->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000128 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000129 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
130 // down through these levels if so.
Dan Gohmand0080c42012-09-13 18:19:06 +0000131 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach7815f562012-02-03 00:07:04 +0000132
Mon P Wangc576ee92010-04-04 03:10:48 +0000133 if (SrcETy->isSingleValueType()) {
134 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
135 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohman3f553c22012-09-13 21:51:01 +0000136
137 // If the memcpy has metadata describing the members, see if we can
138 // get the TBAA tag describing our copy.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000139 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000140 if (M->getNumOperands() == 3 && M->getOperand(0) &&
141 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
142 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000143 M->getOperand(1) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000144 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
145 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
146 Size &&
147 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
Dan Gohman3f553c22012-09-13 21:51:01 +0000148 CopyMD = cast<MDNode>(M->getOperand(2));
149 }
Mon P Wangc576ee92010-04-04 03:10:48 +0000150 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000151 }
152 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000153
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000154 // If the memcpy/memmove provides better alignment info than we can
155 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000156 SrcAlign = std::max(SrcAlign, CopyAlign);
157 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000158
Gabor Greif5f3e6562010-06-25 07:57:14 +0000159 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
160 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000161 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
162 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000163 if (CopyMD)
164 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Eli Friedman49346012011-05-18 19:57:14 +0000165 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
166 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000167 if (CopyMD)
168 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000169
170 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000171 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000172 return MI;
173}
174
175Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000176 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, AC, DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000177 if (MI->getAlignment() < Alignment) {
178 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
179 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000180 return MI;
181 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000182
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000183 // Extract the length and alignment and fill if they are constant.
184 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
185 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000186 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000187 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000188 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000189 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000190 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000191
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000192 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
193 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000194 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000195
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000196 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000197 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
198 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
199 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000200
201 // Alignment 0 is identity for alignment 1 for memset, but not store.
202 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000203
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000204 // Extract the fill value and store.
205 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000206 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
207 MI->isVolatile());
208 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000209
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000210 // Set the size of the copy to 0, it will be deleted on the next iteration.
211 MI->setLength(Constant::getNullValue(LenC->getType()));
212 return MI;
213 }
214
Simon Pilgrim18617d12015-08-05 08:18:00 +0000215 return nullptr;
216}
217
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000218static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000219 InstCombiner::BuilderTy &Builder) {
220 bool LogicalShift = false;
221 bool ShiftLeft = false;
222
223 switch (II.getIntrinsicID()) {
224 default:
225 return nullptr;
226 case Intrinsic::x86_sse2_psra_d:
227 case Intrinsic::x86_sse2_psra_w:
228 case Intrinsic::x86_sse2_psrai_d:
229 case Intrinsic::x86_sse2_psrai_w:
230 case Intrinsic::x86_avx2_psra_d:
231 case Intrinsic::x86_avx2_psra_w:
232 case Intrinsic::x86_avx2_psrai_d:
233 case Intrinsic::x86_avx2_psrai_w:
234 LogicalShift = false; ShiftLeft = false;
235 break;
236 case Intrinsic::x86_sse2_psrl_d:
237 case Intrinsic::x86_sse2_psrl_q:
238 case Intrinsic::x86_sse2_psrl_w:
239 case Intrinsic::x86_sse2_psrli_d:
240 case Intrinsic::x86_sse2_psrli_q:
241 case Intrinsic::x86_sse2_psrli_w:
242 case Intrinsic::x86_avx2_psrl_d:
243 case Intrinsic::x86_avx2_psrl_q:
244 case Intrinsic::x86_avx2_psrl_w:
245 case Intrinsic::x86_avx2_psrli_d:
246 case Intrinsic::x86_avx2_psrli_q:
247 case Intrinsic::x86_avx2_psrli_w:
248 LogicalShift = true; ShiftLeft = false;
249 break;
250 case Intrinsic::x86_sse2_psll_d:
251 case Intrinsic::x86_sse2_psll_q:
252 case Intrinsic::x86_sse2_psll_w:
253 case Intrinsic::x86_sse2_pslli_d:
254 case Intrinsic::x86_sse2_pslli_q:
255 case Intrinsic::x86_sse2_pslli_w:
256 case Intrinsic::x86_avx2_psll_d:
257 case Intrinsic::x86_avx2_psll_q:
258 case Intrinsic::x86_avx2_psll_w:
259 case Intrinsic::x86_avx2_pslli_d:
260 case Intrinsic::x86_avx2_pslli_q:
261 case Intrinsic::x86_avx2_pslli_w:
262 LogicalShift = true; ShiftLeft = true;
263 break;
264 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000265 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
266
Simon Pilgrim3815c162015-08-07 18:22:50 +0000267 // Simplify if count is constant.
268 auto Arg1 = II.getArgOperand(1);
269 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
270 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
271 auto CInt = dyn_cast<ConstantInt>(Arg1);
272 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000273 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000274
275 APInt Count(64, 0);
276 if (CDV) {
277 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
278 // operand to compute the shift amount.
279 auto VT = cast<VectorType>(CDV->getType());
280 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
281 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
282 unsigned NumSubElts = 64 / BitWidth;
283
284 // Concatenate the sub-elements to create the 64-bit value.
285 for (unsigned i = 0; i != NumSubElts; ++i) {
286 unsigned SubEltIdx = (NumSubElts - 1) - i;
287 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
288 Count = Count.shl(BitWidth);
289 Count |= SubElt->getValue().zextOrTrunc(64);
290 }
291 }
292 else if (CInt)
293 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000294
295 auto Vec = II.getArgOperand(0);
296 auto VT = cast<VectorType>(Vec->getType());
297 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000298 unsigned VWidth = VT->getNumElements();
299 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
300
301 // If shift-by-zero then just return the original value.
302 if (Count == 0)
303 return Vec;
304
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000305 // Handle cases when Shift >= BitWidth.
306 if (Count.uge(BitWidth)) {
307 // If LogicalShift - just return zero.
308 if (LogicalShift)
309 return ConstantAggregateZero::get(VT);
310
311 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
312 Count = APInt(64, BitWidth - 1);
313 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000314
Simon Pilgrim18617d12015-08-05 08:18:00 +0000315 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000316 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
317 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000318
319 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000320 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000321
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000322 if (LogicalShift)
323 return Builder.CreateLShr(Vec, ShiftVec);
324
325 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000326}
327
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000328static Value *simplifyX86extend(const IntrinsicInst &II,
Simon Pilgrim18617d12015-08-05 08:18:00 +0000329 InstCombiner::BuilderTy &Builder,
330 bool SignExtend) {
Simon Pilgrim15c0a592015-07-27 18:52:15 +0000331 VectorType *SrcTy = cast<VectorType>(II.getArgOperand(0)->getType());
332 VectorType *DstTy = cast<VectorType>(II.getType());
333 unsigned NumDstElts = DstTy->getNumElements();
334
335 // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
336 SmallVector<int, 8> ShuffleMask;
Simon Pilgrim074c0d92015-07-27 19:07:15 +0000337 for (int i = 0; i != (int)NumDstElts; ++i)
Simon Pilgrim15c0a592015-07-27 18:52:15 +0000338 ShuffleMask.push_back(i);
339
340 Value *SV = Builder.CreateShuffleVector(II.getArgOperand(0),
341 UndefValue::get(SrcTy), ShuffleMask);
342 return SignExtend ? Builder.CreateSExt(SV, DstTy)
343 : Builder.CreateZExt(SV, DstTy);
344}
345
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000346static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000347 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000348 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
349 if (!CInt)
350 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000351
Sanjay Patel03c03f52016-01-28 00:03:16 +0000352 VectorType *VecTy = cast<VectorType>(II.getType());
353 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000354
Sanjay Patel03c03f52016-01-28 00:03:16 +0000355 // The immediate permute control byte looks like this:
356 // [3:0] - zero mask for each 32-bit lane
357 // [5:4] - select one 32-bit destination lane
358 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000359
Sanjay Patel03c03f52016-01-28 00:03:16 +0000360 uint8_t Imm = CInt->getZExtValue();
361 uint8_t ZMask = Imm & 0xf;
362 uint8_t DestLane = (Imm >> 4) & 0x3;
363 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000364
Sanjay Patel03c03f52016-01-28 00:03:16 +0000365 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000366
Sanjay Patel03c03f52016-01-28 00:03:16 +0000367 // If all zero mask bits are set, this was just a weird way to
368 // generate a zero vector.
369 if (ZMask == 0xf)
370 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000371
Sanjay Patel03c03f52016-01-28 00:03:16 +0000372 // Initialize by passing all of the first source bits through.
373 int ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000374
Sanjay Patel03c03f52016-01-28 00:03:16 +0000375 // We may replace the second operand with the zero vector.
376 Value *V1 = II.getArgOperand(1);
377
378 if (ZMask) {
379 // If the zero mask is being used with a single input or the zero mask
380 // overrides the destination lane, this is a shuffle with the zero vector.
381 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
382 (ZMask & (1 << DestLane))) {
383 V1 = ZeroVector;
384 // We may still move 32-bits of the first source vector from one lane
385 // to another.
386 ShuffleMask[DestLane] = SourceLane;
387 // The zero mask may override the previous insert operation.
388 for (unsigned i = 0; i < 4; ++i)
389 if ((ZMask >> i) & 0x1)
390 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000391 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000392 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
393 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000394 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000395 } else {
396 // Replace the selected destination lane with the selected source lane.
397 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000398 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000399
400 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000401}
402
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000403/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
404/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000405static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000406 ConstantInt *CILength, ConstantInt *CIIndex,
407 InstCombiner::BuilderTy &Builder) {
408 auto LowConstantHighUndef = [&](uint64_t Val) {
409 Type *IntTy64 = Type::getInt64Ty(II.getContext());
410 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
411 UndefValue::get(IntTy64)};
412 return ConstantVector::get(Args);
413 };
414
415 // See if we're dealing with constant values.
416 Constant *C0 = dyn_cast<Constant>(Op0);
417 ConstantInt *CI0 =
418 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
419 : nullptr;
420
421 // Attempt to constant fold.
422 if (CILength && CIIndex) {
423 // From AMD documentation: "The bit index and field length are each six
424 // bits in length other bits of the field are ignored."
425 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
426 APInt APLength = CILength->getValue().zextOrTrunc(6);
427
428 unsigned Index = APIndex.getZExtValue();
429
430 // From AMD documentation: "a value of zero in the field length is
431 // defined as length of 64".
432 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
433
434 // From AMD documentation: "If the sum of the bit index + length field
435 // is greater than 64, the results are undefined".
436 unsigned End = Index + Length;
437
438 // Note that both field index and field length are 8-bit quantities.
439 // Since variables 'Index' and 'Length' are unsigned values
440 // obtained from zero-extending field index and field length
441 // respectively, their sum should never wrap around.
442 if (End > 64)
443 return UndefValue::get(II.getType());
444
445 // If we are inserting whole bytes, we can convert this to a shuffle.
446 // Lowering can recognize EXTRQI shuffle masks.
447 if ((Length % 8) == 0 && (Index % 8) == 0) {
448 // Convert bit indices to byte indices.
449 Length /= 8;
450 Index /= 8;
451
452 Type *IntTy8 = Type::getInt8Ty(II.getContext());
453 Type *IntTy32 = Type::getInt32Ty(II.getContext());
454 VectorType *ShufTy = VectorType::get(IntTy8, 16);
455
456 SmallVector<Constant *, 16> ShuffleMask;
457 for (int i = 0; i != (int)Length; ++i)
458 ShuffleMask.push_back(
459 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
460 for (int i = Length; i != 8; ++i)
461 ShuffleMask.push_back(
462 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
463 for (int i = 8; i != 16; ++i)
464 ShuffleMask.push_back(UndefValue::get(IntTy32));
465
466 Value *SV = Builder.CreateShuffleVector(
467 Builder.CreateBitCast(Op0, ShufTy),
468 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
469 return Builder.CreateBitCast(SV, II.getType());
470 }
471
472 // Constant Fold - shift Index'th bit to lowest position and mask off
473 // Length bits.
474 if (CI0) {
475 APInt Elt = CI0->getValue();
476 Elt = Elt.lshr(Index).zextOrTrunc(Length);
477 return LowConstantHighUndef(Elt.getZExtValue());
478 }
479
480 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
481 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
482 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000483 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000484 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
485 return Builder.CreateCall(F, Args);
486 }
487 }
488
489 // Constant Fold - extraction from zero is always {zero, undef}.
490 if (CI0 && CI0->equalsInt(0))
491 return LowConstantHighUndef(0);
492
493 return nullptr;
494}
495
496/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
497/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000498static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000499 APInt APLength, APInt APIndex,
500 InstCombiner::BuilderTy &Builder) {
501
502 // From AMD documentation: "The bit index and field length are each six bits
503 // in length other bits of the field are ignored."
504 APIndex = APIndex.zextOrTrunc(6);
505 APLength = APLength.zextOrTrunc(6);
506
507 // Attempt to constant fold.
508 unsigned Index = APIndex.getZExtValue();
509
510 // From AMD documentation: "a value of zero in the field length is
511 // defined as length of 64".
512 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
513
514 // From AMD documentation: "If the sum of the bit index + length field
515 // is greater than 64, the results are undefined".
516 unsigned End = Index + Length;
517
518 // Note that both field index and field length are 8-bit quantities.
519 // Since variables 'Index' and 'Length' are unsigned values
520 // obtained from zero-extending field index and field length
521 // respectively, their sum should never wrap around.
522 if (End > 64)
523 return UndefValue::get(II.getType());
524
525 // If we are inserting whole bytes, we can convert this to a shuffle.
526 // Lowering can recognize INSERTQI shuffle masks.
527 if ((Length % 8) == 0 && (Index % 8) == 0) {
528 // Convert bit indices to byte indices.
529 Length /= 8;
530 Index /= 8;
531
532 Type *IntTy8 = Type::getInt8Ty(II.getContext());
533 Type *IntTy32 = Type::getInt32Ty(II.getContext());
534 VectorType *ShufTy = VectorType::get(IntTy8, 16);
535
536 SmallVector<Constant *, 16> ShuffleMask;
537 for (int i = 0; i != (int)Index; ++i)
538 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
539 for (int i = 0; i != (int)Length; ++i)
540 ShuffleMask.push_back(
541 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
542 for (int i = Index + Length; i != 8; ++i)
543 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
544 for (int i = 8; i != 16; ++i)
545 ShuffleMask.push_back(UndefValue::get(IntTy32));
546
547 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
548 Builder.CreateBitCast(Op1, ShufTy),
549 ConstantVector::get(ShuffleMask));
550 return Builder.CreateBitCast(SV, II.getType());
551 }
552
553 // See if we're dealing with constant values.
554 Constant *C0 = dyn_cast<Constant>(Op0);
555 Constant *C1 = dyn_cast<Constant>(Op1);
556 ConstantInt *CI00 =
557 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
558 : nullptr;
559 ConstantInt *CI10 =
560 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
561 : nullptr;
562
563 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
564 if (CI00 && CI10) {
565 APInt V00 = CI00->getValue();
566 APInt V10 = CI10->getValue();
567 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
568 V00 = V00 & ~Mask;
569 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
570 APInt Val = V00 | V10;
571 Type *IntTy64 = Type::getInt64Ty(II.getContext());
572 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
573 UndefValue::get(IntTy64)};
574 return ConstantVector::get(Args);
575 }
576
577 // If we were an INSERTQ call, we'll save demanded elements if we convert to
578 // INSERTQI.
579 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
580 Type *IntTy8 = Type::getInt8Ty(II.getContext());
581 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
582 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
583
584 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000585 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000586 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
587 return Builder.CreateCall(F, Args);
588 }
589
590 return nullptr;
591}
592
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000593/// Attempt to convert pshufb* to shufflevector if the mask is constant.
594static Value *simplifyX86pshufb(const IntrinsicInst &II,
595 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000596 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
597 if (!V)
598 return nullptr;
599
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000600 auto *VecTy = cast<VectorType>(II.getType());
601 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
602 unsigned NumElts = VecTy->getNumElements();
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000603 assert((NumElts == 16 || NumElts == 32) &&
604 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000605
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000606 // Construct a shuffle mask from constant integers or UNDEFs.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000607 Constant *Indexes[32] = {NULL};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000608
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000609 // Each byte in the shuffle control mask forms an index to permute the
610 // corresponding byte in the destination operand.
611 for (unsigned I = 0; I < NumElts; ++I) {
612 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000613 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000614 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000615
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000616 if (isa<UndefValue>(COp)) {
617 Indexes[I] = UndefValue::get(MaskEltTy);
618 continue;
619 }
620
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000621 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
622
623 // If the most significant bit (bit[7]) of each byte of the shuffle
624 // control mask is set, then zero is written in the result byte.
625 // The zero vector is in the right-hand side of the resulting
626 // shufflevector.
627
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000628 // The value of each index for the high 128-bit lane is the least
629 // significant 4 bits of the respective shuffle control byte.
630 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
631 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000632 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000633
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000634 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000635 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000636 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000637 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
638}
639
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000640/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
641static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
642 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000643 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
644 if (!V)
645 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000646
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000647 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
648 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
649 assert(NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000650
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000651 // Construct a shuffle mask from constant integers or UNDEFs.
652 Constant *Indexes[8] = {NULL};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000653
654 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000655 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000656 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000657 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000658 return nullptr;
659
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000660 if (isa<UndefValue>(COp)) {
661 Indexes[I] = UndefValue::get(MaskEltTy);
662 continue;
663 }
664
665 APInt Index = cast<ConstantInt>(COp)->getValue();
666 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000667
668 // The PD variants uses bit 1 to select per-lane element index, so
669 // shift down to convert to generic shuffle mask index.
670 if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
671 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000672 Index = Index.lshr(1);
673
674 // The _256 variants are a bit trickier since the mask bits always index
675 // into the corresponding 128 half. In order to convert to a generic
676 // shuffle, we have to make that explicit.
677 if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
678 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) &&
679 ((NumElts / 2) <= I)) {
680 Index += APInt(32, NumElts / 2);
681 }
682
683 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000684 }
685
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000686 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000687 auto V1 = II.getArgOperand(0);
688 auto V2 = UndefValue::get(V1->getType());
689 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
690}
691
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000692/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
693static Value *simplifyX86vpermv(const IntrinsicInst &II,
694 InstCombiner::BuilderTy &Builder) {
695 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
696 if (!V)
697 return nullptr;
698
699 VectorType *VecTy = cast<VectorType>(II.getType());
700 unsigned Size = VecTy->getNumElements();
701 assert(Size == 8 && "Unexpected shuffle mask size");
702
703 // Initialize the resulting shuffle mask to all zeroes.
704 uint32_t Indexes[8] = {0};
705
706 for (unsigned I = 0; I < Size; ++I) {
707 Constant *COp = V->getAggregateElement(I);
708 if (!COp || !isa<ConstantInt>(COp))
709 return nullptr;
710
711 APInt Index = cast<ConstantInt>(COp)->getValue();
712 Index = Index.getLoBits(3);
713 Indexes[I] = (uint32_t)Index.getZExtValue();
714 }
715
716 auto ShuffleMask =
717 ConstantDataVector::get(II.getContext(), makeArrayRef(Indexes, Size));
718 auto V1 = II.getArgOperand(0);
719 auto V2 = UndefValue::get(VecTy);
720 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
721}
722
Sanjay Patelccf5f242015-03-20 21:47:56 +0000723/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
724/// source vectors, unless a zero bit is set. If a zero bit is set,
725/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000726static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000727 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000728 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
729 if (!CInt)
730 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000731
Sanjay Patel03c03f52016-01-28 00:03:16 +0000732 VectorType *VecTy = cast<VectorType>(II.getType());
733 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000734
Sanjay Patel03c03f52016-01-28 00:03:16 +0000735 // The immediate permute control byte looks like this:
736 // [1:0] - select 128 bits from sources for low half of destination
737 // [2] - ignore
738 // [3] - zero low half of destination
739 // [5:4] - select 128 bits from sources for high half of destination
740 // [6] - ignore
741 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000742
Sanjay Patel03c03f52016-01-28 00:03:16 +0000743 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000744
Sanjay Patel03c03f52016-01-28 00:03:16 +0000745 bool LowHalfZero = Imm & 0x08;
746 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000747
Sanjay Patel03c03f52016-01-28 00:03:16 +0000748 // If both zero mask bits are set, this was just a weird way to
749 // generate a zero vector.
750 if (LowHalfZero && HighHalfZero)
751 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000752
Sanjay Patel03c03f52016-01-28 00:03:16 +0000753 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
754 unsigned NumElts = VecTy->getNumElements();
755 unsigned HalfSize = NumElts / 2;
756 SmallVector<int, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000757
Sanjay Patel03c03f52016-01-28 00:03:16 +0000758 // The high bit of the selection field chooses the 1st or 2nd operand.
759 bool LowInputSelect = Imm & 0x02;
760 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000761
Sanjay Patel03c03f52016-01-28 00:03:16 +0000762 // The low bit of the selection field chooses the low or high half
763 // of the selected operand.
764 bool LowHalfSelect = Imm & 0x01;
765 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000766
Sanjay Patel03c03f52016-01-28 00:03:16 +0000767 // Determine which operand(s) are actually in use for this instruction.
768 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
769 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000770
Sanjay Patel03c03f52016-01-28 00:03:16 +0000771 // If needed, replace operands based on zero mask.
772 V0 = LowHalfZero ? ZeroVector : V0;
773 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000774
Sanjay Patel03c03f52016-01-28 00:03:16 +0000775 // Permute low half of result.
776 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
777 for (unsigned i = 0; i < HalfSize; ++i)
778 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000779
Sanjay Patel03c03f52016-01-28 00:03:16 +0000780 // Permute high half of result.
781 StartIndex = HighHalfSelect ? HalfSize : 0;
782 StartIndex += NumElts;
783 for (unsigned i = 0; i < HalfSize; ++i)
784 ShuffleMask[i + HalfSize] = StartIndex + i;
785
786 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +0000787}
788
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000789/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000790static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000791 InstCombiner::BuilderTy &Builder,
792 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000793 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
794 uint64_t Imm = CInt->getZExtValue() & 0x7;
795 VectorType *VecTy = cast<VectorType>(II.getType());
796 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
797
798 switch (Imm) {
799 case 0x0:
800 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
801 break;
802 case 0x1:
803 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
804 break;
805 case 0x2:
806 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
807 break;
808 case 0x3:
809 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
810 break;
811 case 0x4:
812 Pred = ICmpInst::ICMP_EQ; break;
813 case 0x5:
814 Pred = ICmpInst::ICMP_NE; break;
815 case 0x6:
816 return ConstantInt::getSigned(VecTy, 0); // FALSE
817 case 0x7:
818 return ConstantInt::getSigned(VecTy, -1); // TRUE
819 }
820
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000821 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
822 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000823 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
824 }
825 return nullptr;
826}
827
Sanjay Patel0069f562016-01-31 16:35:23 +0000828static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
829 Value *Arg0 = II.getArgOperand(0);
830 Value *Arg1 = II.getArgOperand(1);
831
832 // fmin(x, x) -> x
833 if (Arg0 == Arg1)
834 return Arg0;
835
836 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
837
838 // fmin(x, nan) -> x
839 if (C1 && C1->isNaN())
840 return Arg0;
841
842 // This is the value because if undef were NaN, we would return the other
843 // value and cannot return a NaN unless both operands are.
844 //
845 // fmin(undef, x) -> x
846 if (isa<UndefValue>(Arg0))
847 return Arg1;
848
849 // fmin(x, undef) -> x
850 if (isa<UndefValue>(Arg1))
851 return Arg0;
852
853 Value *X = nullptr;
854 Value *Y = nullptr;
855 if (II.getIntrinsicID() == Intrinsic::minnum) {
856 // fmin(x, fmin(x, y)) -> fmin(x, y)
857 // fmin(y, fmin(x, y)) -> fmin(x, y)
858 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
859 if (Arg0 == X || Arg0 == Y)
860 return Arg1;
861 }
862
863 // fmin(fmin(x, y), x) -> fmin(x, y)
864 // fmin(fmin(x, y), y) -> fmin(x, y)
865 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
866 if (Arg1 == X || Arg1 == Y)
867 return Arg0;
868 }
869
870 // TODO: fmin(nnan x, inf) -> x
871 // TODO: fmin(nnan ninf x, flt_max) -> x
872 if (C1 && C1->isInfinity()) {
873 // fmin(x, -inf) -> -inf
874 if (C1->isNegative())
875 return Arg1;
876 }
877 } else {
878 assert(II.getIntrinsicID() == Intrinsic::maxnum);
879 // fmax(x, fmax(x, y)) -> fmax(x, y)
880 // fmax(y, fmax(x, y)) -> fmax(x, y)
881 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
882 if (Arg0 == X || Arg0 == Y)
883 return Arg1;
884 }
885
886 // fmax(fmax(x, y), x) -> fmax(x, y)
887 // fmax(fmax(x, y), y) -> fmax(x, y)
888 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
889 if (Arg1 == X || Arg1 == Y)
890 return Arg0;
891 }
892
893 // TODO: fmax(nnan x, -inf) -> x
894 // TODO: fmax(nnan ninf x, -flt_max) -> x
895 if (C1 && C1->isInfinity()) {
896 // fmax(x, inf) -> inf
897 if (!C1->isNegative())
898 return Arg1;
899 }
900 }
901 return nullptr;
902}
903
Sanjay Patelb695c552016-02-01 17:00:10 +0000904static Value *simplifyMaskedLoad(const IntrinsicInst &II,
905 InstCombiner::BuilderTy &Builder) {
906 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
907 if (!ConstMask)
908 return nullptr;
909
910 // If the mask is all zeros, the "passthru" argument is the result.
911 if (ConstMask->isNullValue())
912 return II.getArgOperand(3);
913
914 // If the mask is all ones, this is a plain vector load of the 1st argument.
915 if (ConstMask->isAllOnesValue()) {
916 Value *LoadPtr = II.getArgOperand(0);
917 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
918 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
919 }
920
921 return nullptr;
922}
923
Sanjay Patel04f792b2016-02-01 19:39:52 +0000924static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
925 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
926 if (!ConstMask)
927 return nullptr;
928
929 // If the mask is all zeros, this instruction does nothing.
930 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +0000931 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +0000932
933 // If the mask is all ones, this is a plain vector store of the 1st argument.
934 if (ConstMask->isAllOnesValue()) {
935 Value *StorePtr = II.getArgOperand(1);
936 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
937 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
938 }
939
940 return nullptr;
941}
942
Sanjay Patel103ab7d2016-02-01 22:10:26 +0000943static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
944 // If the mask is all zeros, return the "passthru" argument of the gather.
945 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
946 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +0000947 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +0000948
949 return nullptr;
950}
951
952static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
953 // If the mask is all zeros, a scatter does nothing.
954 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
955 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +0000956 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +0000957
958 return nullptr;
959}
960
Sanjay Patel1ace9932016-02-26 21:04:14 +0000961// TODO: If the x86 backend knew how to convert a bool vector mask back to an
962// XMM register mask efficiently, we could transform all x86 masked intrinsics
963// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +0000964static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
965 Value *Ptr = II.getOperand(0);
966 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +0000967 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +0000968
969 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +0000970 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +0000971 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +0000972 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +0000973
974 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
975 if (!ConstMask)
976 return nullptr;
977
978 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
979 // to allow target-independent optimizations.
980
981 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
982 // the LLVM intrinsic definition for the pointer argument.
983 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
984 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
985 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
986
987 // Second, convert the x86 XMM integer vector mask to a vector of bools based
988 // on each element's most significant bit (the sign bit).
989 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
990
Sanjay Patel5e5056d2016-04-12 23:16:23 +0000991 // The pass-through vector for an x86 masked load is a zero vector.
992 CallInst *NewMaskedLoad =
993 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +0000994 return IC.replaceInstUsesWith(II, NewMaskedLoad);
995}
996
997// TODO: If the x86 backend knew how to convert a bool vector mask back to an
998// XMM register mask efficiently, we could transform all x86 masked intrinsics
999// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001000static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1001 Value *Ptr = II.getOperand(0);
1002 Value *Mask = II.getOperand(1);
1003 Value *Vec = II.getOperand(2);
1004
1005 // Special case a zero mask since that's not a ConstantDataVector:
1006 // this masked store instruction does nothing.
1007 if (isa<ConstantAggregateZero>(Mask)) {
1008 IC.eraseInstFromFunction(II);
1009 return true;
1010 }
1011
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001012 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1013 // anything else at this level.
1014 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1015 return false;
1016
Sanjay Patel1ace9932016-02-26 21:04:14 +00001017 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1018 if (!ConstMask)
1019 return false;
1020
1021 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1022 // to allow target-independent optimizations.
1023
1024 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1025 // the LLVM intrinsic definition for the pointer argument.
1026 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1027 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001028 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1029
1030 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1031 // on each element's most significant bit (the sign bit).
1032 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1033
1034 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1035
1036 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1037 IC.eraseInstFromFunction(II);
1038 return true;
1039}
1040
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001041/// CallInst simplification. This mostly only handles folding of intrinsic
1042/// instructions. For normal calls, it allows visitCallSite to do the heavy
1043/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001044Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001045 auto Args = CI.arg_operands();
1046 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
1047 TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001048 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001049
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00001050 if (isFreeCall(&CI, TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001051 return visitFree(CI);
1052
1053 // If the caller function is nounwind, mark the call as nounwind, even if the
1054 // callee isn't.
1055 if (CI.getParent()->getParent()->doesNotThrow() &&
1056 !CI.doesNotThrow()) {
1057 CI.setDoesNotThrow();
1058 return &CI;
1059 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001060
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001061 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1062 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001063
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001064 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1065 // visitCallSite.
1066 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1067 bool Changed = false;
1068
1069 // memmove/cpy/set of zero bytes is a noop.
1070 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001071 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001072 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001073
1074 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1075 if (CI->getZExtValue() == 1) {
1076 // Replace the instruction with just byte operations. We would
1077 // transform other cases to loads/stores, but we don't know if
1078 // alignment is sufficient.
1079 }
1080 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001081
Chris Lattnerc663a672010-10-01 05:51:02 +00001082 // No other transformations apply to volatile transfers.
1083 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001084 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001085
1086 // If we have a memmove and the source operation is a constant global,
1087 // then the source and dest pointers can't alias, so we can change this
1088 // into a call to memcpy.
1089 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1090 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1091 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001092 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001093 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001094 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1095 CI.getArgOperand(1)->getType(),
1096 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001097 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001098 Changed = true;
1099 }
1100 }
1101
1102 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1103 // memmove(x,x,size) -> noop.
1104 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001105 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001106 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001107
Eric Christopher7258dcd2010-04-16 23:37:20 +00001108 // If we can determine a pointer alignment that is bigger than currently
1109 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001110 if (isa<MemTransferInst>(MI)) {
1111 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001112 return I;
1113 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1114 if (Instruction *I = SimplifyMemSet(MSI))
1115 return I;
1116 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001117
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001118 if (Changed) return II;
1119 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001120
Sanjay Patel1c600c62016-01-20 16:41:43 +00001121 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1122 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001123 APInt UndefElts(Width, 0);
1124 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1125 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1126 };
Simon Pilgrim424da162016-04-24 18:12:42 +00001127 auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1128 unsigned DemandedWidth) {
1129 APInt UndefElts(Width, 0);
1130 APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1131 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1132 };
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001133
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001134 switch (II->getIntrinsicID()) {
1135 default: break;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001136 case Intrinsic::objectsize: {
Nuno Lopes55fff832012-06-21 15:45:28 +00001137 uint64_t Size;
George Burgess IV278199f2016-04-12 01:05:35 +00001138 if (getObjectSize(II->getArgOperand(0), Size, DL, TLI)) {
1139 APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1140 // Equality check to be sure that `Size` can fit in a value of type
1141 // `II->getType()`
1142 if (APSize == Size)
1143 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1144 }
Craig Topperf40110f2014-04-25 05:29:35 +00001145 return nullptr;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001146 }
Michael Ilseman536cc322012-12-13 03:13:36 +00001147 case Intrinsic::bswap: {
1148 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001149 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001150
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001151 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001152 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001153 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001154
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001155 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001156 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1157 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1158 IIOperand->getType()->getPrimitiveSizeInBits();
1159 Value *CV = ConstantInt::get(X->getType(), C);
1160 Value *V = Builder->CreateLShr(X, CV);
1161 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001162 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001163 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001164 }
1165
James Molloy2d09c002015-11-12 12:39:41 +00001166 case Intrinsic::bitreverse: {
1167 Value *IIOperand = II->getArgOperand(0);
1168 Value *X = nullptr;
1169
1170 // bitreverse(bitreverse(x)) -> x
1171 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001172 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001173 break;
1174 }
1175
Sanjay Patelb695c552016-02-01 17:00:10 +00001176 case Intrinsic::masked_load:
1177 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001178 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001179 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001180 case Intrinsic::masked_store:
1181 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001182 case Intrinsic::masked_gather:
1183 return simplifyMaskedGather(*II, *this);
1184 case Intrinsic::masked_scatter:
1185 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001186
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001187 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001188 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001189 // powi(x, 0) -> 1.0
1190 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001191 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001192 // powi(x, 1) -> x
1193 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001194 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001195 // powi(x, -1) -> 1/x
1196 if (Power->isAllOnesValue())
1197 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001198 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001199 }
1200 break;
1201 case Intrinsic::cttz: {
1202 // If all bits below the first known one are known zero,
1203 // this value is constant.
Chris Lattner229907c2011-07-18 04:54:35 +00001204 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Anderson2f37bdc2011-07-01 21:52:38 +00001205 // FIXME: Try to simplify vectors of integers.
1206 if (!IT) break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001207 uint32_t BitWidth = IT->getBitWidth();
1208 APInt KnownZero(BitWidth, 0);
1209 APInt KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001210 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001211 unsigned TrailingZeros = KnownOne.countTrailingZeros();
1212 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
1213 if ((Mask & KnownZero) == Mask)
Sanjay Patel4b198802016-02-01 22:23:39 +00001214 return replaceInstUsesWith(CI, ConstantInt::get(IT,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001215 APInt(BitWidth, TrailingZeros)));
Jim Grosbach7815f562012-02-03 00:07:04 +00001216
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001217 }
1218 break;
1219 case Intrinsic::ctlz: {
1220 // If all bits above the first known one are known zero,
1221 // this value is constant.
Chris Lattner229907c2011-07-18 04:54:35 +00001222 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Anderson2f37bdc2011-07-01 21:52:38 +00001223 // FIXME: Try to simplify vectors of integers.
1224 if (!IT) break;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001225 uint32_t BitWidth = IT->getBitWidth();
1226 APInt KnownZero(BitWidth, 0);
1227 APInt KnownOne(BitWidth, 0);
Hal Finkel60db0582014-09-07 18:57:58 +00001228 computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001229 unsigned LeadingZeros = KnownOne.countLeadingZeros();
1230 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
1231 if ((Mask & KnownZero) == Mask)
Sanjay Patel4b198802016-02-01 22:23:39 +00001232 return replaceInstUsesWith(CI, ConstantInt::get(IT,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001233 APInt(BitWidth, LeadingZeros)));
Jim Grosbach7815f562012-02-03 00:07:04 +00001234
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001235 }
1236 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001237
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001238 case Intrinsic::uadd_with_overflow:
1239 case Intrinsic::sadd_with_overflow:
1240 case Intrinsic::umul_with_overflow:
1241 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001242 if (isa<Constant>(II->getArgOperand(0)) &&
1243 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001244 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001245 Value *LHS = II->getArgOperand(0);
1246 II->setArgOperand(0, II->getArgOperand(1));
1247 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001248 return II;
1249 }
Nick Lewyckyd6f241d2015-04-13 20:03:08 +00001250 // fall through
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001251
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001252 case Intrinsic::usub_with_overflow:
1253 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001254 OverflowCheckFlavor OCF =
1255 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1256 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001257
Sanjoy Dasb0984472015-04-08 04:27:22 +00001258 Value *OperationResult = nullptr;
1259 Constant *OverflowResult = nullptr;
1260 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1261 *II, OperationResult, OverflowResult))
1262 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001263
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001264 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001265 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001266
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001267 case Intrinsic::minnum:
1268 case Intrinsic::maxnum: {
1269 Value *Arg0 = II->getArgOperand(0);
1270 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001271 // Canonicalize constants to the RHS.
1272 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001273 II->setArgOperand(0, Arg1);
1274 II->setArgOperand(1, Arg0);
1275 return II;
1276 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001277 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001278 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001279 break;
1280 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001281 case Intrinsic::ppc_altivec_lvx:
1282 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001283 // Turn PPC lvx -> load if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001284 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
Chandler Carruth66b31302015-01-04 12:03:27 +00001285 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001286 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001287 PointerType::getUnqual(II->getType()));
1288 return new LoadInst(Ptr);
1289 }
1290 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001291 case Intrinsic::ppc_vsx_lxvw4x:
1292 case Intrinsic::ppc_vsx_lxvd2x: {
1293 // Turn PPC VSX loads into normal loads.
1294 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1295 PointerType::getUnqual(II->getType()));
1296 return new LoadInst(Ptr, Twine(""), false, 1);
1297 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001298 case Intrinsic::ppc_altivec_stvx:
1299 case Intrinsic::ppc_altivec_stvxl:
1300 // Turn stvx -> store if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001301 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
Chandler Carruth66b31302015-01-04 12:03:27 +00001302 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001303 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001304 PointerType::getUnqual(II->getArgOperand(0)->getType());
1305 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1306 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001307 }
1308 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001309 case Intrinsic::ppc_vsx_stxvw4x:
1310 case Intrinsic::ppc_vsx_stxvd2x: {
1311 // Turn PPC VSX stores into normal stores.
1312 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1313 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1314 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1315 }
Hal Finkel221f4672015-02-26 18:56:03 +00001316 case Intrinsic::ppc_qpx_qvlfs:
1317 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001318 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001319 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001320 Type *VTy = VectorType::get(Builder->getFloatTy(),
1321 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001322 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001323 PointerType::getUnqual(VTy));
1324 Value *Load = Builder->CreateLoad(Ptr);
1325 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001326 }
1327 break;
1328 case Intrinsic::ppc_qpx_qvlfd:
1329 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001330 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001331 32) {
1332 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1333 PointerType::getUnqual(II->getType()));
1334 return new LoadInst(Ptr);
1335 }
1336 break;
1337 case Intrinsic::ppc_qpx_qvstfs:
1338 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001339 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001340 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001341 Type *VTy = VectorType::get(Builder->getFloatTy(),
1342 II->getArgOperand(0)->getType()->getVectorNumElements());
1343 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1344 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001345 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001346 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001347 }
1348 break;
1349 case Intrinsic::ppc_qpx_qvstfd:
1350 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001351 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, AC, DT) >=
Hal Finkel221f4672015-02-26 18:56:03 +00001352 32) {
1353 Type *OpPtrTy =
1354 PointerType::getUnqual(II->getArgOperand(0)->getType());
1355 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1356 return new StoreInst(II->getArgOperand(0), Ptr);
1357 }
1358 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001359
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001360 case Intrinsic::x86_sse_storeu_ps:
1361 case Intrinsic::x86_sse2_storeu_pd:
1362 case Intrinsic::x86_sse2_storeu_dq:
1363 // Turn X86 storeu -> store if the pointer is known aligned.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001364 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
Chandler Carruth66b31302015-01-04 12:03:27 +00001365 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001366 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001367 PointerType::getUnqual(II->getArgOperand(1)->getType());
1368 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
1369 return new StoreInst(II->getArgOperand(1), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001370 }
1371 break;
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001372
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001373 case Intrinsic::x86_vcvtph2ps_128:
1374 case Intrinsic::x86_vcvtph2ps_256: {
1375 auto Arg = II->getArgOperand(0);
1376 auto ArgType = cast<VectorType>(Arg->getType());
1377 auto RetType = cast<VectorType>(II->getType());
1378 unsigned ArgWidth = ArgType->getNumElements();
1379 unsigned RetWidth = RetType->getNumElements();
1380 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1381 assert(ArgType->isIntOrIntVectorTy() &&
1382 ArgType->getScalarSizeInBits() == 16 &&
1383 "CVTPH2PS input type should be 16-bit integer vector");
1384 assert(RetType->getScalarType()->isFloatTy() &&
1385 "CVTPH2PS output type should be 32-bit float vector");
1386
1387 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001388 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001389 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001390
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001391 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001392 auto VectorHalfAsShorts = Arg;
1393 if (RetWidth < ArgWidth) {
1394 SmallVector<int, 8> SubVecMask;
1395 for (unsigned i = 0; i != RetWidth; ++i)
1396 SubVecMask.push_back((int)i);
1397 VectorHalfAsShorts = Builder->CreateShuffleVector(
1398 Arg, UndefValue::get(ArgType), SubVecMask);
1399 }
1400
1401 auto VectorHalfType =
1402 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1403 auto VectorHalfs =
1404 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1405 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001406 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001407 }
1408
1409 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001410 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001411 II->setArgOperand(0, V);
1412 return II;
1413 }
1414 break;
1415 }
1416
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001417 case Intrinsic::x86_sse_cvtss2si:
1418 case Intrinsic::x86_sse_cvtss2si64:
1419 case Intrinsic::x86_sse_cvttss2si:
1420 case Intrinsic::x86_sse_cvttss2si64:
1421 case Intrinsic::x86_sse2_cvtsd2si:
1422 case Intrinsic::x86_sse2_cvtsd2si64:
1423 case Intrinsic::x86_sse2_cvttsd2si:
1424 case Intrinsic::x86_sse2_cvttsd2si64: {
1425 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001426 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001427 Value *Arg = II->getArgOperand(0);
1428 unsigned VWidth = Arg->getType()->getVectorNumElements();
1429 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001430 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001431 return II;
1432 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001433 break;
1434 }
1435
Simon Pilgrim471efd22016-02-20 23:17:35 +00001436 case Intrinsic::x86_sse_comieq_ss:
1437 case Intrinsic::x86_sse_comige_ss:
1438 case Intrinsic::x86_sse_comigt_ss:
1439 case Intrinsic::x86_sse_comile_ss:
1440 case Intrinsic::x86_sse_comilt_ss:
1441 case Intrinsic::x86_sse_comineq_ss:
1442 case Intrinsic::x86_sse_ucomieq_ss:
1443 case Intrinsic::x86_sse_ucomige_ss:
1444 case Intrinsic::x86_sse_ucomigt_ss:
1445 case Intrinsic::x86_sse_ucomile_ss:
1446 case Intrinsic::x86_sse_ucomilt_ss:
1447 case Intrinsic::x86_sse_ucomineq_ss:
1448 case Intrinsic::x86_sse2_comieq_sd:
1449 case Intrinsic::x86_sse2_comige_sd:
1450 case Intrinsic::x86_sse2_comigt_sd:
1451 case Intrinsic::x86_sse2_comile_sd:
1452 case Intrinsic::x86_sse2_comilt_sd:
1453 case Intrinsic::x86_sse2_comineq_sd:
1454 case Intrinsic::x86_sse2_ucomieq_sd:
1455 case Intrinsic::x86_sse2_ucomige_sd:
1456 case Intrinsic::x86_sse2_ucomigt_sd:
1457 case Intrinsic::x86_sse2_ucomile_sd:
1458 case Intrinsic::x86_sse2_ucomilt_sd:
1459 case Intrinsic::x86_sse2_ucomineq_sd: {
1460 // These intrinsics only demand the 0th element of their input vectors. If
1461 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001462 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001463 Value *Arg0 = II->getArgOperand(0);
1464 Value *Arg1 = II->getArgOperand(1);
1465 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1466 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1467 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001468 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001469 }
1470 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1471 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001472 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001473 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001474 if (MadeChange)
1475 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001476 break;
1477 }
1478
Simon Pilgrim424da162016-04-24 18:12:42 +00001479 case Intrinsic::x86_sse_add_ss:
1480 case Intrinsic::x86_sse_sub_ss:
1481 case Intrinsic::x86_sse_mul_ss:
1482 case Intrinsic::x86_sse_div_ss:
1483 case Intrinsic::x86_sse_min_ss:
1484 case Intrinsic::x86_sse_max_ss:
1485 case Intrinsic::x86_sse_cmp_ss:
1486 case Intrinsic::x86_sse2_add_sd:
1487 case Intrinsic::x86_sse2_sub_sd:
1488 case Intrinsic::x86_sse2_mul_sd:
1489 case Intrinsic::x86_sse2_div_sd:
1490 case Intrinsic::x86_sse2_min_sd:
1491 case Intrinsic::x86_sse2_max_sd:
1492 case Intrinsic::x86_sse2_cmp_sd: {
1493 // These intrinsics only demand the lowest element of the second input
1494 // vector.
1495 Value *Arg1 = II->getArgOperand(1);
1496 unsigned VWidth = Arg1->getType()->getVectorNumElements();
1497 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1498 II->setArgOperand(1, V);
1499 return II;
1500 }
1501 break;
1502 }
1503
1504 case Intrinsic::x86_sse41_round_ss:
1505 case Intrinsic::x86_sse41_round_sd: {
1506 // These intrinsics demand the upper elements of the first input vector and
1507 // the lowest element of the second input vector.
1508 bool MadeChange = false;
1509 Value *Arg0 = II->getArgOperand(0);
1510 Value *Arg1 = II->getArgOperand(1);
1511 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1512 if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1513 II->setArgOperand(0, V);
1514 MadeChange = true;
1515 }
1516 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1517 II->setArgOperand(1, V);
1518 MadeChange = true;
1519 }
1520 if (MadeChange)
1521 return II;
1522 break;
1523 }
1524
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001525 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001526 // Constant fold lshr( <A x Bi>, Ci ).
1527 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001528 case Intrinsic::x86_sse2_psrai_d:
1529 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001530 case Intrinsic::x86_avx2_psrai_d:
1531 case Intrinsic::x86_avx2_psrai_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001532 case Intrinsic::x86_sse2_psrli_d:
1533 case Intrinsic::x86_sse2_psrli_q:
1534 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001535 case Intrinsic::x86_avx2_psrli_d:
1536 case Intrinsic::x86_avx2_psrli_q:
1537 case Intrinsic::x86_avx2_psrli_w:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00001538 case Intrinsic::x86_sse2_pslli_d:
1539 case Intrinsic::x86_sse2_pslli_q:
1540 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001541 case Intrinsic::x86_avx2_pslli_d:
1542 case Intrinsic::x86_avx2_pslli_q:
1543 case Intrinsic::x86_avx2_pslli_w:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001544 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001545 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00001546 break;
1547
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001548 case Intrinsic::x86_sse2_psra_d:
1549 case Intrinsic::x86_sse2_psra_w:
1550 case Intrinsic::x86_avx2_psra_d:
1551 case Intrinsic::x86_avx2_psra_w:
1552 case Intrinsic::x86_sse2_psrl_d:
1553 case Intrinsic::x86_sse2_psrl_q:
1554 case Intrinsic::x86_sse2_psrl_w:
1555 case Intrinsic::x86_avx2_psrl_d:
1556 case Intrinsic::x86_avx2_psrl_q:
1557 case Intrinsic::x86_avx2_psrl_w:
1558 case Intrinsic::x86_sse2_psll_d:
1559 case Intrinsic::x86_sse2_psll_q:
1560 case Intrinsic::x86_sse2_psll_w:
1561 case Intrinsic::x86_avx2_psll_d:
1562 case Intrinsic::x86_avx2_psll_q:
1563 case Intrinsic::x86_avx2_psll_w: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001564 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001565 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001566
1567 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1568 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001569 Value *Arg1 = II->getArgOperand(1);
1570 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001571 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00001572 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001573
Simon Pilgrim996725e2015-09-19 11:41:53 +00001574 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001575 II->setArgOperand(1, V);
1576 return II;
1577 }
1578 break;
1579 }
1580
Simon Pilgrim15c0a592015-07-27 18:52:15 +00001581 case Intrinsic::x86_avx2_pmovsxbd:
1582 case Intrinsic::x86_avx2_pmovsxbq:
1583 case Intrinsic::x86_avx2_pmovsxbw:
1584 case Intrinsic::x86_avx2_pmovsxdq:
1585 case Intrinsic::x86_avx2_pmovsxwd:
1586 case Intrinsic::x86_avx2_pmovsxwq:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001587 if (Value *V = simplifyX86extend(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00001588 return replaceInstUsesWith(*II, V);
Stuart Hastings5bd18b62011-05-17 22:13:31 +00001589 break;
Simon Pilgrim15c0a592015-07-27 18:52:15 +00001590
1591 case Intrinsic::x86_sse41_pmovzxbd:
1592 case Intrinsic::x86_sse41_pmovzxbq:
1593 case Intrinsic::x86_sse41_pmovzxbw:
1594 case Intrinsic::x86_sse41_pmovzxdq:
1595 case Intrinsic::x86_sse41_pmovzxwd:
1596 case Intrinsic::x86_sse41_pmovzxwq:
1597 case Intrinsic::x86_avx2_pmovzxbd:
1598 case Intrinsic::x86_avx2_pmovzxbq:
1599 case Intrinsic::x86_avx2_pmovzxbw:
1600 case Intrinsic::x86_avx2_pmovzxdq:
1601 case Intrinsic::x86_avx2_pmovzxwd:
1602 case Intrinsic::x86_avx2_pmovzxwq:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001603 if (Value *V = simplifyX86extend(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00001604 return replaceInstUsesWith(*II, V);
Simon Pilgrim15c0a592015-07-27 18:52:15 +00001605 break;
1606
Sanjay Patelc86867c2015-04-16 17:52:13 +00001607 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001608 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001609 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00001610 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001611
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001612 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001613 Value *Op0 = II->getArgOperand(0);
1614 Value *Op1 = II->getArgOperand(1);
1615 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1616 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001617 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1618 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1619 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001620
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001621 // See if we're dealing with constant values.
1622 Constant *C1 = dyn_cast<Constant>(Op1);
1623 ConstantInt *CILength =
1624 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
1625 : nullptr;
1626 ConstantInt *CIIndex =
1627 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1628 : nullptr;
1629
1630 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001631 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001632 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001633
1634 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1635 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001636 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001637 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1638 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001639 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001640 }
1641 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1642 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001643 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001644 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001645 if (MadeChange)
1646 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001647 break;
1648 }
1649
1650 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001651 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1652 // bits of the lower 64-bits. The upper 64-bits are undefined.
1653 Value *Op0 = II->getArgOperand(0);
1654 unsigned VWidth = Op0->getType()->getVectorNumElements();
1655 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1656 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001657
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001658 // See if we're dealing with constant values.
1659 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1660 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1661
1662 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001663 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001664 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001665
1666 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1667 // operand.
1668 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001669 II->setArgOperand(0, V);
1670 return II;
1671 }
1672 break;
1673 }
1674
1675 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001676 Value *Op0 = II->getArgOperand(0);
1677 Value *Op1 = II->getArgOperand(1);
1678 unsigned VWidth = Op0->getType()->getVectorNumElements();
1679 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1680 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1681 Op1->getType()->getVectorNumElements() == 2 &&
1682 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001683
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001684 // See if we're dealing with constant values.
1685 Constant *C1 = dyn_cast<Constant>(Op1);
1686 ConstantInt *CI11 =
1687 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1688 : nullptr;
1689
1690 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1691 if (CI11) {
1692 APInt V11 = CI11->getValue();
1693 APInt Len = V11.zextOrTrunc(6);
1694 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001695 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001696 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001697 }
1698
1699 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1700 // operand.
1701 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001702 II->setArgOperand(0, V);
1703 return II;
1704 }
1705 break;
1706 }
1707
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001708 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001709 // INSERTQI: Extract lowest Length bits from lower half of second source and
1710 // insert over first source starting at Index bit. The upper 64-bits are
1711 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001712 Value *Op0 = II->getArgOperand(0);
1713 Value *Op1 = II->getArgOperand(1);
1714 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1715 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001716 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1717 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1718 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001719
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001720 // See if we're dealing with constant values.
1721 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
1722 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
1723
1724 // Attempt to simplify to a constant or shuffle vector.
1725 if (CILength && CIIndex) {
1726 APInt Len = CILength->getValue().zextOrTrunc(6);
1727 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001728 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001729 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001730 }
1731
1732 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
1733 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001734 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001735 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1736 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001737 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001738 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001739 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
1740 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001741 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001742 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001743 if (MadeChange)
1744 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001745 break;
1746 }
1747
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001748 case Intrinsic::x86_sse41_pblendvb:
1749 case Intrinsic::x86_sse41_blendvps:
1750 case Intrinsic::x86_sse41_blendvpd:
1751 case Intrinsic::x86_avx_blendv_ps_256:
1752 case Intrinsic::x86_avx_blendv_pd_256:
1753 case Intrinsic::x86_avx2_pblendvb: {
1754 // Convert blendv* to vector selects if the mask is constant.
1755 // This optimization is convoluted because the intrinsic is defined as
1756 // getting a vector of floats or doubles for the ps and pd versions.
1757 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001758
1759 Value *Op0 = II->getArgOperand(0);
1760 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001761 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001762
1763 // fold (blend A, A, Mask) -> A
1764 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00001765 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001766
1767 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00001768 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00001769 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001770
1771 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00001772 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
1773 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001774 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001775 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001776 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001777 }
1778
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00001779 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001780 case Intrinsic::x86_avx2_pshuf_b:
1781 if (Value *V = simplifyX86pshufb(*II, *Builder))
1782 return replaceInstUsesWith(*II, V);
1783 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00001784
Rafael Espindolabad3f772014-04-21 22:06:04 +00001785 case Intrinsic::x86_avx_vpermilvar_ps:
1786 case Intrinsic::x86_avx_vpermilvar_ps_256:
1787 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001788 case Intrinsic::x86_avx_vpermilvar_pd_256:
1789 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
1790 return replaceInstUsesWith(*II, V);
1791 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00001792
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001793 case Intrinsic::x86_avx2_permd:
1794 case Intrinsic::x86_avx2_permps:
1795 if (Value *V = simplifyX86vpermv(*II, *Builder))
1796 return replaceInstUsesWith(*II, V);
1797 break;
1798
Sanjay Patelccf5f242015-03-20 21:47:56 +00001799 case Intrinsic::x86_avx_vperm2f128_pd_256:
1800 case Intrinsic::x86_avx_vperm2f128_ps_256:
1801 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00001802 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001803 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001804 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00001805 break;
1806
Sanjay Patel98a71502016-02-29 23:16:48 +00001807 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00001808 case Intrinsic::x86_avx_maskload_pd:
1809 case Intrinsic::x86_avx_maskload_ps_256:
1810 case Intrinsic::x86_avx_maskload_pd_256:
1811 case Intrinsic::x86_avx2_maskload_d:
1812 case Intrinsic::x86_avx2_maskload_q:
1813 case Intrinsic::x86_avx2_maskload_d_256:
1814 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00001815 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
1816 return I;
1817 break;
1818
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001819 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00001820 case Intrinsic::x86_avx_maskstore_ps:
1821 case Intrinsic::x86_avx_maskstore_pd:
1822 case Intrinsic::x86_avx_maskstore_ps_256:
1823 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00001824 case Intrinsic::x86_avx2_maskstore_d:
1825 case Intrinsic::x86_avx2_maskstore_q:
1826 case Intrinsic::x86_avx2_maskstore_d_256:
1827 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00001828 if (simplifyX86MaskedStore(*II, *this))
1829 return nullptr;
1830 break;
1831
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001832 case Intrinsic::x86_xop_vpcomb:
1833 case Intrinsic::x86_xop_vpcomd:
1834 case Intrinsic::x86_xop_vpcomq:
1835 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001836 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00001837 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001838 break;
1839
1840 case Intrinsic::x86_xop_vpcomub:
1841 case Intrinsic::x86_xop_vpcomud:
1842 case Intrinsic::x86_xop_vpcomuq:
1843 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001844 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00001845 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001846 break;
1847
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001848 case Intrinsic::ppc_altivec_vperm:
1849 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00001850 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
1851 // a vectorshuffle for little endian, we must undo the transformation
1852 // performed on vec_perm in altivec.h. That is, we must complement
1853 // the permutation mask with respect to 31 and reverse the order of
1854 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00001855 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
1856 assert(Mask->getType()->getVectorNumElements() == 16 &&
1857 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001858
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001859 // Check that all of the elements are integer constants or undefs.
1860 bool AllEltsOk = true;
1861 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00001862 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00001863 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001864 AllEltsOk = false;
1865 break;
1866 }
1867 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001868
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001869 if (AllEltsOk) {
1870 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00001871 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
1872 Mask->getType());
1873 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
1874 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001875 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00001876
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001877 // Only extract each element once.
1878 Value *ExtractedElts[32];
1879 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00001880
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001881 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00001882 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001883 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00001884 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00001885 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001886 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001887 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00001888 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00001889
Craig Topperf40110f2014-04-25 05:29:35 +00001890 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001891 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
1892 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00001893 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00001894 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001895 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001896 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001897
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001898 // Insert this value into the result vector.
1899 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00001900 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001901 }
1902 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
1903 }
1904 }
1905 break;
1906
Bob Wilsona4e231c2010-10-22 21:41:48 +00001907 case Intrinsic::arm_neon_vld1:
1908 case Intrinsic::arm_neon_vld2:
1909 case Intrinsic::arm_neon_vld3:
1910 case Intrinsic::arm_neon_vld4:
1911 case Intrinsic::arm_neon_vld2lane:
1912 case Intrinsic::arm_neon_vld3lane:
1913 case Intrinsic::arm_neon_vld4lane:
1914 case Intrinsic::arm_neon_vst1:
1915 case Intrinsic::arm_neon_vst2:
1916 case Intrinsic::arm_neon_vst3:
1917 case Intrinsic::arm_neon_vst4:
1918 case Intrinsic::arm_neon_vst2lane:
1919 case Intrinsic::arm_neon_vst3lane:
1920 case Intrinsic::arm_neon_vst4lane: {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001921 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, II, AC, DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00001922 unsigned AlignArg = II->getNumArgOperands() - 1;
1923 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
1924 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
1925 II->setArgOperand(AlignArg,
1926 ConstantInt::get(Type::getInt32Ty(II->getContext()),
1927 MemAlign, false));
1928 return II;
1929 }
1930 break;
1931 }
1932
Lang Hames3a90fab2012-05-01 00:20:38 +00001933 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00001934 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00001935 case Intrinsic::aarch64_neon_smull:
1936 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00001937 Value *Arg0 = II->getArgOperand(0);
1938 Value *Arg1 = II->getArgOperand(1);
1939
1940 // Handle mul by zero first:
1941 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00001942 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00001943 }
1944
1945 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00001946 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00001947 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00001948 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00001949 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1950 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1951 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1952 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1953
Sanjay Patel4b198802016-02-01 22:23:39 +00001954 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00001955 }
1956
Alp Tokercb402912014-01-24 17:20:08 +00001957 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00001958 std::swap(Arg0, Arg1);
1959 }
1960
1961 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00001962 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00001963 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00001964 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1965 if (Splat->isOne())
1966 return CastInst::CreateIntegerCast(Arg0, II->getType(),
1967 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00001968
1969 break;
1970 }
1971
Matt Arsenaultbef34e22016-01-22 21:30:34 +00001972 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00001973 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
1974 const APFloat &ArgVal = C->getValueAPF();
1975 APFloat Val(ArgVal.getSemantics(), 1.0);
1976 APFloat::opStatus Status = Val.divide(ArgVal,
1977 APFloat::rmNearestTiesToEven);
1978 // Only do this if it was exact and therefore not dependent on the
1979 // rounding mode.
1980 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00001981 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00001982 }
1983
1984 break;
1985 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00001986 case Intrinsic::amdgcn_frexp_mant:
1987 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00001988 Value *Src = II->getArgOperand(0);
1989 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
1990 int Exp;
1991 APFloat Significand = frexp(C->getValueAPF(), Exp,
1992 APFloat::rmNearestTiesToEven);
1993
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00001994 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
1995 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
1996 Significand));
1997 }
1998
1999 // Match instruction special case behavior.
2000 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2001 Exp = 0;
2002
2003 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2004 }
2005
2006 if (isa<UndefValue>(Src))
2007 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002008
2009 break;
2010 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002011 case Intrinsic::stackrestore: {
2012 // If the save is right next to the restore, remove the restore. This can
2013 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002014 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002015 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002016 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002017 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002018 }
2019 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002020
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002021 // Scan down this block to see if there is another stack restore in the
2022 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002023 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002024 TerminatorInst *TI = II->getParent()->getTerminator();
2025 bool CannotRemove = false;
2026 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002027 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002028 CannotRemove = true;
2029 break;
2030 }
2031 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2032 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2033 // If there is a stackrestore below this one, remove this one.
2034 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002035 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002036
2037 // Bail if we cross over an intrinsic with side effects, such as
2038 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2039 if (II->mayHaveSideEffects()) {
2040 CannotRemove = true;
2041 break;
2042 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002043 } else {
2044 // If we found a non-intrinsic call, we can't remove the stack
2045 // restore.
2046 CannotRemove = true;
2047 break;
2048 }
2049 }
2050 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002051
Bill Wendlingf891bf82011-07-31 06:30:59 +00002052 // If the stack restore is in a return, resume, or unwind block and if there
2053 // are no allocas or calls between the restore and the return, nuke the
2054 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002055 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002056 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002057 break;
2058 }
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002059 case Intrinsic::lifetime_start: {
2060 // Remove trivially empty lifetime_start/end ranges, i.e. a start
2061 // immediately followed by an end (ignoring debuginfo or other
2062 // lifetime markers in between).
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002063 BasicBlock::iterator BI = II->getIterator(), BE = II->getParent()->end();
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002064 for (++BI; BI != BE; ++BI) {
2065 if (IntrinsicInst *LTE = dyn_cast<IntrinsicInst>(BI)) {
2066 if (isa<DbgInfoIntrinsic>(LTE) ||
2067 LTE->getIntrinsicID() == Intrinsic::lifetime_start)
2068 continue;
2069 if (LTE->getIntrinsicID() == Intrinsic::lifetime_end) {
2070 if (II->getOperand(0) == LTE->getOperand(0) &&
2071 II->getOperand(1) == LTE->getOperand(1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002072 eraseInstFromFunction(*LTE);
2073 return eraseInstFromFunction(*II);
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002074 }
2075 continue;
2076 }
2077 }
2078 break;
2079 }
2080 break;
2081 }
Hal Finkelf5867a72014-07-25 21:45:17 +00002082 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002083 Value *IIOperand = II->getArgOperand(0);
2084 // Remove an assume if it is immediately followed by an identical assume.
2085 if (match(II->getNextNode(),
2086 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2087 return eraseInstFromFunction(CI);
2088
Hal Finkelf5867a72014-07-25 21:45:17 +00002089 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002090 // Note: New assumption intrinsics created here are registered by
2091 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002092 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002093 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2094 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2095 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002096 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002097 }
2098 // assume(!(a || b)) -> assume(!a); assume(!b);
2099 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002100 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2101 II->getName());
2102 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2103 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002104 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002105 }
Hal Finkel04a15612014-10-04 21:27:06 +00002106
Philip Reames66c6de62014-11-11 23:33:19 +00002107 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2108 // (if assume is valid at the load)
2109 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2110 Value *LHS = ICmp->getOperand(0);
2111 Value *RHS = ICmp->getOperand(1);
2112 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2113 isa<LoadInst>(LHS) &&
2114 isa<Constant>(RHS) &&
2115 RHS->getType()->isPointerTy() &&
2116 cast<Constant>(RHS)->isNullValue()) {
2117 LoadInst* LI = cast<LoadInst>(LHS);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002118 if (isValidAssumeForContext(II, LI, DT)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002119 MDNode *MD = MDNode::get(II->getContext(), None);
Philip Reames66c6de62014-11-11 23:33:19 +00002120 LI->setMetadata(LLVMContext::MD_nonnull, MD);
Sanjay Patel4b198802016-02-01 22:23:39 +00002121 return eraseInstFromFunction(*II);
Philip Reames66c6de62014-11-11 23:33:19 +00002122 }
2123 }
Chandler Carruth24969102015-02-10 08:07:32 +00002124 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002125 // TODO: apply range metadata for range check patterns?
2126 }
Hal Finkel04a15612014-10-04 21:27:06 +00002127 // If there is a dominating assume with the same condition as this one,
2128 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002129 APInt KnownZero(1, 0), KnownOne(1, 0);
2130 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2131 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002132 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002133
Hal Finkelf5867a72014-07-25 21:45:17 +00002134 break;
2135 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002136 case Intrinsic::experimental_gc_relocate: {
2137 // Translate facts known about a pointer before relocating into
2138 // facts about the relocate value, while being careful to
2139 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002140 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002141
2142 // Remove the relocation if unused, note that this check is required
2143 // to prevent the cases below from looping forever.
2144 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002145 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002146
2147 // Undef is undef, even after relocation.
2148 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2149 // most practical collectors, but there was discussion in the review thread
2150 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002151 if (isa<UndefValue>(DerivedPtr))
2152 // Use undef of gc_relocate's type to replace it.
2153 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002154
Philip Reamesea4d8e82016-02-09 21:09:22 +00002155 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2156 // The relocation of null will be null for most any collector.
2157 // TODO: provide a hook for this in GCStrategy. There might be some
2158 // weird collector this property does not hold for.
2159 if (isa<ConstantPointerNull>(DerivedPtr))
2160 // Use null-pointer of gc_relocate's type to replace it.
2161 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002162
Philip Reamesea4d8e82016-02-09 21:09:22 +00002163 // isKnownNonNull -> nonnull attribute
2164 if (isKnownNonNullAt(DerivedPtr, II, DT, TLI))
2165 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002166 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002167
2168 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2169 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002170
Philip Reames9db26ff2014-12-29 23:27:30 +00002171 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002172 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002173 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002174 }
2175
2176 return visitCallSite(II);
2177}
2178
2179// InvokeInst simplification
2180//
2181Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2182 return visitCallSite(&II);
2183}
2184
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002185/// If this cast does not affect the value passed through the varargs area, we
2186/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002187static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002188 const DataLayout &DL,
2189 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002190 const int ix) {
2191 if (!CI->isLosslessCast())
2192 return false;
2193
Philip Reames1a1bdb22014-12-02 18:50:36 +00002194 // If this is a GC intrinsic, avoid munging types. We need types for
2195 // statepoint reconstruction in SelectionDAG.
2196 // TODO: This is probably something which should be expanded to all
2197 // intrinsics since the entire point of intrinsics is that
2198 // they are understandable by the optimizer.
2199 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2200 return false;
2201
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002202 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002203 // can't change to a type with a different size. If the size were
2204 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002205 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002206 return true;
2207
Jim Grosbach7815f562012-02-03 00:07:04 +00002208 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002209 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002210 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002211 if (!SrcTy->isSized() || !DstTy->isSized())
2212 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002213 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002214 return false;
2215 return true;
2216}
2217
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002218Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002219 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002220
Chandler Carruthba4c5172015-01-21 11:23:40 +00002221 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002222 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002223 };
2224 LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW);
2225 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002226 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002227 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002228 }
Meador Ingedf796f82012-10-13 16:45:24 +00002229
Craig Topperf40110f2014-04-25 05:29:35 +00002230 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002231}
2232
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002233static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002234 // Strip off at most one level of pointer casts, looking for an alloca. This
2235 // is good enough in practice and simpler than handling any number of casts.
2236 Value *Underlying = TrampMem->stripPointerCasts();
2237 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002238 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002239 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002240 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002241 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002242
Craig Topperf40110f2014-04-25 05:29:35 +00002243 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002244 for (User *U : TrampMem->users()) {
2245 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002246 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002247 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002248 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2249 if (InitTrampoline)
2250 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002251 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002252 InitTrampoline = II;
2253 continue;
2254 }
2255 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2256 // Allow any number of calls to adjust.trampoline.
2257 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002258 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002259 }
2260
2261 // No call to init.trampoline found.
2262 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002263 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002264
2265 // Check that the alloca is being used in the expected way.
2266 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002267 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002268
2269 return InitTrampoline;
2270}
2271
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002272static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002273 Value *TrampMem) {
2274 // Visit all the previous instructions in the basic block, and try to find a
2275 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002276 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2277 E = AdjustTramp->getParent()->begin();
2278 I != E;) {
2279 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00002280 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2281 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2282 II->getOperand(0) == TrampMem)
2283 return II;
2284 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00002285 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002286 }
Craig Topperf40110f2014-04-25 05:29:35 +00002287 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002288}
2289
2290// Given a call to llvm.adjust.trampoline, find and return the corresponding
2291// call to llvm.init.trampoline if the call to the trampoline can be optimized
2292// to a direct call to a function. Otherwise return NULL.
2293//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002294static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002295 Callee = Callee->stripPointerCasts();
2296 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2297 if (!AdjustTramp ||
2298 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002299 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002300
2301 Value *TrampMem = AdjustTramp->getOperand(0);
2302
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002303 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002304 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002305 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002306 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00002307 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002308}
2309
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002310/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002311Instruction *InstCombiner::visitCallSite(CallSite CS) {
Philip Reamesc25df112015-06-16 20:24:25 +00002312
Benjamin Kramer8bcc9712012-08-29 15:32:21 +00002313 if (isAllocLikeFn(CS.getInstruction(), TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002314 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002315
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002316 bool Changed = false;
2317
Philip Reamesc25df112015-06-16 20:24:25 +00002318 // Mark any parameters that are known to be non-null with the nonnull
2319 // attribute. This is helpful for inlining calls to functions with null
2320 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00002321 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00002322 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00002323
Philip Reamesc25df112015-06-16 20:24:25 +00002324 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00002325 if (V->getType()->isPointerTy() &&
2326 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Akira Hatanaka237916b2015-12-02 06:58:49 +00002327 isKnownNonNullAt(V, CS.getInstruction(), DT, TLI))
2328 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00002329 ArgNo++;
2330 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00002331
Philip Reamesc25df112015-06-16 20:24:25 +00002332 assert(ArgNo == CS.arg_size() && "sanity check");
2333
Akira Hatanaka237916b2015-12-02 06:58:49 +00002334 if (!Indices.empty()) {
2335 AttributeSet AS = CS.getAttributes();
2336 LLVMContext &Ctx = CS.getInstruction()->getContext();
2337 AS = AS.addAttribute(Ctx, Indices,
2338 Attribute::get(Ctx, Attribute::NonNull));
2339 CS.setAttributes(AS);
2340 Changed = true;
2341 }
2342
Chris Lattner73989652010-12-20 08:25:06 +00002343 // If the callee is a pointer to a function, attempt to move any casts to the
2344 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002345 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00002346 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00002347 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002348
Justin Lebar9d943972016-03-14 20:18:54 +00002349 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2350 // Remove the convergent attr on calls when the callee is not convergent.
2351 if (CS.isConvergent() && !CalleeF->isConvergent()) {
2352 DEBUG(dbgs() << "Removing convergent attr from instr "
2353 << CS.getInstruction() << "\n");
2354 CS.setNotConvergent();
2355 return CS.getInstruction();
2356 }
2357
Chris Lattner846a52e2010-02-01 18:11:34 +00002358 // If the call and callee calling conventions don't match, this call must
2359 // be unreachable, as the call is undefined.
2360 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2361 // Only do this for calls to a function with a body. A prototype may
2362 // not actually end up matching the implementation's calling conv for a
2363 // variety of reasons (e.g. it may be written in assembly).
2364 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002365 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002366 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00002367 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002368 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00002369 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002370 // This allows ValueHandlers and custom metadata to adjust itself.
2371 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002372 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00002373 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00002374 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00002375
Chris Lattner2cecedf2010-02-01 18:04:58 +00002376 // We cannot remove an invoke, because it would change the CFG, just
2377 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00002378 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00002379 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00002380 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002381 }
Justin Lebar9d943972016-03-14 20:18:54 +00002382 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002383
2384 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002385 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002386 // This allows ValueHandlers and custom metadata to adjust itself.
2387 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002388 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002389 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002390
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002391 if (isa<InvokeInst>(CS.getInstruction())) {
2392 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00002393 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002394 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002395
2396 // This instruction is not reachable, just remove it. We insert a store to
2397 // undef so that we know that this code is not reachable, despite the fact
2398 // that we can't modify the CFG here.
2399 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2400 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2401 CS.getInstruction());
2402
Sanjay Patel4b198802016-02-01 22:23:39 +00002403 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002404 }
2405
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002406 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00002407 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002408
Chris Lattner229907c2011-07-18 04:54:35 +00002409 PointerType *PTy = cast<PointerType>(Callee->getType());
2410 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002411 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00002412 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002413 // See if we can optimize any arguments passed through the varargs area of
2414 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002415 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002416 E = CS.arg_end(); I != E; ++I, ++ix) {
2417 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002418 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002419 *I = CI->getOperand(0);
2420 Changed = true;
2421 }
2422 }
2423 }
2424
2425 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2426 // Inline asm calls cannot throw - mark them 'nounwind'.
2427 CS.setDoesNotThrow();
2428 Changed = true;
2429 }
2430
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002431 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00002432 // this. None of these calls are seen as possibly dead so go ahead and
2433 // delete the instruction now.
2434 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002435 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00002436 // If we changed something return the result, etc. Otherwise let
2437 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00002438 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00002439 }
2440
Craig Topperf40110f2014-04-25 05:29:35 +00002441 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002442}
2443
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002444/// If the callee is a constexpr cast of a function, attempt to move the cast to
2445/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002446bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Chris Lattner73989652010-12-20 08:25:06 +00002447 Function *Callee =
2448 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00002449 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002450 return false;
David Majnemer4c0a6e92015-01-21 22:32:04 +00002451 // The prototype of thunks are a lie, don't try to directly call such
2452 // functions.
2453 if (Callee->hasFnAttribute("thunk"))
2454 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002455 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00002456 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002457
2458 // Okay, this is a cast from a function to a different type. Unless doing so
2459 // would cause a type conversion of one of our arguments, change this call to
2460 // be a direct call with arguments casted to the appropriate types.
2461 //
Chris Lattner229907c2011-07-18 04:54:35 +00002462 FunctionType *FT = Callee->getFunctionType();
2463 Type *OldRetTy = Caller->getType();
2464 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002465
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002466 // Check to see if we are changing the return type...
2467 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00002468
2469 if (NewRetTy->isStructTy())
2470 return false; // TODO: Handle multiple return values.
2471
David Majnemer9b6b8222015-01-06 08:41:31 +00002472 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002473 if (Callee->isDeclaration())
2474 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002475
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002476 if (!Caller->use_empty() &&
2477 // void -> non-void is handled specially
2478 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00002479 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002480 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002481
2482 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00002483 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00002484 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002485 return false; // Attribute not compatible with transformed value.
2486 }
2487
2488 // If the callsite is an invoke instruction, and the return value is used by
2489 // a PHI node in a successor, we cannot change the return type of the call
2490 // because there is no place to put the cast instruction (without breaking
2491 // the critical edge). Bail out in this case.
2492 if (!Caller->use_empty())
2493 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002494 for (User *U : II->users())
2495 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002496 if (PN->getParent() == II->getNormalDest() ||
2497 PN->getParent() == II->getUnwindDest())
2498 return false;
2499 }
2500
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002501 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002502 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2503
David Majnemer9b6b8222015-01-06 08:41:31 +00002504 // Prevent us turning:
2505 // declare void @takes_i32_inalloca(i32* inalloca)
2506 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2507 //
2508 // into:
2509 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00002510 //
2511 // Similarly, avoid folding away bitcasts of byval calls.
2512 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2513 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00002514 return false;
2515
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002516 CallSite::arg_iterator AI = CS.arg_begin();
2517 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002518 Type *ParamTy = FT->getParamType(i);
2519 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002520
David Majnemer9b6b8222015-01-06 08:41:31 +00002521 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002522 return false; // Cannot transform this parameter value.
2523
Bill Wendling49bc76c2013-01-23 06:14:59 +00002524 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00002525 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002526 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00002527
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002528 if (CS.isInAllocaArgument(i))
2529 return false; // Cannot transform to and from inalloca.
2530
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002531 // If the parameter is passed as a byval argument, then we have to have a
2532 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002533 if (ParamTy != ActTy &&
2534 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2535 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00002536 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002537 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002538 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00002539
Matt Arsenaultfa252722013-09-27 22:18:51 +00002540 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002541 if (DL.getTypeAllocSize(CurElTy) !=
2542 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002543 return false;
2544 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002545 }
2546
Chris Lattneradf38b32011-02-24 05:10:56 +00002547 if (Callee->isDeclaration()) {
2548 // Do not delete arguments unless we have a function body.
2549 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2550 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002551
Chris Lattneradf38b32011-02-24 05:10:56 +00002552 // If the callee is just a declaration, don't change the varargsness of the
2553 // call. We don't want to introduce a varargs call where one doesn't
2554 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00002555 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00002556 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2557 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002558
2559 // If both the callee and the cast type are varargs, we still have to make
2560 // sure the number of fixed parameters are the same or we have the same
2561 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00002562 if (FT->isVarArg() &&
2563 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2564 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002565 cast<FunctionType>(APTy->getElementType())->getNumParams())
2566 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00002567 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002568
Jim Grosbach0ab54182012-02-03 00:00:50 +00002569 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2570 !CallerPAL.isEmpty())
2571 // In this case we have more arguments than the new function type, but we
2572 // won't be dropping them. Check that these extra arguments have attributes
2573 // that are compatible with being a vararg call argument.
2574 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00002575 unsigned Index = CallerPAL.getSlotIndex(i - 1);
2576 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00002577 break;
Bill Wendling57625a42013-01-25 23:09:36 +00002578
Bill Wendlingd97b75d2012-12-19 08:57:40 +00002579 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00002580 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2581 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00002582 return false;
2583 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002584
Jim Grosbach7815f562012-02-03 00:07:04 +00002585
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002586 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00002587 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002588 std::vector<Value*> Args;
2589 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002590 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002591 attrVec.reserve(NumCommonArgs);
2592
2593 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002594 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002595
2596 // If the return value is not being used, the type may not be compatible
2597 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00002598 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002599
2600 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00002601 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002602 attrVec.push_back(AttributeSet::get(Caller->getContext(),
2603 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002604
2605 AI = CS.arg_begin();
2606 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002607 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00002608
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002609 if ((*AI)->getType() == ParamTy) {
2610 Args.push_back(*AI);
2611 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00002612 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002613 }
2614
2615 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002616 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002617 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002618 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2619 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002620 }
2621
2622 // If the function takes more arguments than the call was taking, add them
2623 // now.
2624 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2625 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2626
2627 // If we are removing arguments to the function, emit an obnoxious warning.
2628 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00002629 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2630 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002631 // Add all of the arguments in their promoted form to the arg list.
2632 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002633 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002634 if (PTy != (*AI)->getType()) {
2635 // Must promote to pass through va_arg area!
2636 Instruction::CastOps opcode =
2637 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002638 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002639 } else {
2640 Args.push_back(*AI);
2641 }
2642
2643 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002644 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002645 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002646 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
2647 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002648 }
2649 }
2650 }
2651
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002652 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00002653 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002654 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002655
2656 if (NewRetTy->isVoidTy())
2657 Caller->setName(""); // Void type should not have a name.
2658
Bill Wendlinge94d8432012-12-07 23:16:57 +00002659 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002660 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002661
Sanjoy Das76293462015-11-25 00:42:19 +00002662 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00002663 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00002664
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002665 Instruction *NC;
2666 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00002667 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
2668 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002669 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002670 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
2671 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
2672 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002673 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00002674 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002675 NC->takeName(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002676 if (CI->isTailCall())
2677 cast<CallInst>(NC)->setTailCall();
2678 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
2679 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
2680 }
2681
2682 // Insert a cast of the return type as necessary.
2683 Value *NV = NC;
2684 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
2685 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00002686 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00002687 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002688
2689 // If this is an invoke instruction, we should insert it after the first
2690 // non-phi, instruction in the normal successor block.
2691 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00002692 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002693 InsertNewInstBefore(NC, *I);
2694 } else {
Chris Lattner73989652010-12-20 08:25:06 +00002695 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002696 InsertNewInstBefore(NC, *Caller);
2697 }
2698 Worklist.AddUsersToWorkList(*Caller);
2699 } else {
2700 NV = UndefValue::get(Caller->getType());
2701 }
2702 }
2703
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002704 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002705 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00002706 else if (Caller->hasValueHandle()) {
2707 if (OldRetTy == NV->getType())
2708 ValueHandleBase::ValueIsRAUWd(Caller, NV);
2709 else
2710 // We cannot call ValueIsRAUWd with a different type, and the
2711 // actual tracked value will disappear.
2712 ValueHandleBase::ValueIsDeleted(Caller);
2713 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002714
Sanjay Patel4b198802016-02-01 22:23:39 +00002715 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002716 return true;
2717}
2718
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002719/// Turn a call to a function created by init_trampoline / adjust_trampoline
2720/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00002721Instruction *
2722InstCombiner::transformCallThroughTrampoline(CallSite CS,
2723 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002724 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00002725 PointerType *PTy = cast<PointerType>(Callee->getType());
2726 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00002727 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002728
2729 // If the call already has the 'nest' attribute somewhere then give up -
2730 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00002731 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00002732 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002733
Duncan Sandsa0984362011-09-06 13:37:06 +00002734 assert(Tramp &&
2735 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002736
Gabor Greif3e44ea12010-07-22 10:37:47 +00002737 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002738 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002739
Bill Wendlinge94d8432012-12-07 23:16:57 +00002740 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002741 if (!NestAttrs.isEmpty()) {
2742 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00002743 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00002744 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002745
2746 // Look for a parameter marked with the 'nest' attribute.
2747 for (FunctionType::param_iterator I = NestFTy->param_begin(),
2748 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00002749 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002750 // Record the parameter type and any other attributes.
2751 NestTy = *I;
2752 NestAttr = NestAttrs.getParamAttributes(NestIdx);
2753 break;
2754 }
2755
2756 if (NestTy) {
2757 Instruction *Caller = CS.getInstruction();
2758 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002759 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002760
Bill Wendling3575c8c2013-01-27 02:08:22 +00002761 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002762 NewAttrs.reserve(Attrs.getNumSlots() + 1);
2763
2764 // Insert the nest argument into the call argument list, which may
2765 // mean appending it. Likewise for attributes.
2766
2767 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002768 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002769 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2770 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002771
2772 {
2773 unsigned Idx = 1;
2774 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2775 do {
2776 if (Idx == NestIdx) {
2777 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00002778 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002779 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00002780 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002781 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002782 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2783 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002784 }
2785
2786 if (I == E)
2787 break;
2788
2789 // Add the original argument and attributes.
2790 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00002791 AttributeSet Attr = Attrs.getParamAttributes(Idx);
2792 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00002793 AttrBuilder B(Attr, Idx);
2794 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2795 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00002796 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002797
Richard Trieu7a083812016-02-18 22:09:30 +00002798 ++Idx;
2799 ++I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002800 } while (1);
2801 }
2802
2803 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00002804 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002805 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
2806 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002807
2808 // The trampoline may have been bitcast to a bogus type (FTy).
2809 // Handle this by synthesizing a new function type, equal to FTy
2810 // with the chain parameter inserted.
2811
Jay Foadb804a2b2011-07-12 14:06:48 +00002812 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002813 NewTypes.reserve(FTy->getNumParams()+1);
2814
2815 // Insert the chain's type into the list of parameter types, which may
2816 // mean appending it.
2817 {
2818 unsigned Idx = 1;
2819 FunctionType::param_iterator I = FTy->param_begin(),
2820 E = FTy->param_end();
2821
2822 do {
2823 if (Idx == NestIdx)
2824 // Add the chain's type.
2825 NewTypes.push_back(NestTy);
2826
2827 if (I == E)
2828 break;
2829
2830 // Add the original type.
2831 NewTypes.push_back(*I);
2832
Richard Trieu7a083812016-02-18 22:09:30 +00002833 ++Idx;
2834 ++I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002835 } while (1);
2836 }
2837
2838 // Replace the trampoline call with a direct call. Let the generic
2839 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00002840 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002841 FTy->isVarArg());
2842 Constant *NewCallee =
2843 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00002844 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002845 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00002846 const AttributeSet &NewPAL =
2847 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002848
David Majnemer231a68c2016-04-29 08:07:20 +00002849 SmallVector<OperandBundleDef, 1> OpBundles;
2850 CS.getOperandBundlesAsDefs(OpBundles);
2851
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002852 Instruction *NewCaller;
2853 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
2854 NewCaller = InvokeInst::Create(NewCallee,
2855 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00002856 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002857 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
2858 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
2859 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00002860 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002861 if (cast<CallInst>(Caller)->isTailCall())
2862 cast<CallInst>(NewCaller)->setTailCall();
2863 cast<CallInst>(NewCaller)->
2864 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
2865 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
2866 }
Eli Friedman49346012011-05-18 19:57:14 +00002867
2868 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002869 }
2870 }
2871
2872 // Replace the trampoline call with a direct call. Since there is no 'nest'
2873 // parameter, there is no need to adjust the argument list. Let the generic
2874 // code sort out any function type mismatches.
2875 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00002876 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002877 ConstantExpr::getBitCast(NestF, PTy);
2878 CS.setCalledFunction(NewCallee);
2879 return CS.getInstruction();
2880}