blob: f00363e029cb5fd77de3a01de20c111885f314a0 [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"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Meador Ingee3f2b262012-11-30 04:05:06 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Twine.h"
David Majnemer15032582015-05-22 03:56:46 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000025#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/IR/Constant.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Intrinsics.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000041#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000042#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
44#include "llvm/IR/ValueHandle.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/MathExtras.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000048#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include <algorithm>
51#include <cassert>
52#include <cstdint>
53#include <cstring>
54#include <vector>
55
Chris Lattner7a9e47a2010-01-05 07:32:13 +000056using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000057using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000058
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "instcombine"
60
Meador Ingee3f2b262012-11-30 04:05:06 +000061STATISTIC(NumSimplified, "Number of library calls simplified");
62
Sanjay Patelcd4377c2016-01-20 22:24:38 +000063/// Return the specified type promoted as it would be to pass though a va_arg
64/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000065static Type *getPromotedType(Type *Ty) {
66 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000067 if (ITy->getBitWidth() < 32)
68 return Type::getInt32Ty(Ty->getContext());
69 }
70 return Ty;
71}
72
Sanjay Patelcd4377c2016-01-20 22:24:38 +000073/// Given an aggregate type which ultimately holds a single scalar element,
74/// like {{{type}}} or [1 x type], return type.
Dan Gohmand0080c42012-09-13 18:19:06 +000075static Type *reduceToSingleValueType(Type *T) {
76 while (!T->isSingleValueType()) {
77 if (StructType *STy = dyn_cast<StructType>(T)) {
78 if (STy->getNumElements() == 1)
79 T = STy->getElementType(0);
80 else
81 break;
82 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
83 if (ATy->getNumElements() == 1)
84 T = ATy->getElementType();
85 else
86 break;
87 } else
88 break;
89 }
90
91 return T;
92}
Chris Lattner7a9e47a2010-01-05 07:32:13 +000093
Sanjay Patel368ac5d2016-02-21 17:29:33 +000094/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000095/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000096static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
97 SmallVector<Constant *, 32> BoolVec;
98 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
99 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
100 Constant *Elt = V->getElementAsConstant(I);
101 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
102 "Unexpected constant data vector element type");
103 bool Sign = V->getElementType()->isIntegerTy()
104 ? cast<ConstantInt>(Elt)->isNegative()
105 : cast<ConstantFP>(Elt)->isNegative();
106 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
107 }
108 return ConstantVector::get(BoolVec);
109}
110
Pete Cooper67cf9a72015-11-19 05:56:52 +0000111Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Justin Bogner99798402016-08-05 01:06:44 +0000112 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
113 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000114 unsigned MinAlign = std::min(DstAlign, SrcAlign);
115 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000116
Pete Cooper67cf9a72015-11-19 05:56:52 +0000117 if (CopyAlign < MinAlign) {
118 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000119 return MI;
120 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000121
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000122 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
123 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000124 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000125 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000126
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000127 // Source and destination pointer types are always "i8*" for intrinsic. See
128 // if the size is something we can handle with a single primitive load/store.
129 // A single load+store correctly handles overlapping memory in the memmove
130 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000131 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000132 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000133
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000134 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000136
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000137 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000138 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000139 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000140 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000141 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000142
Chris Lattner229907c2011-07-18 04:54:35 +0000143 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000144 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
145 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000146
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000147 // Memcpy forces the use of i8* for the source and destination. That means
148 // that if you're using memcpy to move one double around, you'll get a cast
149 // from double* to i8*. We'd much rather use a double load+store rather than
150 // an i64 load+store, here because this improves the odds that the source or
151 // dest address will be promotable. See if we can find a better type than the
152 // integer datatype.
Gabor Greif589a0b92010-06-24 12:58:35 +0000153 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Craig Topperf40110f2014-04-25 05:29:35 +0000154 MDNode *CopyMD = nullptr;
Gabor Greif589a0b92010-06-24 12:58:35 +0000155 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000156 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000157 ->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000158 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000159 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
160 // down through these levels if so.
Dan Gohmand0080c42012-09-13 18:19:06 +0000161 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach7815f562012-02-03 00:07:04 +0000162
Mon P Wangc576ee92010-04-04 03:10:48 +0000163 if (SrcETy->isSingleValueType()) {
164 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
165 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohman3f553c22012-09-13 21:51:01 +0000166
167 // If the memcpy has metadata describing the members, see if we can
168 // get the TBAA tag describing our copy.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000169 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000170 if (M->getNumOperands() == 3 && M->getOperand(0) &&
171 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
172 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000173 M->getOperand(1) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000174 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
175 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
176 Size &&
177 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
Dan Gohman3f553c22012-09-13 21:51:01 +0000178 CopyMD = cast<MDNode>(M->getOperand(2));
179 }
Mon P Wangc576ee92010-04-04 03:10:48 +0000180 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000181 }
182 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000183
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000184 // If the memcpy/memmove provides better alignment info than we can
185 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000186 SrcAlign = std::max(SrcAlign, CopyAlign);
187 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000188
Gabor Greif5f3e6562010-06-25 07:57:14 +0000189 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
190 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000191 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
192 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000193 if (CopyMD)
194 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Eli Friedman49346012011-05-18 19:57:14 +0000195 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
196 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000197 if (CopyMD)
198 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000199
200 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000201 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000202 return MI;
203}
204
205Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Justin Bogner99798402016-08-05 01:06:44 +0000206 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000207 if (MI->getAlignment() < Alignment) {
208 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
209 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000210 return MI;
211 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000212
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000213 // Extract the length and alignment and fill if they are constant.
214 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
215 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000216 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000217 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000218 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000219 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000220 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000221
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000222 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
223 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000224 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000225
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000226 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000227 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
228 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
229 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000230
231 // Alignment 0 is identity for alignment 1 for memset, but not store.
232 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000233
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000234 // Extract the fill value and store.
235 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000236 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
237 MI->isVolatile());
238 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000239
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000240 // Set the size of the copy to 0, it will be deleted on the next iteration.
241 MI->setLength(Constant::getNullValue(LenC->getType()));
242 return MI;
243 }
244
Simon Pilgrim18617d12015-08-05 08:18:00 +0000245 return nullptr;
246}
247
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000248static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000249 InstCombiner::BuilderTy &Builder) {
250 bool LogicalShift = false;
251 bool ShiftLeft = false;
252
253 switch (II.getIntrinsicID()) {
254 default:
255 return nullptr;
256 case Intrinsic::x86_sse2_psra_d:
257 case Intrinsic::x86_sse2_psra_w:
258 case Intrinsic::x86_sse2_psrai_d:
259 case Intrinsic::x86_sse2_psrai_w:
260 case Intrinsic::x86_avx2_psra_d:
261 case Intrinsic::x86_avx2_psra_w:
262 case Intrinsic::x86_avx2_psrai_d:
263 case Intrinsic::x86_avx2_psrai_w:
264 LogicalShift = false; ShiftLeft = false;
265 break;
266 case Intrinsic::x86_sse2_psrl_d:
267 case Intrinsic::x86_sse2_psrl_q:
268 case Intrinsic::x86_sse2_psrl_w:
269 case Intrinsic::x86_sse2_psrli_d:
270 case Intrinsic::x86_sse2_psrli_q:
271 case Intrinsic::x86_sse2_psrli_w:
272 case Intrinsic::x86_avx2_psrl_d:
273 case Intrinsic::x86_avx2_psrl_q:
274 case Intrinsic::x86_avx2_psrl_w:
275 case Intrinsic::x86_avx2_psrli_d:
276 case Intrinsic::x86_avx2_psrli_q:
277 case Intrinsic::x86_avx2_psrli_w:
278 LogicalShift = true; ShiftLeft = false;
279 break;
280 case Intrinsic::x86_sse2_psll_d:
281 case Intrinsic::x86_sse2_psll_q:
282 case Intrinsic::x86_sse2_psll_w:
283 case Intrinsic::x86_sse2_pslli_d:
284 case Intrinsic::x86_sse2_pslli_q:
285 case Intrinsic::x86_sse2_pslli_w:
286 case Intrinsic::x86_avx2_psll_d:
287 case Intrinsic::x86_avx2_psll_q:
288 case Intrinsic::x86_avx2_psll_w:
289 case Intrinsic::x86_avx2_pslli_d:
290 case Intrinsic::x86_avx2_pslli_q:
291 case Intrinsic::x86_avx2_pslli_w:
292 LogicalShift = true; ShiftLeft = true;
293 break;
294 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000295 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
296
Simon Pilgrim3815c162015-08-07 18:22:50 +0000297 // Simplify if count is constant.
298 auto Arg1 = II.getArgOperand(1);
299 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
300 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
301 auto CInt = dyn_cast<ConstantInt>(Arg1);
302 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000303 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000304
305 APInt Count(64, 0);
306 if (CDV) {
307 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
308 // operand to compute the shift amount.
309 auto VT = cast<VectorType>(CDV->getType());
310 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
311 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
312 unsigned NumSubElts = 64 / BitWidth;
313
314 // Concatenate the sub-elements to create the 64-bit value.
315 for (unsigned i = 0; i != NumSubElts; ++i) {
316 unsigned SubEltIdx = (NumSubElts - 1) - i;
317 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
318 Count = Count.shl(BitWidth);
319 Count |= SubElt->getValue().zextOrTrunc(64);
320 }
321 }
322 else if (CInt)
323 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000324
325 auto Vec = II.getArgOperand(0);
326 auto VT = cast<VectorType>(Vec->getType());
327 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000328 unsigned VWidth = VT->getNumElements();
329 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
330
331 // If shift-by-zero then just return the original value.
332 if (Count == 0)
333 return Vec;
334
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000335 // Handle cases when Shift >= BitWidth.
336 if (Count.uge(BitWidth)) {
337 // If LogicalShift - just return zero.
338 if (LogicalShift)
339 return ConstantAggregateZero::get(VT);
340
341 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
342 Count = APInt(64, BitWidth - 1);
343 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000344
Simon Pilgrim18617d12015-08-05 08:18:00 +0000345 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000346 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
347 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000348
349 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000350 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000351
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000352 if (LogicalShift)
353 return Builder.CreateLShr(Vec, ShiftVec);
354
355 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000356}
357
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000358// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
359// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
360// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
361static Value *simplifyX86varShift(const IntrinsicInst &II,
362 InstCombiner::BuilderTy &Builder) {
363 bool LogicalShift = false;
364 bool ShiftLeft = false;
365
366 switch (II.getIntrinsicID()) {
367 default:
368 return nullptr;
369 case Intrinsic::x86_avx2_psrav_d:
370 case Intrinsic::x86_avx2_psrav_d_256:
371 LogicalShift = false;
372 ShiftLeft = false;
373 break;
374 case Intrinsic::x86_avx2_psrlv_d:
375 case Intrinsic::x86_avx2_psrlv_d_256:
376 case Intrinsic::x86_avx2_psrlv_q:
377 case Intrinsic::x86_avx2_psrlv_q_256:
378 LogicalShift = true;
379 ShiftLeft = false;
380 break;
381 case Intrinsic::x86_avx2_psllv_d:
382 case Intrinsic::x86_avx2_psllv_d_256:
383 case Intrinsic::x86_avx2_psllv_q:
384 case Intrinsic::x86_avx2_psllv_q_256:
385 LogicalShift = true;
386 ShiftLeft = true;
387 break;
388 }
389 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
390
391 // Simplify if all shift amounts are constant/undef.
392 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
393 if (!CShift)
394 return nullptr;
395
396 auto Vec = II.getArgOperand(0);
397 auto VT = cast<VectorType>(II.getType());
398 auto SVT = VT->getVectorElementType();
399 int NumElts = VT->getNumElements();
400 int BitWidth = SVT->getIntegerBitWidth();
401
402 // Collect each element's shift amount.
403 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
404 bool AnyOutOfRange = false;
405 SmallVector<int, 8> ShiftAmts;
406 for (int I = 0; I < NumElts; ++I) {
407 auto *CElt = CShift->getAggregateElement(I);
408 if (CElt && isa<UndefValue>(CElt)) {
409 ShiftAmts.push_back(-1);
410 continue;
411 }
412
413 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
414 if (!COp)
415 return nullptr;
416
417 // Handle out of range shifts.
418 // If LogicalShift - set to BitWidth (special case).
419 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
420 APInt ShiftVal = COp->getValue();
421 if (ShiftVal.uge(BitWidth)) {
422 AnyOutOfRange = LogicalShift;
423 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
424 continue;
425 }
426
427 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
428 }
429
430 // If all elements out of range or UNDEF, return vector of zeros/undefs.
431 // ArithmeticShift should only hit this if they are all UNDEF.
432 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000433 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000434 SmallVector<Constant *, 8> ConstantVec;
435 for (int Idx : ShiftAmts) {
436 if (Idx < 0) {
437 ConstantVec.push_back(UndefValue::get(SVT));
438 } else {
439 assert(LogicalShift && "Logical shift expected");
440 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
441 }
442 }
443 return ConstantVector::get(ConstantVec);
444 }
445
446 // We can't handle only some out of range values with generic logical shifts.
447 if (AnyOutOfRange)
448 return nullptr;
449
450 // Build the shift amount constant vector.
451 SmallVector<Constant *, 8> ShiftVecAmts;
452 for (int Idx : ShiftAmts) {
453 if (Idx < 0)
454 ShiftVecAmts.push_back(UndefValue::get(SVT));
455 else
456 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
457 }
458 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
459
460 if (ShiftLeft)
461 return Builder.CreateShl(Vec, ShiftVec);
462
463 if (LogicalShift)
464 return Builder.CreateLShr(Vec, ShiftVec);
465
466 return Builder.CreateAShr(Vec, ShiftVec);
467}
468
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000469static Value *simplifyX86movmsk(const IntrinsicInst &II,
470 InstCombiner::BuilderTy &Builder) {
471 Value *Arg = II.getArgOperand(0);
472 Type *ResTy = II.getType();
473 Type *ArgTy = Arg->getType();
474
475 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
476 if (isa<UndefValue>(Arg))
477 return Constant::getNullValue(ResTy);
478
479 // We can't easily peek through x86_mmx types.
480 if (!ArgTy->isVectorTy())
481 return nullptr;
482
483 auto *C = dyn_cast<Constant>(Arg);
484 if (!C)
485 return nullptr;
486
487 // Extract signbits of the vector input and pack into integer result.
488 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
489 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
490 auto *COp = C->getAggregateElement(I);
491 if (!COp)
492 return nullptr;
493 if (isa<UndefValue>(COp))
494 continue;
495
496 auto *CInt = dyn_cast<ConstantInt>(COp);
497 auto *CFp = dyn_cast<ConstantFP>(COp);
498 if (!CInt && !CFp)
499 return nullptr;
500
501 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
502 Result.setBit(I);
503 }
504
505 return Constant::getIntegerValue(ResTy, Result);
506}
507
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000508static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000509 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000510 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
511 if (!CInt)
512 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000513
Sanjay Patel03c03f52016-01-28 00:03:16 +0000514 VectorType *VecTy = cast<VectorType>(II.getType());
515 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000516
Sanjay Patel03c03f52016-01-28 00:03:16 +0000517 // The immediate permute control byte looks like this:
518 // [3:0] - zero mask for each 32-bit lane
519 // [5:4] - select one 32-bit destination lane
520 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000521
Sanjay Patel03c03f52016-01-28 00:03:16 +0000522 uint8_t Imm = CInt->getZExtValue();
523 uint8_t ZMask = Imm & 0xf;
524 uint8_t DestLane = (Imm >> 4) & 0x3;
525 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000526
Sanjay Patel03c03f52016-01-28 00:03:16 +0000527 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000528
Sanjay Patel03c03f52016-01-28 00:03:16 +0000529 // If all zero mask bits are set, this was just a weird way to
530 // generate a zero vector.
531 if (ZMask == 0xf)
532 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000533
Sanjay Patel03c03f52016-01-28 00:03:16 +0000534 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000535 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000536
Sanjay Patel03c03f52016-01-28 00:03:16 +0000537 // We may replace the second operand with the zero vector.
538 Value *V1 = II.getArgOperand(1);
539
540 if (ZMask) {
541 // If the zero mask is being used with a single input or the zero mask
542 // overrides the destination lane, this is a shuffle with the zero vector.
543 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
544 (ZMask & (1 << DestLane))) {
545 V1 = ZeroVector;
546 // We may still move 32-bits of the first source vector from one lane
547 // to another.
548 ShuffleMask[DestLane] = SourceLane;
549 // The zero mask may override the previous insert operation.
550 for (unsigned i = 0; i < 4; ++i)
551 if ((ZMask >> i) & 0x1)
552 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000553 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000554 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
555 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000556 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000557 } else {
558 // Replace the selected destination lane with the selected source lane.
559 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000560 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000561
562 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000563}
564
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000565/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
566/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000567static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000568 ConstantInt *CILength, ConstantInt *CIIndex,
569 InstCombiner::BuilderTy &Builder) {
570 auto LowConstantHighUndef = [&](uint64_t Val) {
571 Type *IntTy64 = Type::getInt64Ty(II.getContext());
572 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
573 UndefValue::get(IntTy64)};
574 return ConstantVector::get(Args);
575 };
576
577 // See if we're dealing with constant values.
578 Constant *C0 = dyn_cast<Constant>(Op0);
579 ConstantInt *CI0 =
580 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
581 : nullptr;
582
583 // Attempt to constant fold.
584 if (CILength && CIIndex) {
585 // From AMD documentation: "The bit index and field length are each six
586 // bits in length other bits of the field are ignored."
587 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
588 APInt APLength = CILength->getValue().zextOrTrunc(6);
589
590 unsigned Index = APIndex.getZExtValue();
591
592 // From AMD documentation: "a value of zero in the field length is
593 // defined as length of 64".
594 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
595
596 // From AMD documentation: "If the sum of the bit index + length field
597 // is greater than 64, the results are undefined".
598 unsigned End = Index + Length;
599
600 // Note that both field index and field length are 8-bit quantities.
601 // Since variables 'Index' and 'Length' are unsigned values
602 // obtained from zero-extending field index and field length
603 // respectively, their sum should never wrap around.
604 if (End > 64)
605 return UndefValue::get(II.getType());
606
607 // If we are inserting whole bytes, we can convert this to a shuffle.
608 // Lowering can recognize EXTRQI shuffle masks.
609 if ((Length % 8) == 0 && (Index % 8) == 0) {
610 // Convert bit indices to byte indices.
611 Length /= 8;
612 Index /= 8;
613
614 Type *IntTy8 = Type::getInt8Ty(II.getContext());
615 Type *IntTy32 = Type::getInt32Ty(II.getContext());
616 VectorType *ShufTy = VectorType::get(IntTy8, 16);
617
618 SmallVector<Constant *, 16> ShuffleMask;
619 for (int i = 0; i != (int)Length; ++i)
620 ShuffleMask.push_back(
621 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
622 for (int i = Length; i != 8; ++i)
623 ShuffleMask.push_back(
624 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
625 for (int i = 8; i != 16; ++i)
626 ShuffleMask.push_back(UndefValue::get(IntTy32));
627
628 Value *SV = Builder.CreateShuffleVector(
629 Builder.CreateBitCast(Op0, ShufTy),
630 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
631 return Builder.CreateBitCast(SV, II.getType());
632 }
633
634 // Constant Fold - shift Index'th bit to lowest position and mask off
635 // Length bits.
636 if (CI0) {
637 APInt Elt = CI0->getValue();
638 Elt = Elt.lshr(Index).zextOrTrunc(Length);
639 return LowConstantHighUndef(Elt.getZExtValue());
640 }
641
642 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
643 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
644 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000645 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000646 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
647 return Builder.CreateCall(F, Args);
648 }
649 }
650
651 // Constant Fold - extraction from zero is always {zero, undef}.
652 if (CI0 && CI0->equalsInt(0))
653 return LowConstantHighUndef(0);
654
655 return nullptr;
656}
657
658/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
659/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000660static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000661 APInt APLength, APInt APIndex,
662 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000663 // From AMD documentation: "The bit index and field length are each six bits
664 // in length other bits of the field are ignored."
665 APIndex = APIndex.zextOrTrunc(6);
666 APLength = APLength.zextOrTrunc(6);
667
668 // Attempt to constant fold.
669 unsigned Index = APIndex.getZExtValue();
670
671 // From AMD documentation: "a value of zero in the field length is
672 // defined as length of 64".
673 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
674
675 // From AMD documentation: "If the sum of the bit index + length field
676 // is greater than 64, the results are undefined".
677 unsigned End = Index + Length;
678
679 // Note that both field index and field length are 8-bit quantities.
680 // Since variables 'Index' and 'Length' are unsigned values
681 // obtained from zero-extending field index and field length
682 // respectively, their sum should never wrap around.
683 if (End > 64)
684 return UndefValue::get(II.getType());
685
686 // If we are inserting whole bytes, we can convert this to a shuffle.
687 // Lowering can recognize INSERTQI shuffle masks.
688 if ((Length % 8) == 0 && (Index % 8) == 0) {
689 // Convert bit indices to byte indices.
690 Length /= 8;
691 Index /= 8;
692
693 Type *IntTy8 = Type::getInt8Ty(II.getContext());
694 Type *IntTy32 = Type::getInt32Ty(II.getContext());
695 VectorType *ShufTy = VectorType::get(IntTy8, 16);
696
697 SmallVector<Constant *, 16> ShuffleMask;
698 for (int i = 0; i != (int)Index; ++i)
699 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
700 for (int i = 0; i != (int)Length; ++i)
701 ShuffleMask.push_back(
702 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
703 for (int i = Index + Length; i != 8; ++i)
704 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
705 for (int i = 8; i != 16; ++i)
706 ShuffleMask.push_back(UndefValue::get(IntTy32));
707
708 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
709 Builder.CreateBitCast(Op1, ShufTy),
710 ConstantVector::get(ShuffleMask));
711 return Builder.CreateBitCast(SV, II.getType());
712 }
713
714 // See if we're dealing with constant values.
715 Constant *C0 = dyn_cast<Constant>(Op0);
716 Constant *C1 = dyn_cast<Constant>(Op1);
717 ConstantInt *CI00 =
718 C0 ? dyn_cast<ConstantInt>(C0->getAggregateElement((unsigned)0))
719 : nullptr;
720 ConstantInt *CI10 =
721 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
722 : nullptr;
723
724 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
725 if (CI00 && CI10) {
726 APInt V00 = CI00->getValue();
727 APInt V10 = CI10->getValue();
728 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
729 V00 = V00 & ~Mask;
730 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
731 APInt Val = V00 | V10;
732 Type *IntTy64 = Type::getInt64Ty(II.getContext());
733 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
734 UndefValue::get(IntTy64)};
735 return ConstantVector::get(Args);
736 }
737
738 // If we were an INSERTQ call, we'll save demanded elements if we convert to
739 // INSERTQI.
740 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
741 Type *IntTy8 = Type::getInt8Ty(II.getContext());
742 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
743 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
744
745 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000746 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000747 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
748 return Builder.CreateCall(F, Args);
749 }
750
751 return nullptr;
752}
753
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000754/// Attempt to convert pshufb* to shufflevector if the mask is constant.
755static Value *simplifyX86pshufb(const IntrinsicInst &II,
756 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000757 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
758 if (!V)
759 return nullptr;
760
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000761 auto *VecTy = cast<VectorType>(II.getType());
762 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
763 unsigned NumElts = VecTy->getNumElements();
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000764 assert((NumElts == 16 || NumElts == 32) &&
765 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000766
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000767 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000768 Constant *Indexes[32] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000769
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000770 // Each byte in the shuffle control mask forms an index to permute the
771 // corresponding byte in the destination operand.
772 for (unsigned I = 0; I < NumElts; ++I) {
773 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000774 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000775 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000776
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000777 if (isa<UndefValue>(COp)) {
778 Indexes[I] = UndefValue::get(MaskEltTy);
779 continue;
780 }
781
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000782 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
783
784 // If the most significant bit (bit[7]) of each byte of the shuffle
785 // control mask is set, then zero is written in the result byte.
786 // The zero vector is in the right-hand side of the resulting
787 // shufflevector.
788
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000789 // The value of each index for the high 128-bit lane is the least
790 // significant 4 bits of the respective shuffle control byte.
791 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
792 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000793 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000794
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000795 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000796 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000797 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000798 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
799}
800
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000801/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
802static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
803 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000804 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
805 if (!V)
806 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000807
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000808 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
809 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
810 assert(NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000811
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000812 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000813 Constant *Indexes[8] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000814
815 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000816 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000817 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000818 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000819 return nullptr;
820
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000821 if (isa<UndefValue>(COp)) {
822 Indexes[I] = UndefValue::get(MaskEltTy);
823 continue;
824 }
825
826 APInt Index = cast<ConstantInt>(COp)->getValue();
827 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000828
829 // The PD variants uses bit 1 to select per-lane element index, so
830 // shift down to convert to generic shuffle mask index.
831 if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
832 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000833 Index = Index.lshr(1);
834
835 // The _256 variants are a bit trickier since the mask bits always index
836 // into the corresponding 128 half. In order to convert to a generic
837 // shuffle, we have to make that explicit.
838 if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
839 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) &&
840 ((NumElts / 2) <= I)) {
841 Index += APInt(32, NumElts / 2);
842 }
843
844 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000845 }
846
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000847 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000848 auto V1 = II.getArgOperand(0);
849 auto V2 = UndefValue::get(V1->getType());
850 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
851}
852
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000853/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
854static Value *simplifyX86vpermv(const IntrinsicInst &II,
855 InstCombiner::BuilderTy &Builder) {
856 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
857 if (!V)
858 return nullptr;
859
Simon Pilgrimca140b12016-05-01 20:43:02 +0000860 auto *VecTy = cast<VectorType>(II.getType());
861 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000862 unsigned Size = VecTy->getNumElements();
863 assert(Size == 8 && "Unexpected shuffle mask size");
864
Simon Pilgrimca140b12016-05-01 20:43:02 +0000865 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000866 Constant *Indexes[8] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000867
868 for (unsigned I = 0; I < Size; ++I) {
869 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +0000870 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000871 return nullptr;
872
Simon Pilgrimca140b12016-05-01 20:43:02 +0000873 if (isa<UndefValue>(COp)) {
874 Indexes[I] = UndefValue::get(MaskEltTy);
875 continue;
876 }
877
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000878 APInt Index = cast<ConstantInt>(COp)->getValue();
Simon Pilgrimca140b12016-05-01 20:43:02 +0000879 Index = Index.zextOrTrunc(32).getLoBits(3);
880 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000881 }
882
Simon Pilgrimca140b12016-05-01 20:43:02 +0000883 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000884 auto V1 = II.getArgOperand(0);
885 auto V2 = UndefValue::get(VecTy);
886 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
887}
888
Sanjay Patelccf5f242015-03-20 21:47:56 +0000889/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
890/// source vectors, unless a zero bit is set. If a zero bit is set,
891/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000892static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000893 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000894 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
895 if (!CInt)
896 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000897
Sanjay Patel03c03f52016-01-28 00:03:16 +0000898 VectorType *VecTy = cast<VectorType>(II.getType());
899 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000900
Sanjay Patel03c03f52016-01-28 00:03:16 +0000901 // The immediate permute control byte looks like this:
902 // [1:0] - select 128 bits from sources for low half of destination
903 // [2] - ignore
904 // [3] - zero low half of destination
905 // [5:4] - select 128 bits from sources for high half of destination
906 // [6] - ignore
907 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000908
Sanjay Patel03c03f52016-01-28 00:03:16 +0000909 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000910
Sanjay Patel03c03f52016-01-28 00:03:16 +0000911 bool LowHalfZero = Imm & 0x08;
912 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000913
Sanjay Patel03c03f52016-01-28 00:03:16 +0000914 // If both zero mask bits are set, this was just a weird way to
915 // generate a zero vector.
916 if (LowHalfZero && HighHalfZero)
917 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000918
Sanjay Patel03c03f52016-01-28 00:03:16 +0000919 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
920 unsigned NumElts = VecTy->getNumElements();
921 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +0000922 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000923
Sanjay Patel03c03f52016-01-28 00:03:16 +0000924 // The high bit of the selection field chooses the 1st or 2nd operand.
925 bool LowInputSelect = Imm & 0x02;
926 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000927
Sanjay Patel03c03f52016-01-28 00:03:16 +0000928 // The low bit of the selection field chooses the low or high half
929 // of the selected operand.
930 bool LowHalfSelect = Imm & 0x01;
931 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000932
Sanjay Patel03c03f52016-01-28 00:03:16 +0000933 // Determine which operand(s) are actually in use for this instruction.
934 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
935 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000936
Sanjay Patel03c03f52016-01-28 00:03:16 +0000937 // If needed, replace operands based on zero mask.
938 V0 = LowHalfZero ? ZeroVector : V0;
939 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000940
Sanjay Patel03c03f52016-01-28 00:03:16 +0000941 // Permute low half of result.
942 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
943 for (unsigned i = 0; i < HalfSize; ++i)
944 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000945
Sanjay Patel03c03f52016-01-28 00:03:16 +0000946 // Permute high half of result.
947 StartIndex = HighHalfSelect ? HalfSize : 0;
948 StartIndex += NumElts;
949 for (unsigned i = 0; i < HalfSize; ++i)
950 ShuffleMask[i + HalfSize] = StartIndex + i;
951
952 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +0000953}
954
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000955/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000956static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000957 InstCombiner::BuilderTy &Builder,
958 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000959 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
960 uint64_t Imm = CInt->getZExtValue() & 0x7;
961 VectorType *VecTy = cast<VectorType>(II.getType());
962 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
963
964 switch (Imm) {
965 case 0x0:
966 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
967 break;
968 case 0x1:
969 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
970 break;
971 case 0x2:
972 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
973 break;
974 case 0x3:
975 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
976 break;
977 case 0x4:
978 Pred = ICmpInst::ICMP_EQ; break;
979 case 0x5:
980 Pred = ICmpInst::ICMP_NE; break;
981 case 0x6:
982 return ConstantInt::getSigned(VecTy, 0); // FALSE
983 case 0x7:
984 return ConstantInt::getSigned(VecTy, -1); // TRUE
985 }
986
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000987 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
988 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000989 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
990 }
991 return nullptr;
992}
993
Sanjay Patel0069f562016-01-31 16:35:23 +0000994static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
995 Value *Arg0 = II.getArgOperand(0);
996 Value *Arg1 = II.getArgOperand(1);
997
998 // fmin(x, x) -> x
999 if (Arg0 == Arg1)
1000 return Arg0;
1001
1002 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1003
1004 // fmin(x, nan) -> x
1005 if (C1 && C1->isNaN())
1006 return Arg0;
1007
1008 // This is the value because if undef were NaN, we would return the other
1009 // value and cannot return a NaN unless both operands are.
1010 //
1011 // fmin(undef, x) -> x
1012 if (isa<UndefValue>(Arg0))
1013 return Arg1;
1014
1015 // fmin(x, undef) -> x
1016 if (isa<UndefValue>(Arg1))
1017 return Arg0;
1018
1019 Value *X = nullptr;
1020 Value *Y = nullptr;
1021 if (II.getIntrinsicID() == Intrinsic::minnum) {
1022 // fmin(x, fmin(x, y)) -> fmin(x, y)
1023 // fmin(y, fmin(x, y)) -> fmin(x, y)
1024 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1025 if (Arg0 == X || Arg0 == Y)
1026 return Arg1;
1027 }
1028
1029 // fmin(fmin(x, y), x) -> fmin(x, y)
1030 // fmin(fmin(x, y), y) -> fmin(x, y)
1031 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1032 if (Arg1 == X || Arg1 == Y)
1033 return Arg0;
1034 }
1035
1036 // TODO: fmin(nnan x, inf) -> x
1037 // TODO: fmin(nnan ninf x, flt_max) -> x
1038 if (C1 && C1->isInfinity()) {
1039 // fmin(x, -inf) -> -inf
1040 if (C1->isNegative())
1041 return Arg1;
1042 }
1043 } else {
1044 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1045 // fmax(x, fmax(x, y)) -> fmax(x, y)
1046 // fmax(y, fmax(x, y)) -> fmax(x, y)
1047 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1048 if (Arg0 == X || Arg0 == Y)
1049 return Arg1;
1050 }
1051
1052 // fmax(fmax(x, y), x) -> fmax(x, y)
1053 // fmax(fmax(x, y), y) -> fmax(x, y)
1054 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1055 if (Arg1 == X || Arg1 == Y)
1056 return Arg0;
1057 }
1058
1059 // TODO: fmax(nnan x, -inf) -> x
1060 // TODO: fmax(nnan ninf x, -flt_max) -> x
1061 if (C1 && C1->isInfinity()) {
1062 // fmax(x, inf) -> inf
1063 if (!C1->isNegative())
1064 return Arg1;
1065 }
1066 }
1067 return nullptr;
1068}
1069
David Majnemer666aa942016-07-14 06:58:42 +00001070static bool maskIsAllOneOrUndef(Value *Mask) {
1071 auto *ConstMask = dyn_cast<Constant>(Mask);
1072 if (!ConstMask)
1073 return false;
1074 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1075 return true;
1076 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1077 ++I) {
1078 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1079 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1080 continue;
1081 return false;
1082 }
1083 return true;
1084}
1085
Sanjay Patelb695c552016-02-01 17:00:10 +00001086static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1087 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001088 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1089 // argument.
1090 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001091 Value *LoadPtr = II.getArgOperand(0);
1092 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1093 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1094 }
1095
1096 return nullptr;
1097}
1098
Sanjay Patel04f792b2016-02-01 19:39:52 +00001099static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1100 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1101 if (!ConstMask)
1102 return nullptr;
1103
1104 // If the mask is all zeros, this instruction does nothing.
1105 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001106 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001107
1108 // If the mask is all ones, this is a plain vector store of the 1st argument.
1109 if (ConstMask->isAllOnesValue()) {
1110 Value *StorePtr = II.getArgOperand(1);
1111 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1112 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1113 }
1114
1115 return nullptr;
1116}
1117
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001118static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1119 // If the mask is all zeros, return the "passthru" argument of the gather.
1120 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1121 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001122 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001123
1124 return nullptr;
1125}
1126
1127static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1128 // If the mask is all zeros, a scatter does nothing.
1129 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1130 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001131 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001132
1133 return nullptr;
1134}
1135
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001136static Value *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1137 Value *Op0 = II.getArgOperand(0);
1138 // FIXME: Try to simplify vectors of integers.
1139 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1140 if (!IT)
1141 return nullptr;
1142
1143 unsigned BitWidth = IT->getBitWidth();
1144 APInt KnownZero(BitWidth, 0);
1145 APInt KnownOne(BitWidth, 0);
1146 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1147
1148 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1149 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1150 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1151 : KnownOne.countLeadingZeros();
1152 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1153 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1154
1155 // If all bits above (ctlz) or below (cttz) the first known one are known
1156 // zero, this value is constant.
1157 // FIXME: This should be in InstSimplify because we're replacing an
1158 // instruction with a constant.
1159 if ((Mask & KnownZero) == Mask)
1160 return ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1161
1162 return nullptr;
1163}
1164
Sanjay Patel1ace9932016-02-26 21:04:14 +00001165// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1166// XMM register mask efficiently, we could transform all x86 masked intrinsics
1167// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001168static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1169 Value *Ptr = II.getOperand(0);
1170 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001171 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001172
1173 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001174 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001175 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001176 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001177
1178 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1179 if (!ConstMask)
1180 return nullptr;
1181
1182 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1183 // to allow target-independent optimizations.
1184
1185 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1186 // the LLVM intrinsic definition for the pointer argument.
1187 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1188 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1189 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1190
1191 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1192 // on each element's most significant bit (the sign bit).
1193 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1194
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001195 // The pass-through vector for an x86 masked load is a zero vector.
1196 CallInst *NewMaskedLoad =
1197 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001198 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1199}
1200
1201// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1202// XMM register mask efficiently, we could transform all x86 masked intrinsics
1203// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001204static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1205 Value *Ptr = II.getOperand(0);
1206 Value *Mask = II.getOperand(1);
1207 Value *Vec = II.getOperand(2);
1208
1209 // Special case a zero mask since that's not a ConstantDataVector:
1210 // this masked store instruction does nothing.
1211 if (isa<ConstantAggregateZero>(Mask)) {
1212 IC.eraseInstFromFunction(II);
1213 return true;
1214 }
1215
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001216 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1217 // anything else at this level.
1218 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1219 return false;
1220
Sanjay Patel1ace9932016-02-26 21:04:14 +00001221 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1222 if (!ConstMask)
1223 return false;
1224
1225 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1226 // to allow target-independent optimizations.
1227
1228 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1229 // the LLVM intrinsic definition for the pointer argument.
1230 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1231 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001232 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1233
1234 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1235 // on each element's most significant bit (the sign bit).
1236 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1237
1238 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1239
1240 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1241 IC.eraseInstFromFunction(II);
1242 return true;
1243}
1244
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001245// Returns true iff the 2 intrinsics have the same operands, limiting the
1246// comparison to the first NumOperands.
1247static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1248 unsigned NumOperands) {
1249 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1250 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1251 for (unsigned i = 0; i < NumOperands; i++)
1252 if (I.getArgOperand(i) != E.getArgOperand(i))
1253 return false;
1254 return true;
1255}
1256
1257// Remove trivially empty start/end intrinsic ranges, i.e. a start
1258// immediately followed by an end (ignoring debuginfo or other
1259// start/end intrinsics in between). As this handles only the most trivial
1260// cases, tracking the nesting level is not needed:
1261//
1262// call @llvm.foo.start(i1 0) ; &I
1263// call @llvm.foo.start(i1 0)
1264// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1265// call @llvm.foo.end(i1 0)
1266static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1267 unsigned EndID, InstCombiner &IC) {
1268 assert(I.getIntrinsicID() == StartID &&
1269 "Start intrinsic does not have expected ID");
1270 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1271 for (++BI; BI != BE; ++BI) {
1272 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1273 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1274 continue;
1275 if (E->getIntrinsicID() == EndID &&
1276 haveSameOperands(I, *E, E->getNumArgOperands())) {
1277 IC.eraseInstFromFunction(*E);
1278 IC.eraseInstFromFunction(I);
1279 return true;
1280 }
1281 }
1282 break;
1283 }
1284
1285 return false;
1286}
1287
1288Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1289 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1290 return nullptr;
1291}
1292
1293Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1294 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1295 return nullptr;
1296}
1297
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001298/// CallInst simplification. This mostly only handles folding of intrinsic
1299/// instructions. For normal calls, it allows visitCallSite to do the heavy
1300/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001301Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001302 auto Args = CI.arg_operands();
1303 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Justin Bogner99798402016-08-05 01:06:44 +00001304 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001305 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001306
Justin Bogner99798402016-08-05 01:06:44 +00001307 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001308 return visitFree(CI);
1309
1310 // If the caller function is nounwind, mark the call as nounwind, even if the
1311 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001312 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001313 CI.setDoesNotThrow();
1314 return &CI;
1315 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001316
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001317 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1318 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001319
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001320 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1321 // visitCallSite.
1322 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1323 bool Changed = false;
1324
1325 // memmove/cpy/set of zero bytes is a noop.
1326 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001327 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001328 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001329
1330 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1331 if (CI->getZExtValue() == 1) {
1332 // Replace the instruction with just byte operations. We would
1333 // transform other cases to loads/stores, but we don't know if
1334 // alignment is sufficient.
1335 }
1336 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001337
Chris Lattnerc663a672010-10-01 05:51:02 +00001338 // No other transformations apply to volatile transfers.
1339 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001340 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001341
1342 // If we have a memmove and the source operation is a constant global,
1343 // then the source and dest pointers can't alias, so we can change this
1344 // into a call to memcpy.
1345 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1346 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1347 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001348 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001349 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001350 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1351 CI.getArgOperand(1)->getType(),
1352 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001353 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001354 Changed = true;
1355 }
1356 }
1357
1358 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1359 // memmove(x,x,size) -> noop.
1360 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001361 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001362 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001363
Eric Christopher7258dcd2010-04-16 23:37:20 +00001364 // If we can determine a pointer alignment that is bigger than currently
1365 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001366 if (isa<MemTransferInst>(MI)) {
1367 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001368 return I;
1369 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1370 if (Instruction *I = SimplifyMemSet(MSI))
1371 return I;
1372 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001373
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001374 if (Changed) return II;
1375 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001376
Sanjay Patel1c600c62016-01-20 16:41:43 +00001377 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1378 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001379 APInt UndefElts(Width, 0);
1380 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1381 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1382 };
Simon Pilgrim424da162016-04-24 18:12:42 +00001383 auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1384 unsigned DemandedWidth) {
1385 APInt UndefElts(Width, 0);
1386 APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1387 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1388 };
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001389
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001390 switch (II->getIntrinsicID()) {
1391 default: break;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001392 case Intrinsic::objectsize: {
Nuno Lopes55fff832012-06-21 15:45:28 +00001393 uint64_t Size;
Justin Bogner99798402016-08-05 01:06:44 +00001394 if (getObjectSize(II->getArgOperand(0), Size, DL, &TLI)) {
George Burgess IV278199f2016-04-12 01:05:35 +00001395 APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1396 // Equality check to be sure that `Size` can fit in a value of type
1397 // `II->getType()`
1398 if (APSize == Size)
1399 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1400 }
Craig Topperf40110f2014-04-25 05:29:35 +00001401 return nullptr;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001402 }
Michael Ilseman536cc322012-12-13 03:13:36 +00001403 case Intrinsic::bswap: {
1404 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001405 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001406
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001407 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001408 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001409 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001410
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001411 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001412 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1413 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1414 IIOperand->getType()->getPrimitiveSizeInBits();
1415 Value *CV = ConstantInt::get(X->getType(), C);
1416 Value *V = Builder->CreateLShr(X, CV);
1417 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001418 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001419 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001420 }
1421
James Molloy2d09c002015-11-12 12:39:41 +00001422 case Intrinsic::bitreverse: {
1423 Value *IIOperand = II->getArgOperand(0);
1424 Value *X = nullptr;
1425
1426 // bitreverse(bitreverse(x)) -> x
1427 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001428 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001429 break;
1430 }
1431
Sanjay Patelb695c552016-02-01 17:00:10 +00001432 case Intrinsic::masked_load:
1433 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001434 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001435 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001436 case Intrinsic::masked_store:
1437 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001438 case Intrinsic::masked_gather:
1439 return simplifyMaskedGather(*II, *this);
1440 case Intrinsic::masked_scatter:
1441 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001442
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001443 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001444 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001445 // powi(x, 0) -> 1.0
1446 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001447 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001448 // powi(x, 1) -> x
1449 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001450 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001451 // powi(x, -1) -> 1/x
1452 if (Power->isAllOnesValue())
1453 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001454 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001455 }
1456 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001457
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001458 case Intrinsic::cttz:
1459 case Intrinsic::ctlz:
1460 if (Value *V = foldCttzCtlz(*II, *this))
1461 return replaceInstUsesWith(*II, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001462 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001463
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001464 case Intrinsic::uadd_with_overflow:
1465 case Intrinsic::sadd_with_overflow:
1466 case Intrinsic::umul_with_overflow:
1467 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001468 if (isa<Constant>(II->getArgOperand(0)) &&
1469 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001470 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001471 Value *LHS = II->getArgOperand(0);
1472 II->setArgOperand(0, II->getArgOperand(1));
1473 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001474 return II;
1475 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001476 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001477
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001478 case Intrinsic::usub_with_overflow:
1479 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001480 OverflowCheckFlavor OCF =
1481 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1482 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001483
Sanjoy Dasb0984472015-04-08 04:27:22 +00001484 Value *OperationResult = nullptr;
1485 Constant *OverflowResult = nullptr;
1486 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1487 *II, OperationResult, OverflowResult))
1488 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001489
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001490 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001491 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001492
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001493 case Intrinsic::minnum:
1494 case Intrinsic::maxnum: {
1495 Value *Arg0 = II->getArgOperand(0);
1496 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001497 // Canonicalize constants to the RHS.
1498 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001499 II->setArgOperand(0, Arg1);
1500 II->setArgOperand(1, Arg0);
1501 return II;
1502 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001503 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001504 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001505 break;
1506 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001507 case Intrinsic::ppc_altivec_lvx:
1508 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001509 // Turn PPC lvx -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001510 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1511 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001512 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001513 PointerType::getUnqual(II->getType()));
1514 return new LoadInst(Ptr);
1515 }
1516 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001517 case Intrinsic::ppc_vsx_lxvw4x:
1518 case Intrinsic::ppc_vsx_lxvd2x: {
1519 // Turn PPC VSX loads into normal loads.
1520 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1521 PointerType::getUnqual(II->getType()));
1522 return new LoadInst(Ptr, Twine(""), false, 1);
1523 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001524 case Intrinsic::ppc_altivec_stvx:
1525 case Intrinsic::ppc_altivec_stvxl:
1526 // Turn stvx -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001527 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1528 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001529 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001530 PointerType::getUnqual(II->getArgOperand(0)->getType());
1531 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1532 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001533 }
1534 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001535 case Intrinsic::ppc_vsx_stxvw4x:
1536 case Intrinsic::ppc_vsx_stxvd2x: {
1537 // Turn PPC VSX stores into normal stores.
1538 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1539 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1540 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1541 }
Hal Finkel221f4672015-02-26 18:56:03 +00001542 case Intrinsic::ppc_qpx_qvlfs:
1543 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001544 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1545 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001546 Type *VTy = VectorType::get(Builder->getFloatTy(),
1547 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001548 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001549 PointerType::getUnqual(VTy));
1550 Value *Load = Builder->CreateLoad(Ptr);
1551 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001552 }
1553 break;
1554 case Intrinsic::ppc_qpx_qvlfd:
1555 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001556 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
1557 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001558 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1559 PointerType::getUnqual(II->getType()));
1560 return new LoadInst(Ptr);
1561 }
1562 break;
1563 case Intrinsic::ppc_qpx_qvstfs:
1564 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001565 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1566 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001567 Type *VTy = VectorType::get(Builder->getFloatTy(),
1568 II->getArgOperand(0)->getType()->getVectorNumElements());
1569 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1570 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001571 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001572 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001573 }
1574 break;
1575 case Intrinsic::ppc_qpx_qvstfd:
1576 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001577 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
1578 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001579 Type *OpPtrTy =
1580 PointerType::getUnqual(II->getArgOperand(0)->getType());
1581 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1582 return new StoreInst(II->getArgOperand(0), Ptr);
1583 }
1584 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001585
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001586 case Intrinsic::x86_vcvtph2ps_128:
1587 case Intrinsic::x86_vcvtph2ps_256: {
1588 auto Arg = II->getArgOperand(0);
1589 auto ArgType = cast<VectorType>(Arg->getType());
1590 auto RetType = cast<VectorType>(II->getType());
1591 unsigned ArgWidth = ArgType->getNumElements();
1592 unsigned RetWidth = RetType->getNumElements();
1593 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1594 assert(ArgType->isIntOrIntVectorTy() &&
1595 ArgType->getScalarSizeInBits() == 16 &&
1596 "CVTPH2PS input type should be 16-bit integer vector");
1597 assert(RetType->getScalarType()->isFloatTy() &&
1598 "CVTPH2PS output type should be 32-bit float vector");
1599
1600 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001601 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001602 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001603
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001604 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001605 auto VectorHalfAsShorts = Arg;
1606 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00001607 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001608 for (unsigned i = 0; i != RetWidth; ++i)
1609 SubVecMask.push_back((int)i);
1610 VectorHalfAsShorts = Builder->CreateShuffleVector(
1611 Arg, UndefValue::get(ArgType), SubVecMask);
1612 }
1613
1614 auto VectorHalfType =
1615 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1616 auto VectorHalfs =
1617 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1618 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001619 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001620 }
1621
1622 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001623 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001624 II->setArgOperand(0, V);
1625 return II;
1626 }
1627 break;
1628 }
1629
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001630 case Intrinsic::x86_sse_cvtss2si:
1631 case Intrinsic::x86_sse_cvtss2si64:
1632 case Intrinsic::x86_sse_cvttss2si:
1633 case Intrinsic::x86_sse_cvttss2si64:
1634 case Intrinsic::x86_sse2_cvtsd2si:
1635 case Intrinsic::x86_sse2_cvtsd2si64:
1636 case Intrinsic::x86_sse2_cvttsd2si:
1637 case Intrinsic::x86_sse2_cvttsd2si64: {
1638 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001639 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001640 Value *Arg = II->getArgOperand(0);
1641 unsigned VWidth = Arg->getType()->getVectorNumElements();
1642 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001643 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001644 return II;
1645 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001646 break;
1647 }
1648
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00001649 case Intrinsic::x86_mmx_pmovmskb:
1650 case Intrinsic::x86_sse_movmsk_ps:
1651 case Intrinsic::x86_sse2_movmsk_pd:
1652 case Intrinsic::x86_sse2_pmovmskb_128:
1653 case Intrinsic::x86_avx_movmsk_pd_256:
1654 case Intrinsic::x86_avx_movmsk_ps_256:
1655 case Intrinsic::x86_avx2_pmovmskb: {
1656 if (Value *V = simplifyX86movmsk(*II, *Builder))
1657 return replaceInstUsesWith(*II, V);
1658 break;
1659 }
1660
Simon Pilgrim471efd22016-02-20 23:17:35 +00001661 case Intrinsic::x86_sse_comieq_ss:
1662 case Intrinsic::x86_sse_comige_ss:
1663 case Intrinsic::x86_sse_comigt_ss:
1664 case Intrinsic::x86_sse_comile_ss:
1665 case Intrinsic::x86_sse_comilt_ss:
1666 case Intrinsic::x86_sse_comineq_ss:
1667 case Intrinsic::x86_sse_ucomieq_ss:
1668 case Intrinsic::x86_sse_ucomige_ss:
1669 case Intrinsic::x86_sse_ucomigt_ss:
1670 case Intrinsic::x86_sse_ucomile_ss:
1671 case Intrinsic::x86_sse_ucomilt_ss:
1672 case Intrinsic::x86_sse_ucomineq_ss:
1673 case Intrinsic::x86_sse2_comieq_sd:
1674 case Intrinsic::x86_sse2_comige_sd:
1675 case Intrinsic::x86_sse2_comigt_sd:
1676 case Intrinsic::x86_sse2_comile_sd:
1677 case Intrinsic::x86_sse2_comilt_sd:
1678 case Intrinsic::x86_sse2_comineq_sd:
1679 case Intrinsic::x86_sse2_ucomieq_sd:
1680 case Intrinsic::x86_sse2_ucomige_sd:
1681 case Intrinsic::x86_sse2_ucomigt_sd:
1682 case Intrinsic::x86_sse2_ucomile_sd:
1683 case Intrinsic::x86_sse2_ucomilt_sd:
1684 case Intrinsic::x86_sse2_ucomineq_sd: {
1685 // These intrinsics only demand the 0th element of their input vectors. If
1686 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001687 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001688 Value *Arg0 = II->getArgOperand(0);
1689 Value *Arg1 = II->getArgOperand(1);
1690 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1691 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1692 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001693 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001694 }
1695 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1696 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001697 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001698 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001699 if (MadeChange)
1700 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001701 break;
1702 }
1703
Simon Pilgrim424da162016-04-24 18:12:42 +00001704 case Intrinsic::x86_sse_add_ss:
1705 case Intrinsic::x86_sse_sub_ss:
1706 case Intrinsic::x86_sse_mul_ss:
1707 case Intrinsic::x86_sse_div_ss:
1708 case Intrinsic::x86_sse_min_ss:
1709 case Intrinsic::x86_sse_max_ss:
1710 case Intrinsic::x86_sse_cmp_ss:
1711 case Intrinsic::x86_sse2_add_sd:
1712 case Intrinsic::x86_sse2_sub_sd:
1713 case Intrinsic::x86_sse2_mul_sd:
1714 case Intrinsic::x86_sse2_div_sd:
1715 case Intrinsic::x86_sse2_min_sd:
1716 case Intrinsic::x86_sse2_max_sd:
1717 case Intrinsic::x86_sse2_cmp_sd: {
1718 // These intrinsics only demand the lowest element of the second input
1719 // vector.
1720 Value *Arg1 = II->getArgOperand(1);
1721 unsigned VWidth = Arg1->getType()->getVectorNumElements();
1722 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1723 II->setArgOperand(1, V);
1724 return II;
1725 }
1726 break;
1727 }
1728
1729 case Intrinsic::x86_sse41_round_ss:
1730 case Intrinsic::x86_sse41_round_sd: {
1731 // These intrinsics demand the upper elements of the first input vector and
1732 // the lowest element of the second input vector.
1733 bool MadeChange = false;
1734 Value *Arg0 = II->getArgOperand(0);
1735 Value *Arg1 = II->getArgOperand(1);
1736 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1737 if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1738 II->setArgOperand(0, V);
1739 MadeChange = true;
1740 }
1741 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1742 II->setArgOperand(1, V);
1743 MadeChange = true;
1744 }
1745 if (MadeChange)
1746 return II;
1747 break;
1748 }
1749
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001750 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001751 // Constant fold lshr( <A x Bi>, Ci ).
1752 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001753 case Intrinsic::x86_sse2_psrai_d:
1754 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001755 case Intrinsic::x86_avx2_psrai_d:
1756 case Intrinsic::x86_avx2_psrai_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001757 case Intrinsic::x86_sse2_psrli_d:
1758 case Intrinsic::x86_sse2_psrli_q:
1759 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001760 case Intrinsic::x86_avx2_psrli_d:
1761 case Intrinsic::x86_avx2_psrli_q:
1762 case Intrinsic::x86_avx2_psrli_w:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00001763 case Intrinsic::x86_sse2_pslli_d:
1764 case Intrinsic::x86_sse2_pslli_q:
1765 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001766 case Intrinsic::x86_avx2_pslli_d:
1767 case Intrinsic::x86_avx2_pslli_q:
1768 case Intrinsic::x86_avx2_pslli_w:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001769 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001770 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00001771 break;
1772
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001773 case Intrinsic::x86_sse2_psra_d:
1774 case Intrinsic::x86_sse2_psra_w:
1775 case Intrinsic::x86_avx2_psra_d:
1776 case Intrinsic::x86_avx2_psra_w:
1777 case Intrinsic::x86_sse2_psrl_d:
1778 case Intrinsic::x86_sse2_psrl_q:
1779 case Intrinsic::x86_sse2_psrl_w:
1780 case Intrinsic::x86_avx2_psrl_d:
1781 case Intrinsic::x86_avx2_psrl_q:
1782 case Intrinsic::x86_avx2_psrl_w:
1783 case Intrinsic::x86_sse2_psll_d:
1784 case Intrinsic::x86_sse2_psll_q:
1785 case Intrinsic::x86_sse2_psll_w:
1786 case Intrinsic::x86_avx2_psll_d:
1787 case Intrinsic::x86_avx2_psll_q:
1788 case Intrinsic::x86_avx2_psll_w: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001789 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001790 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001791
1792 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1793 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001794 Value *Arg1 = II->getArgOperand(1);
1795 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001796 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00001797 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001798
Simon Pilgrim996725e2015-09-19 11:41:53 +00001799 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001800 II->setArgOperand(1, V);
1801 return II;
1802 }
1803 break;
1804 }
1805
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001806 case Intrinsic::x86_avx2_psllv_d:
1807 case Intrinsic::x86_avx2_psllv_d_256:
1808 case Intrinsic::x86_avx2_psllv_q:
1809 case Intrinsic::x86_avx2_psllv_q_256:
1810 case Intrinsic::x86_avx2_psrav_d:
1811 case Intrinsic::x86_avx2_psrav_d_256:
1812 case Intrinsic::x86_avx2_psrlv_d:
1813 case Intrinsic::x86_avx2_psrlv_d_256:
1814 case Intrinsic::x86_avx2_psrlv_q:
1815 case Intrinsic::x86_avx2_psrlv_q_256:
1816 if (Value *V = simplifyX86varShift(*II, *Builder))
1817 return replaceInstUsesWith(*II, V);
1818 break;
1819
Sanjay Patelc86867c2015-04-16 17:52:13 +00001820 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001821 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001822 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00001823 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001824
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001825 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001826 Value *Op0 = II->getArgOperand(0);
1827 Value *Op1 = II->getArgOperand(1);
1828 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1829 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001830 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1831 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1832 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001833
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001834 // See if we're dealing with constant values.
1835 Constant *C1 = dyn_cast<Constant>(Op1);
1836 ConstantInt *CILength =
1837 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)0))
1838 : nullptr;
1839 ConstantInt *CIIndex =
1840 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1841 : nullptr;
1842
1843 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001844 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001845 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001846
1847 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1848 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001849 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001850 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1851 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001852 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001853 }
1854 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1855 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001856 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001857 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001858 if (MadeChange)
1859 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001860 break;
1861 }
1862
1863 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001864 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1865 // bits of the lower 64-bits. The upper 64-bits are undefined.
1866 Value *Op0 = II->getArgOperand(0);
1867 unsigned VWidth = Op0->getType()->getVectorNumElements();
1868 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1869 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001870
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001871 // See if we're dealing with constant values.
1872 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1873 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1874
1875 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001876 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001877 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001878
1879 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1880 // operand.
1881 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001882 II->setArgOperand(0, V);
1883 return II;
1884 }
1885 break;
1886 }
1887
1888 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001889 Value *Op0 = II->getArgOperand(0);
1890 Value *Op1 = II->getArgOperand(1);
1891 unsigned VWidth = Op0->getType()->getVectorNumElements();
1892 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1893 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1894 Op1->getType()->getVectorNumElements() == 2 &&
1895 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001896
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001897 // See if we're dealing with constant values.
1898 Constant *C1 = dyn_cast<Constant>(Op1);
1899 ConstantInt *CI11 =
1900 C1 ? dyn_cast<ConstantInt>(C1->getAggregateElement((unsigned)1))
1901 : nullptr;
1902
1903 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1904 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001905 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001906 APInt Len = V11.zextOrTrunc(6);
1907 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001908 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001909 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001910 }
1911
1912 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1913 // operand.
1914 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001915 II->setArgOperand(0, V);
1916 return II;
1917 }
1918 break;
1919 }
1920
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001921 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001922 // INSERTQI: Extract lowest Length bits from lower half of second source and
1923 // insert over first source starting at Index bit. The upper 64-bits are
1924 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001925 Value *Op0 = II->getArgOperand(0);
1926 Value *Op1 = II->getArgOperand(1);
1927 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1928 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001929 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1930 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1931 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001932
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001933 // See if we're dealing with constant values.
1934 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
1935 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
1936
1937 // Attempt to simplify to a constant or shuffle vector.
1938 if (CILength && CIIndex) {
1939 APInt Len = CILength->getValue().zextOrTrunc(6);
1940 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001941 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001942 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001943 }
1944
1945 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
1946 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001947 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001948 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1949 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001950 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001951 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001952 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
1953 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001954 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001955 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001956 if (MadeChange)
1957 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00001958 break;
1959 }
1960
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001961 case Intrinsic::x86_sse41_pblendvb:
1962 case Intrinsic::x86_sse41_blendvps:
1963 case Intrinsic::x86_sse41_blendvpd:
1964 case Intrinsic::x86_avx_blendv_ps_256:
1965 case Intrinsic::x86_avx_blendv_pd_256:
1966 case Intrinsic::x86_avx2_pblendvb: {
1967 // Convert blendv* to vector selects if the mask is constant.
1968 // This optimization is convoluted because the intrinsic is defined as
1969 // getting a vector of floats or doubles for the ps and pd versions.
1970 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001971
1972 Value *Op0 = II->getArgOperand(0);
1973 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001974 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001975
1976 // fold (blend A, A, Mask) -> A
1977 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00001978 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001979
1980 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00001981 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00001982 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001983
1984 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00001985 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
1986 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001987 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001988 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00001989 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00001990 }
1991
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00001992 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001993 case Intrinsic::x86_avx2_pshuf_b:
1994 if (Value *V = simplifyX86pshufb(*II, *Builder))
1995 return replaceInstUsesWith(*II, V);
1996 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00001997
Rafael Espindolabad3f772014-04-21 22:06:04 +00001998 case Intrinsic::x86_avx_vpermilvar_ps:
1999 case Intrinsic::x86_avx_vpermilvar_ps_256:
2000 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002001 case Intrinsic::x86_avx_vpermilvar_pd_256:
2002 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2003 return replaceInstUsesWith(*II, V);
2004 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002005
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002006 case Intrinsic::x86_avx2_permd:
2007 case Intrinsic::x86_avx2_permps:
2008 if (Value *V = simplifyX86vpermv(*II, *Builder))
2009 return replaceInstUsesWith(*II, V);
2010 break;
2011
Sanjay Patelccf5f242015-03-20 21:47:56 +00002012 case Intrinsic::x86_avx_vperm2f128_pd_256:
2013 case Intrinsic::x86_avx_vperm2f128_ps_256:
2014 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002015 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002016 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002017 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002018 break;
2019
Sanjay Patel98a71502016-02-29 23:16:48 +00002020 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002021 case Intrinsic::x86_avx_maskload_pd:
2022 case Intrinsic::x86_avx_maskload_ps_256:
2023 case Intrinsic::x86_avx_maskload_pd_256:
2024 case Intrinsic::x86_avx2_maskload_d:
2025 case Intrinsic::x86_avx2_maskload_q:
2026 case Intrinsic::x86_avx2_maskload_d_256:
2027 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002028 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2029 return I;
2030 break;
2031
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002032 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002033 case Intrinsic::x86_avx_maskstore_ps:
2034 case Intrinsic::x86_avx_maskstore_pd:
2035 case Intrinsic::x86_avx_maskstore_ps_256:
2036 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002037 case Intrinsic::x86_avx2_maskstore_d:
2038 case Intrinsic::x86_avx2_maskstore_q:
2039 case Intrinsic::x86_avx2_maskstore_d_256:
2040 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002041 if (simplifyX86MaskedStore(*II, *this))
2042 return nullptr;
2043 break;
2044
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002045 case Intrinsic::x86_xop_vpcomb:
2046 case Intrinsic::x86_xop_vpcomd:
2047 case Intrinsic::x86_xop_vpcomq:
2048 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002049 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002050 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002051 break;
2052
2053 case Intrinsic::x86_xop_vpcomub:
2054 case Intrinsic::x86_xop_vpcomud:
2055 case Intrinsic::x86_xop_vpcomuq:
2056 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002057 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002058 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002059 break;
2060
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002061 case Intrinsic::ppc_altivec_vperm:
2062 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002063 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2064 // a vectorshuffle for little endian, we must undo the transformation
2065 // performed on vec_perm in altivec.h. That is, we must complement
2066 // the permutation mask with respect to 31 and reverse the order of
2067 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002068 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2069 assert(Mask->getType()->getVectorNumElements() == 16 &&
2070 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002071
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002072 // Check that all of the elements are integer constants or undefs.
2073 bool AllEltsOk = true;
2074 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002075 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002076 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002077 AllEltsOk = false;
2078 break;
2079 }
2080 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002081
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002082 if (AllEltsOk) {
2083 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002084 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2085 Mask->getType());
2086 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2087 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002088 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002089
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002090 // Only extract each element once.
2091 Value *ExtractedElts[32];
2092 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002093
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002094 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002095 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002096 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002097 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002098 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002099 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002100 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002101 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002102
Craig Topperf40110f2014-04-25 05:29:35 +00002103 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002104 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2105 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002106 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002107 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002108 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002109 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002110
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002111 // Insert this value into the result vector.
2112 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002113 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002114 }
2115 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2116 }
2117 }
2118 break;
2119
Bob Wilsona4e231c2010-10-22 21:41:48 +00002120 case Intrinsic::arm_neon_vld1:
2121 case Intrinsic::arm_neon_vld2:
2122 case Intrinsic::arm_neon_vld3:
2123 case Intrinsic::arm_neon_vld4:
2124 case Intrinsic::arm_neon_vld2lane:
2125 case Intrinsic::arm_neon_vld3lane:
2126 case Intrinsic::arm_neon_vld4lane:
2127 case Intrinsic::arm_neon_vst1:
2128 case Intrinsic::arm_neon_vst2:
2129 case Intrinsic::arm_neon_vst3:
2130 case Intrinsic::arm_neon_vst4:
2131 case Intrinsic::arm_neon_vst2lane:
2132 case Intrinsic::arm_neon_vst3lane:
2133 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00002134 unsigned MemAlign =
2135 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002136 unsigned AlignArg = II->getNumArgOperands() - 1;
2137 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2138 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2139 II->setArgOperand(AlignArg,
2140 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2141 MemAlign, false));
2142 return II;
2143 }
2144 break;
2145 }
2146
Lang Hames3a90fab2012-05-01 00:20:38 +00002147 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00002148 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00002149 case Intrinsic::aarch64_neon_smull:
2150 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00002151 Value *Arg0 = II->getArgOperand(0);
2152 Value *Arg1 = II->getArgOperand(1);
2153
2154 // Handle mul by zero first:
2155 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002156 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00002157 }
2158
2159 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00002160 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00002161 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00002162 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00002163 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2164 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2165 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2166 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2167
Sanjay Patel4b198802016-02-01 22:23:39 +00002168 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00002169 }
2170
Alp Tokercb402912014-01-24 17:20:08 +00002171 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00002172 std::swap(Arg0, Arg1);
2173 }
2174
2175 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00002176 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00002177 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00002178 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2179 if (Splat->isOne())
2180 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2181 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00002182
2183 break;
2184 }
2185
Matt Arsenaultbef34e22016-01-22 21:30:34 +00002186 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002187 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2188 const APFloat &ArgVal = C->getValueAPF();
2189 APFloat Val(ArgVal.getSemantics(), 1.0);
2190 APFloat::opStatus Status = Val.divide(ArgVal,
2191 APFloat::rmNearestTiesToEven);
2192 // Only do this if it was exact and therefore not dependent on the
2193 // rounding mode.
2194 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00002195 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002196 }
2197
2198 break;
2199 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002200 case Intrinsic::amdgcn_frexp_mant:
2201 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002202 Value *Src = II->getArgOperand(0);
2203 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2204 int Exp;
2205 APFloat Significand = frexp(C->getValueAPF(), Exp,
2206 APFloat::rmNearestTiesToEven);
2207
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002208 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2209 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2210 Significand));
2211 }
2212
2213 // Match instruction special case behavior.
2214 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2215 Exp = 0;
2216
2217 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2218 }
2219
2220 if (isa<UndefValue>(Src))
2221 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002222
2223 break;
2224 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002225 case Intrinsic::stackrestore: {
2226 // If the save is right next to the restore, remove the restore. This can
2227 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002228 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002229 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002230 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002231 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002232 }
2233 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002234
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002235 // Scan down this block to see if there is another stack restore in the
2236 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002237 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002238 TerminatorInst *TI = II->getParent()->getTerminator();
2239 bool CannotRemove = false;
2240 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002241 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002242 CannotRemove = true;
2243 break;
2244 }
2245 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2246 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2247 // If there is a stackrestore below this one, remove this one.
2248 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002249 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002250
2251 // Bail if we cross over an intrinsic with side effects, such as
2252 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2253 if (II->mayHaveSideEffects()) {
2254 CannotRemove = true;
2255 break;
2256 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002257 } else {
2258 // If we found a non-intrinsic call, we can't remove the stack
2259 // restore.
2260 CannotRemove = true;
2261 break;
2262 }
2263 }
2264 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002265
Bill Wendlingf891bf82011-07-31 06:30:59 +00002266 // If the stack restore is in a return, resume, or unwind block and if there
2267 // are no allocas or calls between the restore and the return, nuke the
2268 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002269 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002270 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002271 break;
2272 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00002273 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00002274 // Asan needs to poison memory to detect invalid access which is possible
2275 // even for empty lifetime range.
2276 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2277 break;
2278
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00002279 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2280 Intrinsic::lifetime_end, *this))
2281 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002282 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00002283 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002284 Value *IIOperand = II->getArgOperand(0);
2285 // Remove an assume if it is immediately followed by an identical assume.
2286 if (match(II->getNextNode(),
2287 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2288 return eraseInstFromFunction(CI);
2289
Hal Finkelf5867a72014-07-25 21:45:17 +00002290 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002291 // Note: New assumption intrinsics created here are registered by
2292 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002293 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002294 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2295 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2296 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002297 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002298 }
2299 // assume(!(a || b)) -> assume(!a); assume(!b);
2300 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002301 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2302 II->getName());
2303 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2304 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002305 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002306 }
Hal Finkel04a15612014-10-04 21:27:06 +00002307
Philip Reames66c6de62014-11-11 23:33:19 +00002308 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2309 // (if assume is valid at the load)
2310 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2311 Value *LHS = ICmp->getOperand(0);
2312 Value *RHS = ICmp->getOperand(1);
2313 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2314 isa<LoadInst>(LHS) &&
2315 isa<Constant>(RHS) &&
2316 RHS->getType()->isPointerTy() &&
2317 cast<Constant>(RHS)->isNullValue()) {
2318 LoadInst* LI = cast<LoadInst>(LHS);
Justin Bogner99798402016-08-05 01:06:44 +00002319 if (isValidAssumeForContext(II, LI, &DT)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002320 MDNode *MD = MDNode::get(II->getContext(), None);
Philip Reames66c6de62014-11-11 23:33:19 +00002321 LI->setMetadata(LLVMContext::MD_nonnull, MD);
Sanjay Patel4b198802016-02-01 22:23:39 +00002322 return eraseInstFromFunction(*II);
Philip Reames66c6de62014-11-11 23:33:19 +00002323 }
2324 }
Chandler Carruth24969102015-02-10 08:07:32 +00002325 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002326 // TODO: apply range metadata for range check patterns?
2327 }
Hal Finkel04a15612014-10-04 21:27:06 +00002328 // If there is a dominating assume with the same condition as this one,
2329 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002330 APInt KnownZero(1, 0), KnownOne(1, 0);
2331 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2332 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002333 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002334
Hal Finkelf5867a72014-07-25 21:45:17 +00002335 break;
2336 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002337 case Intrinsic::experimental_gc_relocate: {
2338 // Translate facts known about a pointer before relocating into
2339 // facts about the relocate value, while being careful to
2340 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002341 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002342
2343 // Remove the relocation if unused, note that this check is required
2344 // to prevent the cases below from looping forever.
2345 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002346 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002347
2348 // Undef is undef, even after relocation.
2349 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2350 // most practical collectors, but there was discussion in the review thread
2351 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002352 if (isa<UndefValue>(DerivedPtr))
2353 // Use undef of gc_relocate's type to replace it.
2354 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002355
Philip Reamesea4d8e82016-02-09 21:09:22 +00002356 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2357 // The relocation of null will be null for most any collector.
2358 // TODO: provide a hook for this in GCStrategy. There might be some
2359 // weird collector this property does not hold for.
2360 if (isa<ConstantPointerNull>(DerivedPtr))
2361 // Use null-pointer of gc_relocate's type to replace it.
2362 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002363
Philip Reamesea4d8e82016-02-09 21:09:22 +00002364 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00002365 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00002366 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002367 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002368
2369 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2370 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002371
Philip Reames9db26ff2014-12-29 23:27:30 +00002372 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002373 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002374 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002375 }
2376
2377 return visitCallSite(II);
2378}
2379
2380// InvokeInst simplification
2381//
2382Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2383 return visitCallSite(&II);
2384}
2385
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002386/// If this cast does not affect the value passed through the varargs area, we
2387/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002388static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002389 const DataLayout &DL,
2390 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002391 const int ix) {
2392 if (!CI->isLosslessCast())
2393 return false;
2394
Philip Reames1a1bdb22014-12-02 18:50:36 +00002395 // If this is a GC intrinsic, avoid munging types. We need types for
2396 // statepoint reconstruction in SelectionDAG.
2397 // TODO: This is probably something which should be expanded to all
2398 // intrinsics since the entire point of intrinsics is that
2399 // they are understandable by the optimizer.
2400 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2401 return false;
2402
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002403 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002404 // can't change to a type with a different size. If the size were
2405 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002406 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002407 return true;
2408
Jim Grosbach7815f562012-02-03 00:07:04 +00002409 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002410 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002411 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002412 if (!SrcTy->isSized() || !DstTy->isSized())
2413 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002414 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002415 return false;
2416 return true;
2417}
2418
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002419Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002420 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002421
Chandler Carruthba4c5172015-01-21 11:23:40 +00002422 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002423 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002424 };
Justin Bogner99798402016-08-05 01:06:44 +00002425 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002426 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002427 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002428 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002429 }
Meador Ingedf796f82012-10-13 16:45:24 +00002430
Craig Topperf40110f2014-04-25 05:29:35 +00002431 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002432}
2433
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002434static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002435 // Strip off at most one level of pointer casts, looking for an alloca. This
2436 // is good enough in practice and simpler than handling any number of casts.
2437 Value *Underlying = TrampMem->stripPointerCasts();
2438 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002439 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002440 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002441 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002442 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002443
Craig Topperf40110f2014-04-25 05:29:35 +00002444 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002445 for (User *U : TrampMem->users()) {
2446 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002447 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002448 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002449 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2450 if (InitTrampoline)
2451 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002452 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002453 InitTrampoline = II;
2454 continue;
2455 }
2456 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2457 // Allow any number of calls to adjust.trampoline.
2458 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002459 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002460 }
2461
2462 // No call to init.trampoline found.
2463 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002464 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002465
2466 // Check that the alloca is being used in the expected way.
2467 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002468 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002469
2470 return InitTrampoline;
2471}
2472
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002473static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002474 Value *TrampMem) {
2475 // Visit all the previous instructions in the basic block, and try to find a
2476 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002477 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2478 E = AdjustTramp->getParent()->begin();
2479 I != E;) {
2480 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00002481 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2482 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2483 II->getOperand(0) == TrampMem)
2484 return II;
2485 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00002486 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002487 }
Craig Topperf40110f2014-04-25 05:29:35 +00002488 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002489}
2490
2491// Given a call to llvm.adjust.trampoline, find and return the corresponding
2492// call to llvm.init.trampoline if the call to the trampoline can be optimized
2493// to a direct call to a function. Otherwise return NULL.
2494//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002495static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002496 Callee = Callee->stripPointerCasts();
2497 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2498 if (!AdjustTramp ||
2499 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002500 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002501
2502 Value *TrampMem = AdjustTramp->getOperand(0);
2503
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002504 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002505 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002506 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002507 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00002508 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002509}
2510
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002511/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002512Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00002513 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002514 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002515
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002516 bool Changed = false;
2517
Philip Reamesc25df112015-06-16 20:24:25 +00002518 // Mark any parameters that are known to be non-null with the nonnull
2519 // attribute. This is helpful for inlining calls to functions with null
2520 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00002521 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00002522 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00002523
Philip Reamesc25df112015-06-16 20:24:25 +00002524 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00002525 if (V->getType()->isPointerTy() &&
2526 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00002527 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00002528 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00002529 ArgNo++;
2530 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00002531
Philip Reamesc25df112015-06-16 20:24:25 +00002532 assert(ArgNo == CS.arg_size() && "sanity check");
2533
Akira Hatanaka237916b2015-12-02 06:58:49 +00002534 if (!Indices.empty()) {
2535 AttributeSet AS = CS.getAttributes();
2536 LLVMContext &Ctx = CS.getInstruction()->getContext();
2537 AS = AS.addAttribute(Ctx, Indices,
2538 Attribute::get(Ctx, Attribute::NonNull));
2539 CS.setAttributes(AS);
2540 Changed = true;
2541 }
2542
Chris Lattner73989652010-12-20 08:25:06 +00002543 // If the callee is a pointer to a function, attempt to move any casts to the
2544 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002545 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00002546 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00002547 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002548
Justin Lebar9d943972016-03-14 20:18:54 +00002549 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2550 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00002551 if (CS.isConvergent() && !CalleeF->isConvergent() &&
2552 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00002553 DEBUG(dbgs() << "Removing convergent attr from instr "
2554 << CS.getInstruction() << "\n");
2555 CS.setNotConvergent();
2556 return CS.getInstruction();
2557 }
2558
Chris Lattner846a52e2010-02-01 18:11:34 +00002559 // If the call and callee calling conventions don't match, this call must
2560 // be unreachable, as the call is undefined.
2561 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2562 // Only do this for calls to a function with a body. A prototype may
2563 // not actually end up matching the implementation's calling conv for a
2564 // variety of reasons (e.g. it may be written in assembly).
2565 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002566 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002567 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00002568 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002569 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00002570 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002571 // This allows ValueHandlers and custom metadata to adjust itself.
2572 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002573 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00002574 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00002575 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00002576
Chris Lattner2cecedf2010-02-01 18:04:58 +00002577 // We cannot remove an invoke, because it would change the CFG, just
2578 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00002579 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00002580 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00002581 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002582 }
Justin Lebar9d943972016-03-14 20:18:54 +00002583 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002584
2585 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002586 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002587 // This allows ValueHandlers and custom metadata to adjust itself.
2588 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002589 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002590 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002591
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002592 if (isa<InvokeInst>(CS.getInstruction())) {
2593 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00002594 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002595 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002596
2597 // This instruction is not reachable, just remove it. We insert a store to
2598 // undef so that we know that this code is not reachable, despite the fact
2599 // that we can't modify the CFG here.
2600 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2601 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2602 CS.getInstruction());
2603
Sanjay Patel4b198802016-02-01 22:23:39 +00002604 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002605 }
2606
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002607 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00002608 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002609
Chris Lattner229907c2011-07-18 04:54:35 +00002610 PointerType *PTy = cast<PointerType>(Callee->getType());
2611 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002612 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00002613 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002614 // See if we can optimize any arguments passed through the varargs area of
2615 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002616 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002617 E = CS.arg_end(); I != E; ++I, ++ix) {
2618 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002619 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002620 *I = CI->getOperand(0);
2621 Changed = true;
2622 }
2623 }
2624 }
2625
2626 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2627 // Inline asm calls cannot throw - mark them 'nounwind'.
2628 CS.setDoesNotThrow();
2629 Changed = true;
2630 }
2631
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002632 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00002633 // this. None of these calls are seen as possibly dead so go ahead and
2634 // delete the instruction now.
2635 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002636 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00002637 // If we changed something return the result, etc. Otherwise let
2638 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00002639 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00002640 }
2641
Craig Topperf40110f2014-04-25 05:29:35 +00002642 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002643}
2644
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002645/// If the callee is a constexpr cast of a function, attempt to move the cast to
2646/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002647bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00002648 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00002649 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002650 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002651
2652 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00002653 if (Callee->hasFnAttribute("thunk"))
2654 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002655
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002656 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00002657 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002658
2659 // Okay, this is a cast from a function to a different type. Unless doing so
2660 // would cause a type conversion of one of our arguments, change this call to
2661 // be a direct call with arguments casted to the appropriate types.
2662 //
Chris Lattner229907c2011-07-18 04:54:35 +00002663 FunctionType *FT = Callee->getFunctionType();
2664 Type *OldRetTy = Caller->getType();
2665 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002666
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002667 // Check to see if we are changing the return type...
2668 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00002669
2670 if (NewRetTy->isStructTy())
2671 return false; // TODO: Handle multiple return values.
2672
David Majnemer9b6b8222015-01-06 08:41:31 +00002673 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002674 if (Callee->isDeclaration())
2675 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002676
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002677 if (!Caller->use_empty() &&
2678 // void -> non-void is handled specially
2679 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00002680 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002681 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002682
2683 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00002684 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00002685 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002686 return false; // Attribute not compatible with transformed value.
2687 }
2688
2689 // If the callsite is an invoke instruction, and the return value is used by
2690 // a PHI node in a successor, we cannot change the return type of the call
2691 // because there is no place to put the cast instruction (without breaking
2692 // the critical edge). Bail out in this case.
2693 if (!Caller->use_empty())
2694 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002695 for (User *U : II->users())
2696 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002697 if (PN->getParent() == II->getNormalDest() ||
2698 PN->getParent() == II->getUnwindDest())
2699 return false;
2700 }
2701
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002702 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002703 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2704
David Majnemer9b6b8222015-01-06 08:41:31 +00002705 // Prevent us turning:
2706 // declare void @takes_i32_inalloca(i32* inalloca)
2707 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2708 //
2709 // into:
2710 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00002711 //
2712 // Similarly, avoid folding away bitcasts of byval calls.
2713 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2714 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00002715 return false;
2716
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002717 CallSite::arg_iterator AI = CS.arg_begin();
2718 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002719 Type *ParamTy = FT->getParamType(i);
2720 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002721
David Majnemer9b6b8222015-01-06 08:41:31 +00002722 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002723 return false; // Cannot transform this parameter value.
2724
Bill Wendling49bc76c2013-01-23 06:14:59 +00002725 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00002726 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002727 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00002728
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002729 if (CS.isInAllocaArgument(i))
2730 return false; // Cannot transform to and from inalloca.
2731
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002732 // If the parameter is passed as a byval argument, then we have to have a
2733 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002734 if (ParamTy != ActTy &&
2735 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2736 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00002737 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002738 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002739 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00002740
Matt Arsenaultfa252722013-09-27 22:18:51 +00002741 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002742 if (DL.getTypeAllocSize(CurElTy) !=
2743 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002744 return false;
2745 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002746 }
2747
Chris Lattneradf38b32011-02-24 05:10:56 +00002748 if (Callee->isDeclaration()) {
2749 // Do not delete arguments unless we have a function body.
2750 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2751 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002752
Chris Lattneradf38b32011-02-24 05:10:56 +00002753 // If the callee is just a declaration, don't change the varargsness of the
2754 // call. We don't want to introduce a varargs call where one doesn't
2755 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00002756 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00002757 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2758 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002759
2760 // If both the callee and the cast type are varargs, we still have to make
2761 // sure the number of fixed parameters are the same or we have the same
2762 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00002763 if (FT->isVarArg() &&
2764 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2765 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002766 cast<FunctionType>(APTy->getElementType())->getNumParams())
2767 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00002768 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002769
Jim Grosbach0ab54182012-02-03 00:00:50 +00002770 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2771 !CallerPAL.isEmpty())
2772 // In this case we have more arguments than the new function type, but we
2773 // won't be dropping them. Check that these extra arguments have attributes
2774 // that are compatible with being a vararg call argument.
2775 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00002776 unsigned Index = CallerPAL.getSlotIndex(i - 1);
2777 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00002778 break;
Bill Wendling57625a42013-01-25 23:09:36 +00002779
Bill Wendlingd97b75d2012-12-19 08:57:40 +00002780 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00002781 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2782 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00002783 return false;
2784 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002785
Jim Grosbach7815f562012-02-03 00:07:04 +00002786
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002787 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00002788 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002789 std::vector<Value*> Args;
2790 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002791 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002792 attrVec.reserve(NumCommonArgs);
2793
2794 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002795 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002796
2797 // If the return value is not being used, the type may not be compatible
2798 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00002799 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002800
2801 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00002802 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002803 attrVec.push_back(AttributeSet::get(Caller->getContext(),
2804 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002805
2806 AI = CS.arg_begin();
2807 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002808 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00002809
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002810 if ((*AI)->getType() == ParamTy) {
2811 Args.push_back(*AI);
2812 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00002813 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002814 }
2815
2816 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002817 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002818 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002819 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2820 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002821 }
2822
2823 // If the function takes more arguments than the call was taking, add them
2824 // now.
2825 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2826 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2827
2828 // If we are removing arguments to the function, emit an obnoxious warning.
2829 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00002830 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2831 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002832 // Add all of the arguments in their promoted form to the arg list.
2833 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002834 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002835 if (PTy != (*AI)->getType()) {
2836 // Must promote to pass through va_arg area!
2837 Instruction::CastOps opcode =
2838 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002839 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002840 } else {
2841 Args.push_back(*AI);
2842 }
2843
2844 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002845 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002846 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002847 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
2848 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002849 }
2850 }
2851 }
2852
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002853 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00002854 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002855 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002856
2857 if (NewRetTy->isVoidTy())
2858 Caller->setName(""); // Void type should not have a name.
2859
Bill Wendlinge94d8432012-12-07 23:16:57 +00002860 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00002861 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002862
Sanjoy Das76293462015-11-25 00:42:19 +00002863 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00002864 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00002865
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002866 Instruction *NC;
2867 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00002868 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
2869 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002870 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002871 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
2872 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
2873 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002874 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00002875 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00002876 NC->takeName(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002877 if (CI->isTailCall())
2878 cast<CallInst>(NC)->setTailCall();
2879 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
2880 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
2881 }
2882
2883 // Insert a cast of the return type as necessary.
2884 Value *NV = NC;
2885 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
2886 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00002887 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00002888 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002889
2890 // If this is an invoke instruction, we should insert it after the first
2891 // non-phi, instruction in the normal successor block.
2892 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00002893 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002894 InsertNewInstBefore(NC, *I);
2895 } else {
Chris Lattner73989652010-12-20 08:25:06 +00002896 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002897 InsertNewInstBefore(NC, *Caller);
2898 }
2899 Worklist.AddUsersToWorkList(*Caller);
2900 } else {
2901 NV = UndefValue::get(Caller->getType());
2902 }
2903 }
2904
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002905 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002906 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00002907 else if (Caller->hasValueHandle()) {
2908 if (OldRetTy == NV->getType())
2909 ValueHandleBase::ValueIsRAUWd(Caller, NV);
2910 else
2911 // We cannot call ValueIsRAUWd with a different type, and the
2912 // actual tracked value will disappear.
2913 ValueHandleBase::ValueIsDeleted(Caller);
2914 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002915
Sanjay Patel4b198802016-02-01 22:23:39 +00002916 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002917 return true;
2918}
2919
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002920/// Turn a call to a function created by init_trampoline / adjust_trampoline
2921/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00002922Instruction *
2923InstCombiner::transformCallThroughTrampoline(CallSite CS,
2924 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002925 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00002926 PointerType *PTy = cast<PointerType>(Callee->getType());
2927 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00002928 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002929
2930 // If the call already has the 'nest' attribute somewhere then give up -
2931 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00002932 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00002933 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002934
Duncan Sandsa0984362011-09-06 13:37:06 +00002935 assert(Tramp &&
2936 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002937
Gabor Greif3e44ea12010-07-22 10:37:47 +00002938 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00002939 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002940
Bill Wendlinge94d8432012-12-07 23:16:57 +00002941 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002942 if (!NestAttrs.isEmpty()) {
2943 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00002944 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00002945 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002946
2947 // Look for a parameter marked with the 'nest' attribute.
2948 for (FunctionType::param_iterator I = NestFTy->param_begin(),
2949 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00002950 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002951 // Record the parameter type and any other attributes.
2952 NestTy = *I;
2953 NestAttr = NestAttrs.getParamAttributes(NestIdx);
2954 break;
2955 }
2956
2957 if (NestTy) {
2958 Instruction *Caller = CS.getInstruction();
2959 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002960 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002961
Bill Wendling3575c8c2013-01-27 02:08:22 +00002962 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002963 NewAttrs.reserve(Attrs.getNumSlots() + 1);
2964
2965 // Insert the nest argument into the call argument list, which may
2966 // mean appending it. Likewise for attributes.
2967
2968 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002969 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00002970 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2971 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002972
2973 {
2974 unsigned Idx = 1;
2975 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
2976 do {
2977 if (Idx == NestIdx) {
2978 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00002979 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002980 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00002981 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002982 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002983 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2984 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002985 }
2986
2987 if (I == E)
2988 break;
2989
2990 // Add the original argument and attributes.
2991 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00002992 AttributeSet Attr = Attrs.getParamAttributes(Idx);
2993 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00002994 AttrBuilder B(Attr, Idx);
2995 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
2996 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00002997 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002998
Richard Trieu7a083812016-02-18 22:09:30 +00002999 ++Idx;
3000 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003001 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003002 }
3003
3004 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00003005 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003006 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3007 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003008
3009 // The trampoline may have been bitcast to a bogus type (FTy).
3010 // Handle this by synthesizing a new function type, equal to FTy
3011 // with the chain parameter inserted.
3012
Jay Foadb804a2b2011-07-12 14:06:48 +00003013 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003014 NewTypes.reserve(FTy->getNumParams()+1);
3015
3016 // Insert the chain's type into the list of parameter types, which may
3017 // mean appending it.
3018 {
3019 unsigned Idx = 1;
3020 FunctionType::param_iterator I = FTy->param_begin(),
3021 E = FTy->param_end();
3022
3023 do {
3024 if (Idx == NestIdx)
3025 // Add the chain's type.
3026 NewTypes.push_back(NestTy);
3027
3028 if (I == E)
3029 break;
3030
3031 // Add the original type.
3032 NewTypes.push_back(*I);
3033
Richard Trieu7a083812016-02-18 22:09:30 +00003034 ++Idx;
3035 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003036 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003037 }
3038
3039 // Replace the trampoline call with a direct call. Let the generic
3040 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00003041 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003042 FTy->isVarArg());
3043 Constant *NewCallee =
3044 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00003045 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003046 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00003047 const AttributeSet &NewPAL =
3048 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003049
David Majnemer231a68c2016-04-29 08:07:20 +00003050 SmallVector<OperandBundleDef, 1> OpBundles;
3051 CS.getOperandBundlesAsDefs(OpBundles);
3052
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003053 Instruction *NewCaller;
3054 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3055 NewCaller = InvokeInst::Create(NewCallee,
3056 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00003057 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003058 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3059 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3060 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00003061 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003062 if (cast<CallInst>(Caller)->isTailCall())
3063 cast<CallInst>(NewCaller)->setTailCall();
3064 cast<CallInst>(NewCaller)->
3065 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
3066 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3067 }
Eli Friedman49346012011-05-18 19:57:14 +00003068
3069 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003070 }
3071 }
3072
3073 // Replace the trampoline call with a direct call. Since there is no 'nest'
3074 // parameter, there is no need to adjust the argument list. Let the generic
3075 // code sort out any function type mismatches.
3076 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00003077 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003078 ConstantExpr::getBitCast(NestF, PTy);
3079 CS.setCalledFunction(NewCallee);
3080 return CS.getInstruction();
3081}