blob: 523b35c31bbc9cc799736ff0b2305fa88d929257 [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) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +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);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000195 MDNode *LoopMemParallelMD =
196 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
197 if (LoopMemParallelMD)
198 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000199
Eli Friedman49346012011-05-18 19:57:14 +0000200 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
201 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000202 if (CopyMD)
203 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000204 if (LoopMemParallelMD)
205 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000206
207 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000208 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000209 return MI;
210}
211
212Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000213 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000214 if (MI->getAlignment() < Alignment) {
215 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
216 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000217 return MI;
218 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000219
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000220 // Extract the length and alignment and fill if they are constant.
221 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
222 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000223 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000224 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000225 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000226 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000227 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000228
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000229 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
230 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000231 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000232
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000233 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000234 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
235 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
236 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000237
238 // Alignment 0 is identity for alignment 1 for memset, but not store.
239 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000240
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000241 // Extract the fill value and store.
242 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000243 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
244 MI->isVolatile());
245 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000246
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000247 // Set the size of the copy to 0, it will be deleted on the next iteration.
248 MI->setLength(Constant::getNullValue(LenC->getType()));
249 return MI;
250 }
251
Simon Pilgrim18617d12015-08-05 08:18:00 +0000252 return nullptr;
253}
254
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000255static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000256 InstCombiner::BuilderTy &Builder) {
257 bool LogicalShift = false;
258 bool ShiftLeft = false;
259
260 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000261 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000262 case Intrinsic::x86_sse2_psra_d:
263 case Intrinsic::x86_sse2_psra_w:
264 case Intrinsic::x86_sse2_psrai_d:
265 case Intrinsic::x86_sse2_psrai_w:
266 case Intrinsic::x86_avx2_psra_d:
267 case Intrinsic::x86_avx2_psra_w:
268 case Intrinsic::x86_avx2_psrai_d:
269 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000270 case Intrinsic::x86_avx512_psra_q_128:
271 case Intrinsic::x86_avx512_psrai_q_128:
272 case Intrinsic::x86_avx512_psra_q_256:
273 case Intrinsic::x86_avx512_psrai_q_256:
274 case Intrinsic::x86_avx512_psra_d_512:
275 case Intrinsic::x86_avx512_psra_q_512:
276 case Intrinsic::x86_avx512_psra_w_512:
277 case Intrinsic::x86_avx512_psrai_d_512:
278 case Intrinsic::x86_avx512_psrai_q_512:
279 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000280 LogicalShift = false; ShiftLeft = false;
281 break;
282 case Intrinsic::x86_sse2_psrl_d:
283 case Intrinsic::x86_sse2_psrl_q:
284 case Intrinsic::x86_sse2_psrl_w:
285 case Intrinsic::x86_sse2_psrli_d:
286 case Intrinsic::x86_sse2_psrli_q:
287 case Intrinsic::x86_sse2_psrli_w:
288 case Intrinsic::x86_avx2_psrl_d:
289 case Intrinsic::x86_avx2_psrl_q:
290 case Intrinsic::x86_avx2_psrl_w:
291 case Intrinsic::x86_avx2_psrli_d:
292 case Intrinsic::x86_avx2_psrli_q:
293 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000294 case Intrinsic::x86_avx512_psrl_d_512:
295 case Intrinsic::x86_avx512_psrl_q_512:
296 case Intrinsic::x86_avx512_psrl_w_512:
297 case Intrinsic::x86_avx512_psrli_d_512:
298 case Intrinsic::x86_avx512_psrli_q_512:
299 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000300 LogicalShift = true; ShiftLeft = false;
301 break;
302 case Intrinsic::x86_sse2_psll_d:
303 case Intrinsic::x86_sse2_psll_q:
304 case Intrinsic::x86_sse2_psll_w:
305 case Intrinsic::x86_sse2_pslli_d:
306 case Intrinsic::x86_sse2_pslli_q:
307 case Intrinsic::x86_sse2_pslli_w:
308 case Intrinsic::x86_avx2_psll_d:
309 case Intrinsic::x86_avx2_psll_q:
310 case Intrinsic::x86_avx2_psll_w:
311 case Intrinsic::x86_avx2_pslli_d:
312 case Intrinsic::x86_avx2_pslli_q:
313 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000314 case Intrinsic::x86_avx512_psll_d_512:
315 case Intrinsic::x86_avx512_psll_q_512:
316 case Intrinsic::x86_avx512_psll_w_512:
317 case Intrinsic::x86_avx512_pslli_d_512:
318 case Intrinsic::x86_avx512_pslli_q_512:
319 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000320 LogicalShift = true; ShiftLeft = true;
321 break;
322 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000323 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
324
Simon Pilgrim3815c162015-08-07 18:22:50 +0000325 // Simplify if count is constant.
326 auto Arg1 = II.getArgOperand(1);
327 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
328 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
329 auto CInt = dyn_cast<ConstantInt>(Arg1);
330 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000331 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000332
333 APInt Count(64, 0);
334 if (CDV) {
335 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
336 // operand to compute the shift amount.
337 auto VT = cast<VectorType>(CDV->getType());
338 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
339 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
340 unsigned NumSubElts = 64 / BitWidth;
341
342 // Concatenate the sub-elements to create the 64-bit value.
343 for (unsigned i = 0; i != NumSubElts; ++i) {
344 unsigned SubEltIdx = (NumSubElts - 1) - i;
345 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
346 Count = Count.shl(BitWidth);
347 Count |= SubElt->getValue().zextOrTrunc(64);
348 }
349 }
350 else if (CInt)
351 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000352
353 auto Vec = II.getArgOperand(0);
354 auto VT = cast<VectorType>(Vec->getType());
355 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000356 unsigned VWidth = VT->getNumElements();
357 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
358
359 // If shift-by-zero then just return the original value.
360 if (Count == 0)
361 return Vec;
362
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000363 // Handle cases when Shift >= BitWidth.
364 if (Count.uge(BitWidth)) {
365 // If LogicalShift - just return zero.
366 if (LogicalShift)
367 return ConstantAggregateZero::get(VT);
368
369 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
370 Count = APInt(64, BitWidth - 1);
371 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000372
Simon Pilgrim18617d12015-08-05 08:18:00 +0000373 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000374 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
375 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000376
377 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000378 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000379
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000380 if (LogicalShift)
381 return Builder.CreateLShr(Vec, ShiftVec);
382
383 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000384}
385
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000386// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
387// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
388// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
389static Value *simplifyX86varShift(const IntrinsicInst &II,
390 InstCombiner::BuilderTy &Builder) {
391 bool LogicalShift = false;
392 bool ShiftLeft = false;
393
394 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000395 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000396 case Intrinsic::x86_avx2_psrav_d:
397 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000398 case Intrinsic::x86_avx512_psrav_q_128:
399 case Intrinsic::x86_avx512_psrav_q_256:
400 case Intrinsic::x86_avx512_psrav_d_512:
401 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000402 case Intrinsic::x86_avx512_psrav_w_128:
403 case Intrinsic::x86_avx512_psrav_w_256:
404 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000405 LogicalShift = false;
406 ShiftLeft = false;
407 break;
408 case Intrinsic::x86_avx2_psrlv_d:
409 case Intrinsic::x86_avx2_psrlv_d_256:
410 case Intrinsic::x86_avx2_psrlv_q:
411 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000412 case Intrinsic::x86_avx512_psrlv_d_512:
413 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000414 case Intrinsic::x86_avx512_psrlv_w_128:
415 case Intrinsic::x86_avx512_psrlv_w_256:
416 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000417 LogicalShift = true;
418 ShiftLeft = false;
419 break;
420 case Intrinsic::x86_avx2_psllv_d:
421 case Intrinsic::x86_avx2_psllv_d_256:
422 case Intrinsic::x86_avx2_psllv_q:
423 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000424 case Intrinsic::x86_avx512_psllv_d_512:
425 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000426 case Intrinsic::x86_avx512_psllv_w_128:
427 case Intrinsic::x86_avx512_psllv_w_256:
428 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000429 LogicalShift = true;
430 ShiftLeft = true;
431 break;
432 }
433 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
434
435 // Simplify if all shift amounts are constant/undef.
436 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
437 if (!CShift)
438 return nullptr;
439
440 auto Vec = II.getArgOperand(0);
441 auto VT = cast<VectorType>(II.getType());
442 auto SVT = VT->getVectorElementType();
443 int NumElts = VT->getNumElements();
444 int BitWidth = SVT->getIntegerBitWidth();
445
446 // Collect each element's shift amount.
447 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
448 bool AnyOutOfRange = false;
449 SmallVector<int, 8> ShiftAmts;
450 for (int I = 0; I < NumElts; ++I) {
451 auto *CElt = CShift->getAggregateElement(I);
452 if (CElt && isa<UndefValue>(CElt)) {
453 ShiftAmts.push_back(-1);
454 continue;
455 }
456
457 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
458 if (!COp)
459 return nullptr;
460
461 // Handle out of range shifts.
462 // If LogicalShift - set to BitWidth (special case).
463 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
464 APInt ShiftVal = COp->getValue();
465 if (ShiftVal.uge(BitWidth)) {
466 AnyOutOfRange = LogicalShift;
467 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
468 continue;
469 }
470
471 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
472 }
473
474 // If all elements out of range or UNDEF, return vector of zeros/undefs.
475 // ArithmeticShift should only hit this if they are all UNDEF.
476 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000477 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000478 SmallVector<Constant *, 8> ConstantVec;
479 for (int Idx : ShiftAmts) {
480 if (Idx < 0) {
481 ConstantVec.push_back(UndefValue::get(SVT));
482 } else {
483 assert(LogicalShift && "Logical shift expected");
484 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
485 }
486 }
487 return ConstantVector::get(ConstantVec);
488 }
489
490 // We can't handle only some out of range values with generic logical shifts.
491 if (AnyOutOfRange)
492 return nullptr;
493
494 // Build the shift amount constant vector.
495 SmallVector<Constant *, 8> ShiftVecAmts;
496 for (int Idx : ShiftAmts) {
497 if (Idx < 0)
498 ShiftVecAmts.push_back(UndefValue::get(SVT));
499 else
500 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
501 }
502 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
503
504 if (ShiftLeft)
505 return Builder.CreateShl(Vec, ShiftVec);
506
507 if (LogicalShift)
508 return Builder.CreateLShr(Vec, ShiftVec);
509
510 return Builder.CreateAShr(Vec, ShiftVec);
511}
512
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000513static Value *simplifyX86muldq(const IntrinsicInst &II,
514 InstCombiner::BuilderTy &Builder) {
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000515 Value *Arg0 = II.getArgOperand(0);
516 Value *Arg1 = II.getArgOperand(1);
517 Type *ResTy = II.getType();
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000518 assert(Arg0->getType()->getScalarSizeInBits() == 32 &&
519 Arg1->getType()->getScalarSizeInBits() == 32 &&
520 ResTy->getScalarSizeInBits() == 64 && "Unexpected muldq/muludq types");
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000521
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000522 // muldq/muludq(undef, undef) -> zero (matches generic mul behavior)
Simon Pilgrim78f86302017-01-24 11:07:41 +0000523 if (isa<UndefValue>(Arg0) || isa<UndefValue>(Arg1))
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000524 return ConstantAggregateZero::get(ResTy);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000525
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000526 // Constant folding.
527 // PMULDQ = (mul(vXi64 sext(shuffle<0,2,..>(Arg0)),
528 // vXi64 sext(shuffle<0,2,..>(Arg1))))
529 // PMULUDQ = (mul(vXi64 zext(shuffle<0,2,..>(Arg0)),
530 // vXi64 zext(shuffle<0,2,..>(Arg1))))
531 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
532 return nullptr;
533
534 unsigned NumElts = ResTy->getVectorNumElements();
535 assert(Arg0->getType()->getVectorNumElements() == (2 * NumElts) &&
536 Arg1->getType()->getVectorNumElements() == (2 * NumElts) &&
537 "Unexpected muldq/muludq types");
538
539 unsigned IntrinsicID = II.getIntrinsicID();
540 bool IsSigned = (Intrinsic::x86_sse41_pmuldq == IntrinsicID ||
541 Intrinsic::x86_avx2_pmul_dq == IntrinsicID ||
542 Intrinsic::x86_avx512_pmul_dq_512 == IntrinsicID);
543
544 SmallVector<unsigned, 16> ShuffleMask;
545 for (unsigned i = 0; i != NumElts; ++i)
546 ShuffleMask.push_back(i * 2);
547
548 auto *LHS = Builder.CreateShuffleVector(Arg0, Arg0, ShuffleMask);
549 auto *RHS = Builder.CreateShuffleVector(Arg1, Arg1, ShuffleMask);
550
551 if (IsSigned) {
552 LHS = Builder.CreateSExt(LHS, ResTy);
553 RHS = Builder.CreateSExt(RHS, ResTy);
554 } else {
555 LHS = Builder.CreateZExt(LHS, ResTy);
556 RHS = Builder.CreateZExt(RHS, ResTy);
557 }
558
559 return Builder.CreateMul(LHS, RHS);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000560}
561
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000562static Value *simplifyX86movmsk(const IntrinsicInst &II,
563 InstCombiner::BuilderTy &Builder) {
564 Value *Arg = II.getArgOperand(0);
565 Type *ResTy = II.getType();
566 Type *ArgTy = Arg->getType();
567
568 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
569 if (isa<UndefValue>(Arg))
570 return Constant::getNullValue(ResTy);
571
572 // We can't easily peek through x86_mmx types.
573 if (!ArgTy->isVectorTy())
574 return nullptr;
575
576 auto *C = dyn_cast<Constant>(Arg);
577 if (!C)
578 return nullptr;
579
580 // Extract signbits of the vector input and pack into integer result.
581 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
582 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
583 auto *COp = C->getAggregateElement(I);
584 if (!COp)
585 return nullptr;
586 if (isa<UndefValue>(COp))
587 continue;
588
589 auto *CInt = dyn_cast<ConstantInt>(COp);
590 auto *CFp = dyn_cast<ConstantFP>(COp);
591 if (!CInt && !CFp)
592 return nullptr;
593
594 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
595 Result.setBit(I);
596 }
597
598 return Constant::getIntegerValue(ResTy, Result);
599}
600
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000601static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000602 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000603 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
604 if (!CInt)
605 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000606
Sanjay Patel03c03f52016-01-28 00:03:16 +0000607 VectorType *VecTy = cast<VectorType>(II.getType());
608 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000609
Sanjay Patel03c03f52016-01-28 00:03:16 +0000610 // The immediate permute control byte looks like this:
611 // [3:0] - zero mask for each 32-bit lane
612 // [5:4] - select one 32-bit destination lane
613 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000614
Sanjay Patel03c03f52016-01-28 00:03:16 +0000615 uint8_t Imm = CInt->getZExtValue();
616 uint8_t ZMask = Imm & 0xf;
617 uint8_t DestLane = (Imm >> 4) & 0x3;
618 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000619
Sanjay Patel03c03f52016-01-28 00:03:16 +0000620 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000621
Sanjay Patel03c03f52016-01-28 00:03:16 +0000622 // If all zero mask bits are set, this was just a weird way to
623 // generate a zero vector.
624 if (ZMask == 0xf)
625 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000626
Sanjay Patel03c03f52016-01-28 00:03:16 +0000627 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000628 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000629
Sanjay Patel03c03f52016-01-28 00:03:16 +0000630 // We may replace the second operand with the zero vector.
631 Value *V1 = II.getArgOperand(1);
632
633 if (ZMask) {
634 // If the zero mask is being used with a single input or the zero mask
635 // overrides the destination lane, this is a shuffle with the zero vector.
636 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
637 (ZMask & (1 << DestLane))) {
638 V1 = ZeroVector;
639 // We may still move 32-bits of the first source vector from one lane
640 // to another.
641 ShuffleMask[DestLane] = SourceLane;
642 // The zero mask may override the previous insert operation.
643 for (unsigned i = 0; i < 4; ++i)
644 if ((ZMask >> i) & 0x1)
645 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000646 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000647 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
648 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000649 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000650 } else {
651 // Replace the selected destination lane with the selected source lane.
652 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000653 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000654
655 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000656}
657
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000658/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
659/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000660static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000661 ConstantInt *CILength, ConstantInt *CIIndex,
662 InstCombiner::BuilderTy &Builder) {
663 auto LowConstantHighUndef = [&](uint64_t Val) {
664 Type *IntTy64 = Type::getInt64Ty(II.getContext());
665 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
666 UndefValue::get(IntTy64)};
667 return ConstantVector::get(Args);
668 };
669
670 // See if we're dealing with constant values.
671 Constant *C0 = dyn_cast<Constant>(Op0);
672 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000673 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000674 : nullptr;
675
676 // Attempt to constant fold.
677 if (CILength && CIIndex) {
678 // From AMD documentation: "The bit index and field length are each six
679 // bits in length other bits of the field are ignored."
680 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
681 APInt APLength = CILength->getValue().zextOrTrunc(6);
682
683 unsigned Index = APIndex.getZExtValue();
684
685 // From AMD documentation: "a value of zero in the field length is
686 // defined as length of 64".
687 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
688
689 // From AMD documentation: "If the sum of the bit index + length field
690 // is greater than 64, the results are undefined".
691 unsigned End = Index + Length;
692
693 // Note that both field index and field length are 8-bit quantities.
694 // Since variables 'Index' and 'Length' are unsigned values
695 // obtained from zero-extending field index and field length
696 // respectively, their sum should never wrap around.
697 if (End > 64)
698 return UndefValue::get(II.getType());
699
700 // If we are inserting whole bytes, we can convert this to a shuffle.
701 // Lowering can recognize EXTRQI shuffle masks.
702 if ((Length % 8) == 0 && (Index % 8) == 0) {
703 // Convert bit indices to byte indices.
704 Length /= 8;
705 Index /= 8;
706
707 Type *IntTy8 = Type::getInt8Ty(II.getContext());
708 Type *IntTy32 = Type::getInt32Ty(II.getContext());
709 VectorType *ShufTy = VectorType::get(IntTy8, 16);
710
711 SmallVector<Constant *, 16> ShuffleMask;
712 for (int i = 0; i != (int)Length; ++i)
713 ShuffleMask.push_back(
714 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
715 for (int i = Length; i != 8; ++i)
716 ShuffleMask.push_back(
717 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
718 for (int i = 8; i != 16; ++i)
719 ShuffleMask.push_back(UndefValue::get(IntTy32));
720
721 Value *SV = Builder.CreateShuffleVector(
722 Builder.CreateBitCast(Op0, ShufTy),
723 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
724 return Builder.CreateBitCast(SV, II.getType());
725 }
726
727 // Constant Fold - shift Index'th bit to lowest position and mask off
728 // Length bits.
729 if (CI0) {
730 APInt Elt = CI0->getValue();
731 Elt = Elt.lshr(Index).zextOrTrunc(Length);
732 return LowConstantHighUndef(Elt.getZExtValue());
733 }
734
735 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
736 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
737 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000738 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000739 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
740 return Builder.CreateCall(F, Args);
741 }
742 }
743
744 // Constant Fold - extraction from zero is always {zero, undef}.
745 if (CI0 && CI0->equalsInt(0))
746 return LowConstantHighUndef(0);
747
748 return nullptr;
749}
750
751/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
752/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000753static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000754 APInt APLength, APInt APIndex,
755 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000756 // From AMD documentation: "The bit index and field length are each six bits
757 // in length other bits of the field are ignored."
758 APIndex = APIndex.zextOrTrunc(6);
759 APLength = APLength.zextOrTrunc(6);
760
761 // Attempt to constant fold.
762 unsigned Index = APIndex.getZExtValue();
763
764 // From AMD documentation: "a value of zero in the field length is
765 // defined as length of 64".
766 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
767
768 // From AMD documentation: "If the sum of the bit index + length field
769 // is greater than 64, the results are undefined".
770 unsigned End = Index + Length;
771
772 // Note that both field index and field length are 8-bit quantities.
773 // Since variables 'Index' and 'Length' are unsigned values
774 // obtained from zero-extending field index and field length
775 // respectively, their sum should never wrap around.
776 if (End > 64)
777 return UndefValue::get(II.getType());
778
779 // If we are inserting whole bytes, we can convert this to a shuffle.
780 // Lowering can recognize INSERTQI shuffle masks.
781 if ((Length % 8) == 0 && (Index % 8) == 0) {
782 // Convert bit indices to byte indices.
783 Length /= 8;
784 Index /= 8;
785
786 Type *IntTy8 = Type::getInt8Ty(II.getContext());
787 Type *IntTy32 = Type::getInt32Ty(II.getContext());
788 VectorType *ShufTy = VectorType::get(IntTy8, 16);
789
790 SmallVector<Constant *, 16> ShuffleMask;
791 for (int i = 0; i != (int)Index; ++i)
792 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
793 for (int i = 0; i != (int)Length; ++i)
794 ShuffleMask.push_back(
795 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
796 for (int i = Index + Length; i != 8; ++i)
797 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
798 for (int i = 8; i != 16; ++i)
799 ShuffleMask.push_back(UndefValue::get(IntTy32));
800
801 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
802 Builder.CreateBitCast(Op1, ShufTy),
803 ConstantVector::get(ShuffleMask));
804 return Builder.CreateBitCast(SV, II.getType());
805 }
806
807 // See if we're dealing with constant values.
808 Constant *C0 = dyn_cast<Constant>(Op0);
809 Constant *C1 = dyn_cast<Constant>(Op1);
810 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000811 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000812 : nullptr;
813 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000814 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000815 : nullptr;
816
817 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
818 if (CI00 && CI10) {
819 APInt V00 = CI00->getValue();
820 APInt V10 = CI10->getValue();
821 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
822 V00 = V00 & ~Mask;
823 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
824 APInt Val = V00 | V10;
825 Type *IntTy64 = Type::getInt64Ty(II.getContext());
826 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
827 UndefValue::get(IntTy64)};
828 return ConstantVector::get(Args);
829 }
830
831 // If we were an INSERTQ call, we'll save demanded elements if we convert to
832 // INSERTQI.
833 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
834 Type *IntTy8 = Type::getInt8Ty(II.getContext());
835 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
836 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
837
838 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000839 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000840 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
841 return Builder.CreateCall(F, Args);
842 }
843
844 return nullptr;
845}
846
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000847/// Attempt to convert pshufb* to shufflevector if the mask is constant.
848static Value *simplifyX86pshufb(const IntrinsicInst &II,
849 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000850 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
851 if (!V)
852 return nullptr;
853
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000854 auto *VecTy = cast<VectorType>(II.getType());
855 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
856 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000857 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000858 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000859
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000860 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000861 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000862
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000863 // Each byte in the shuffle control mask forms an index to permute the
864 // corresponding byte in the destination operand.
865 for (unsigned I = 0; I < NumElts; ++I) {
866 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000867 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000868 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000869
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000870 if (isa<UndefValue>(COp)) {
871 Indexes[I] = UndefValue::get(MaskEltTy);
872 continue;
873 }
874
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000875 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
876
877 // If the most significant bit (bit[7]) of each byte of the shuffle
878 // control mask is set, then zero is written in the result byte.
879 // The zero vector is in the right-hand side of the resulting
880 // shufflevector.
881
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000882 // The value of each index for the high 128-bit lane is the least
883 // significant 4 bits of the respective shuffle control byte.
884 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
885 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000886 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000887
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000888 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000889 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000890 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000891 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
892}
893
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000894/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
895static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
896 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000897 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
898 if (!V)
899 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000900
Craig Topper58917f32016-12-11 01:59:36 +0000901 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000902 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +0000903 unsigned NumElts = VecTy->getVectorNumElements();
904 bool IsPD = VecTy->getScalarType()->isDoubleTy();
905 unsigned NumLaneElts = IsPD ? 2 : 4;
906 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000907
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000908 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +0000909 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000910
911 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000912 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000913 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000914 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000915 return nullptr;
916
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000917 if (isa<UndefValue>(COp)) {
918 Indexes[I] = UndefValue::get(MaskEltTy);
919 continue;
920 }
921
922 APInt Index = cast<ConstantInt>(COp)->getValue();
923 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000924
925 // The PD variants uses bit 1 to select per-lane element index, so
926 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +0000927 if (IsPD)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000928 Index = Index.lshr(1);
929
930 // The _256 variants are a bit trickier since the mask bits always index
931 // into the corresponding 128 half. In order to convert to a generic
932 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +0000933 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000934
935 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000936 }
937
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000938 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000939 auto V1 = II.getArgOperand(0);
940 auto V2 = UndefValue::get(V1->getType());
941 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
942}
943
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000944/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
945static Value *simplifyX86vpermv(const IntrinsicInst &II,
946 InstCombiner::BuilderTy &Builder) {
947 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
948 if (!V)
949 return nullptr;
950
Simon Pilgrimca140b12016-05-01 20:43:02 +0000951 auto *VecTy = cast<VectorType>(II.getType());
952 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000953 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +0000954 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
955 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000956
Simon Pilgrimca140b12016-05-01 20:43:02 +0000957 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +0000958 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000959
960 for (unsigned I = 0; I < Size; ++I) {
961 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +0000962 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000963 return nullptr;
964
Simon Pilgrimca140b12016-05-01 20:43:02 +0000965 if (isa<UndefValue>(COp)) {
966 Indexes[I] = UndefValue::get(MaskEltTy);
967 continue;
968 }
969
Craig Toppere3280452016-12-25 23:58:57 +0000970 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
971 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +0000972 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000973 }
974
Simon Pilgrimca140b12016-05-01 20:43:02 +0000975 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000976 auto V1 = II.getArgOperand(0);
977 auto V2 = UndefValue::get(VecTy);
978 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
979}
980
Sanjay Patelccf5f242015-03-20 21:47:56 +0000981/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
982/// source vectors, unless a zero bit is set. If a zero bit is set,
983/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000984static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000985 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000986 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
987 if (!CInt)
988 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000989
Sanjay Patel03c03f52016-01-28 00:03:16 +0000990 VectorType *VecTy = cast<VectorType>(II.getType());
991 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000992
Sanjay Patel03c03f52016-01-28 00:03:16 +0000993 // The immediate permute control byte looks like this:
994 // [1:0] - select 128 bits from sources for low half of destination
995 // [2] - ignore
996 // [3] - zero low half of destination
997 // [5:4] - select 128 bits from sources for high half of destination
998 // [6] - ignore
999 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001000
Sanjay Patel03c03f52016-01-28 00:03:16 +00001001 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001002
Sanjay Patel03c03f52016-01-28 00:03:16 +00001003 bool LowHalfZero = Imm & 0x08;
1004 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001005
Sanjay Patel03c03f52016-01-28 00:03:16 +00001006 // If both zero mask bits are set, this was just a weird way to
1007 // generate a zero vector.
1008 if (LowHalfZero && HighHalfZero)
1009 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001010
Sanjay Patel03c03f52016-01-28 00:03:16 +00001011 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
1012 unsigned NumElts = VecTy->getNumElements();
1013 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +00001014 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001015
Sanjay Patel03c03f52016-01-28 00:03:16 +00001016 // The high bit of the selection field chooses the 1st or 2nd operand.
1017 bool LowInputSelect = Imm & 0x02;
1018 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001019
Sanjay Patel03c03f52016-01-28 00:03:16 +00001020 // The low bit of the selection field chooses the low or high half
1021 // of the selected operand.
1022 bool LowHalfSelect = Imm & 0x01;
1023 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001024
Sanjay Patel03c03f52016-01-28 00:03:16 +00001025 // Determine which operand(s) are actually in use for this instruction.
1026 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
1027 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001028
Sanjay Patel03c03f52016-01-28 00:03:16 +00001029 // If needed, replace operands based on zero mask.
1030 V0 = LowHalfZero ? ZeroVector : V0;
1031 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001032
Sanjay Patel03c03f52016-01-28 00:03:16 +00001033 // Permute low half of result.
1034 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
1035 for (unsigned i = 0; i < HalfSize; ++i)
1036 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001037
Sanjay Patel03c03f52016-01-28 00:03:16 +00001038 // Permute high half of result.
1039 StartIndex = HighHalfSelect ? HalfSize : 0;
1040 StartIndex += NumElts;
1041 for (unsigned i = 0; i < HalfSize; ++i)
1042 ShuffleMask[i + HalfSize] = StartIndex + i;
1043
1044 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +00001045}
1046
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001047/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001048static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001049 InstCombiner::BuilderTy &Builder,
1050 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001051 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1052 uint64_t Imm = CInt->getZExtValue() & 0x7;
1053 VectorType *VecTy = cast<VectorType>(II.getType());
1054 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1055
1056 switch (Imm) {
1057 case 0x0:
1058 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1059 break;
1060 case 0x1:
1061 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1062 break;
1063 case 0x2:
1064 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1065 break;
1066 case 0x3:
1067 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1068 break;
1069 case 0x4:
1070 Pred = ICmpInst::ICMP_EQ; break;
1071 case 0x5:
1072 Pred = ICmpInst::ICMP_NE; break;
1073 case 0x6:
1074 return ConstantInt::getSigned(VecTy, 0); // FALSE
1075 case 0x7:
1076 return ConstantInt::getSigned(VecTy, -1); // TRUE
1077 }
1078
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001079 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1080 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001081 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1082 }
1083 return nullptr;
1084}
1085
Craig Toppere3280452016-12-25 23:58:57 +00001086// Emit a select instruction and appropriate bitcasts to help simplify
1087// masked intrinsics.
1088static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1089 InstCombiner::BuilderTy &Builder) {
Craig Topper99163632016-12-30 23:06:28 +00001090 unsigned VWidth = Op0->getType()->getVectorNumElements();
1091
1092 // If the mask is all ones we don't need the select. But we need to check
1093 // only the bit thats will be used in case VWidth is less than 8.
1094 if (auto *C = dyn_cast<ConstantInt>(Mask))
1095 if (C->getValue().zextOrTrunc(VWidth).isAllOnesValue())
1096 return Op0;
1097
Craig Toppere3280452016-12-25 23:58:57 +00001098 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1099 cast<IntegerType>(Mask->getType())->getBitWidth());
1100 Mask = Builder.CreateBitCast(Mask, MaskTy);
1101
1102 // If we have less than 8 elements, then the starting mask was an i8 and
1103 // we need to extract down to the right number of elements.
Craig Toppere3280452016-12-25 23:58:57 +00001104 if (VWidth < 8) {
1105 uint32_t Indices[4];
1106 for (unsigned i = 0; i != VWidth; ++i)
1107 Indices[i] = i;
1108 Mask = Builder.CreateShuffleVector(Mask, Mask,
1109 makeArrayRef(Indices, VWidth),
1110 "extract");
1111 }
1112
1113 return Builder.CreateSelect(Mask, Op0, Op1);
1114}
1115
Sanjay Patel0069f562016-01-31 16:35:23 +00001116static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1117 Value *Arg0 = II.getArgOperand(0);
1118 Value *Arg1 = II.getArgOperand(1);
1119
1120 // fmin(x, x) -> x
1121 if (Arg0 == Arg1)
1122 return Arg0;
1123
1124 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1125
1126 // fmin(x, nan) -> x
1127 if (C1 && C1->isNaN())
1128 return Arg0;
1129
1130 // This is the value because if undef were NaN, we would return the other
1131 // value and cannot return a NaN unless both operands are.
1132 //
1133 // fmin(undef, x) -> x
1134 if (isa<UndefValue>(Arg0))
1135 return Arg1;
1136
1137 // fmin(x, undef) -> x
1138 if (isa<UndefValue>(Arg1))
1139 return Arg0;
1140
1141 Value *X = nullptr;
1142 Value *Y = nullptr;
1143 if (II.getIntrinsicID() == Intrinsic::minnum) {
1144 // fmin(x, fmin(x, y)) -> fmin(x, y)
1145 // fmin(y, fmin(x, y)) -> fmin(x, y)
1146 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1147 if (Arg0 == X || Arg0 == Y)
1148 return Arg1;
1149 }
1150
1151 // fmin(fmin(x, y), x) -> fmin(x, y)
1152 // fmin(fmin(x, y), y) -> fmin(x, y)
1153 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1154 if (Arg1 == X || Arg1 == Y)
1155 return Arg0;
1156 }
1157
1158 // TODO: fmin(nnan x, inf) -> x
1159 // TODO: fmin(nnan ninf x, flt_max) -> x
1160 if (C1 && C1->isInfinity()) {
1161 // fmin(x, -inf) -> -inf
1162 if (C1->isNegative())
1163 return Arg1;
1164 }
1165 } else {
1166 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1167 // fmax(x, fmax(x, y)) -> fmax(x, y)
1168 // fmax(y, fmax(x, y)) -> fmax(x, y)
1169 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1170 if (Arg0 == X || Arg0 == Y)
1171 return Arg1;
1172 }
1173
1174 // fmax(fmax(x, y), x) -> fmax(x, y)
1175 // fmax(fmax(x, y), y) -> fmax(x, y)
1176 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1177 if (Arg1 == X || Arg1 == Y)
1178 return Arg0;
1179 }
1180
1181 // TODO: fmax(nnan x, -inf) -> x
1182 // TODO: fmax(nnan ninf x, -flt_max) -> x
1183 if (C1 && C1->isInfinity()) {
1184 // fmax(x, inf) -> inf
1185 if (!C1->isNegative())
1186 return Arg1;
1187 }
1188 }
1189 return nullptr;
1190}
1191
David Majnemer666aa942016-07-14 06:58:42 +00001192static bool maskIsAllOneOrUndef(Value *Mask) {
1193 auto *ConstMask = dyn_cast<Constant>(Mask);
1194 if (!ConstMask)
1195 return false;
1196 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1197 return true;
1198 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1199 ++I) {
1200 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1201 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1202 continue;
1203 return false;
1204 }
1205 return true;
1206}
1207
Sanjay Patelb695c552016-02-01 17:00:10 +00001208static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1209 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001210 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1211 // argument.
1212 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001213 Value *LoadPtr = II.getArgOperand(0);
1214 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1215 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1216 }
1217
1218 return nullptr;
1219}
1220
Sanjay Patel04f792b2016-02-01 19:39:52 +00001221static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1222 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1223 if (!ConstMask)
1224 return nullptr;
1225
1226 // If the mask is all zeros, this instruction does nothing.
1227 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001228 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001229
1230 // If the mask is all ones, this is a plain vector store of the 1st argument.
1231 if (ConstMask->isAllOnesValue()) {
1232 Value *StorePtr = II.getArgOperand(1);
1233 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1234 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1235 }
1236
1237 return nullptr;
1238}
1239
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001240static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1241 // If the mask is all zeros, return the "passthru" argument of the gather.
1242 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1243 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001244 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001245
1246 return nullptr;
1247}
1248
1249static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1250 // If the mask is all zeros, a scatter does nothing.
1251 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1252 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001253 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001254
1255 return nullptr;
1256}
1257
Amaury Sechet763c59d2016-08-18 20:43:50 +00001258static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1259 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1260 II.getIntrinsicID() == Intrinsic::ctlz) &&
1261 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001262 Value *Op0 = II.getArgOperand(0);
1263 // FIXME: Try to simplify vectors of integers.
1264 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1265 if (!IT)
1266 return nullptr;
1267
1268 unsigned BitWidth = IT->getBitWidth();
1269 APInt KnownZero(BitWidth, 0);
1270 APInt KnownOne(BitWidth, 0);
1271 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1272
1273 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1274 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1275 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1276 : KnownOne.countLeadingZeros();
1277 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1278 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1279
1280 // If all bits above (ctlz) or below (cttz) the first known one are known
1281 // zero, this value is constant.
1282 // FIXME: This should be in InstSimplify because we're replacing an
1283 // instruction with a constant.
Amaury Sechet763c59d2016-08-18 20:43:50 +00001284 if ((Mask & KnownZero) == Mask) {
1285 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1286 return IC.replaceInstUsesWith(II, C);
1287 }
1288
1289 // If the input to cttz/ctlz is known to be non-zero,
1290 // then change the 'ZeroIsUndef' parameter to 'true'
1291 // because we know the zero behavior can't affect the result.
1292 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1293 if (!match(II.getArgOperand(1), m_One())) {
1294 II.setOperand(1, IC.Builder->getTrue());
1295 return &II;
1296 }
1297 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001298
1299 return nullptr;
1300}
1301
Sanjay Patel1ace9932016-02-26 21:04:14 +00001302// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1303// XMM register mask efficiently, we could transform all x86 masked intrinsics
1304// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001305static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1306 Value *Ptr = II.getOperand(0);
1307 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001308 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001309
1310 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001311 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001312 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001313 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001314
1315 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1316 if (!ConstMask)
1317 return nullptr;
1318
1319 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1320 // to allow target-independent optimizations.
1321
1322 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1323 // the LLVM intrinsic definition for the pointer argument.
1324 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1325 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1326 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1327
1328 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1329 // on each element's most significant bit (the sign bit).
1330 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1331
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001332 // The pass-through vector for an x86 masked load is a zero vector.
1333 CallInst *NewMaskedLoad =
1334 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001335 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1336}
1337
1338// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1339// XMM register mask efficiently, we could transform all x86 masked intrinsics
1340// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001341static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1342 Value *Ptr = II.getOperand(0);
1343 Value *Mask = II.getOperand(1);
1344 Value *Vec = II.getOperand(2);
1345
1346 // Special case a zero mask since that's not a ConstantDataVector:
1347 // this masked store instruction does nothing.
1348 if (isa<ConstantAggregateZero>(Mask)) {
1349 IC.eraseInstFromFunction(II);
1350 return true;
1351 }
1352
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001353 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1354 // anything else at this level.
1355 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1356 return false;
1357
Sanjay Patel1ace9932016-02-26 21:04:14 +00001358 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1359 if (!ConstMask)
1360 return false;
1361
1362 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1363 // to allow target-independent optimizations.
1364
1365 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1366 // the LLVM intrinsic definition for the pointer argument.
1367 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1368 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001369 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1370
1371 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1372 // on each element's most significant bit (the sign bit).
1373 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1374
1375 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1376
1377 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1378 IC.eraseInstFromFunction(II);
1379 return true;
1380}
1381
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001382// Returns true iff the 2 intrinsics have the same operands, limiting the
1383// comparison to the first NumOperands.
1384static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1385 unsigned NumOperands) {
1386 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1387 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1388 for (unsigned i = 0; i < NumOperands; i++)
1389 if (I.getArgOperand(i) != E.getArgOperand(i))
1390 return false;
1391 return true;
1392}
1393
1394// Remove trivially empty start/end intrinsic ranges, i.e. a start
1395// immediately followed by an end (ignoring debuginfo or other
1396// start/end intrinsics in between). As this handles only the most trivial
1397// cases, tracking the nesting level is not needed:
1398//
1399// call @llvm.foo.start(i1 0) ; &I
1400// call @llvm.foo.start(i1 0)
1401// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1402// call @llvm.foo.end(i1 0)
1403static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1404 unsigned EndID, InstCombiner &IC) {
1405 assert(I.getIntrinsicID() == StartID &&
1406 "Start intrinsic does not have expected ID");
1407 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1408 for (++BI; BI != BE; ++BI) {
1409 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1410 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1411 continue;
1412 if (E->getIntrinsicID() == EndID &&
1413 haveSameOperands(I, *E, E->getNumArgOperands())) {
1414 IC.eraseInstFromFunction(*E);
1415 IC.eraseInstFromFunction(I);
1416 return true;
1417 }
1418 }
1419 break;
1420 }
1421
1422 return false;
1423}
1424
1425Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1426 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1427 return nullptr;
1428}
1429
1430Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1431 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1432 return nullptr;
1433}
1434
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001435/// CallInst simplification. This mostly only handles folding of intrinsic
1436/// instructions. For normal calls, it allows visitCallSite to do the heavy
1437/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001438Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001439 auto Args = CI.arg_operands();
1440 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001441 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001442 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001443
Justin Bogner99798402016-08-05 01:06:44 +00001444 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001445 return visitFree(CI);
1446
1447 // If the caller function is nounwind, mark the call as nounwind, even if the
1448 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001449 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001450 CI.setDoesNotThrow();
1451 return &CI;
1452 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001453
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001454 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1455 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001456
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001457 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1458 // visitCallSite.
1459 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1460 bool Changed = false;
1461
1462 // memmove/cpy/set of zero bytes is a noop.
1463 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001464 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001465 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001466
1467 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1468 if (CI->getZExtValue() == 1) {
1469 // Replace the instruction with just byte operations. We would
1470 // transform other cases to loads/stores, but we don't know if
1471 // alignment is sufficient.
1472 }
1473 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001474
Chris Lattnerc663a672010-10-01 05:51:02 +00001475 // No other transformations apply to volatile transfers.
1476 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001477 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001478
1479 // If we have a memmove and the source operation is a constant global,
1480 // then the source and dest pointers can't alias, so we can change this
1481 // into a call to memcpy.
1482 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1483 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1484 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001485 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001486 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001487 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1488 CI.getArgOperand(1)->getType(),
1489 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001490 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001491 Changed = true;
1492 }
1493 }
1494
1495 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1496 // memmove(x,x,size) -> noop.
1497 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001498 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001499 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001500
Eric Christopher7258dcd2010-04-16 23:37:20 +00001501 // If we can determine a pointer alignment that is bigger than currently
1502 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001503 if (isa<MemTransferInst>(MI)) {
1504 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001505 return I;
1506 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1507 if (Instruction *I = SimplifyMemSet(MSI))
1508 return I;
1509 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001510
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001511 if (Changed) return II;
1512 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001513
Sanjay Patel1c600c62016-01-20 16:41:43 +00001514 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1515 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001516 APInt UndefElts(Width, 0);
1517 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1518 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1519 };
1520
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001521 switch (II->getIntrinsicID()) {
1522 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001523 case Intrinsic::objectsize:
1524 if (ConstantInt *N =
1525 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1526 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001527 return nullptr;
George Burgess IV3f089142016-12-20 23:46:36 +00001528
Michael Ilseman536cc322012-12-13 03:13:36 +00001529 case Intrinsic::bswap: {
1530 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001531 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001532
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001533 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001534 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001535 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001536
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001537 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001538 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1539 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1540 IIOperand->getType()->getPrimitiveSizeInBits();
1541 Value *CV = ConstantInt::get(X->getType(), C);
1542 Value *V = Builder->CreateLShr(X, CV);
1543 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001544 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001545 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001546 }
1547
James Molloy2d09c002015-11-12 12:39:41 +00001548 case Intrinsic::bitreverse: {
1549 Value *IIOperand = II->getArgOperand(0);
1550 Value *X = nullptr;
1551
1552 // bitreverse(bitreverse(x)) -> x
1553 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001554 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001555 break;
1556 }
1557
Sanjay Patelb695c552016-02-01 17:00:10 +00001558 case Intrinsic::masked_load:
1559 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001560 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001561 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001562 case Intrinsic::masked_store:
1563 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001564 case Intrinsic::masked_gather:
1565 return simplifyMaskedGather(*II, *this);
1566 case Intrinsic::masked_scatter:
1567 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001568
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001569 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001570 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001571 // powi(x, 0) -> 1.0
1572 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001573 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001574 // powi(x, 1) -> x
1575 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001576 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001577 // powi(x, -1) -> 1/x
1578 if (Power->isAllOnesValue())
1579 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001580 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001581 }
1582 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001583
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001584 case Intrinsic::cttz:
1585 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001586 if (auto *I = foldCttzCtlz(*II, *this))
1587 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001588 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001589
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001590 case Intrinsic::uadd_with_overflow:
1591 case Intrinsic::sadd_with_overflow:
1592 case Intrinsic::umul_with_overflow:
1593 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001594 if (isa<Constant>(II->getArgOperand(0)) &&
1595 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001596 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001597 Value *LHS = II->getArgOperand(0);
1598 II->setArgOperand(0, II->getArgOperand(1));
1599 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001600 return II;
1601 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001602 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001603
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001604 case Intrinsic::usub_with_overflow:
1605 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001606 OverflowCheckFlavor OCF =
1607 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1608 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001609
Sanjoy Dasb0984472015-04-08 04:27:22 +00001610 Value *OperationResult = nullptr;
1611 Constant *OverflowResult = nullptr;
1612 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1613 *II, OperationResult, OverflowResult))
1614 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001615
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001616 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001617 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001618
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001619 case Intrinsic::minnum:
1620 case Intrinsic::maxnum: {
1621 Value *Arg0 = II->getArgOperand(0);
1622 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001623 // Canonicalize constants to the RHS.
1624 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001625 II->setArgOperand(0, Arg1);
1626 II->setArgOperand(1, Arg0);
1627 return II;
1628 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001629 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001630 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001631 break;
1632 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001633 case Intrinsic::fma:
1634 case Intrinsic::fmuladd: {
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001635 Value *Src0 = II->getArgOperand(0);
1636 Value *Src1 = II->getArgOperand(1);
1637
Matt Arsenaultb264c942017-01-03 04:32:35 +00001638 // Canonicalize constants into the RHS.
1639 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
1640 II->setArgOperand(0, Src1);
1641 II->setArgOperand(1, Src0);
1642 std::swap(Src0, Src1);
1643 }
1644
1645 Value *LHS = nullptr;
1646 Value *RHS = nullptr;
1647
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001648 // fma fneg(x), fneg(y), z -> fma x, y, z
1649 if (match(Src0, m_FNeg(m_Value(LHS))) &&
1650 match(Src1, m_FNeg(m_Value(RHS)))) {
Matt Arsenault3f509042017-01-10 23:17:52 +00001651 II->setArgOperand(0, LHS);
1652 II->setArgOperand(1, RHS);
1653 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001654 }
1655
1656 // fma fabs(x), fabs(x), z -> fma x, x, z
1657 if (match(Src0, m_Intrinsic<Intrinsic::fabs>(m_Value(LHS))) &&
1658 match(Src1, m_Intrinsic<Intrinsic::fabs>(m_Value(RHS))) && LHS == RHS) {
Matt Arsenault3f509042017-01-10 23:17:52 +00001659 II->setArgOperand(0, LHS);
1660 II->setArgOperand(1, RHS);
1661 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001662 }
1663
Matt Arsenaultb264c942017-01-03 04:32:35 +00001664 // fma x, 1, z -> fadd x, z
1665 if (match(Src1, m_FPOne())) {
1666 Instruction *RI = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
1667 RI->copyFastMathFlags(II);
1668 return RI;
1669 }
1670
Matt Arsenault1cc294c2017-01-03 04:32:31 +00001671 break;
1672 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00001673 case Intrinsic::fabs: {
1674 Value *Cond;
1675 Constant *LHS, *RHS;
1676 if (match(II->getArgOperand(0),
1677 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
1678 CallInst *Call0 = Builder->CreateCall(II->getCalledFunction(), {LHS});
1679 CallInst *Call1 = Builder->CreateCall(II->getCalledFunction(), {RHS});
1680 return SelectInst::Create(Cond, Call0, Call1);
1681 }
1682
Matt Arsenault954a6242017-01-23 23:55:08 +00001683 LLVM_FALLTHROUGH;
1684 }
1685 case Intrinsic::ceil:
1686 case Intrinsic::floor:
1687 case Intrinsic::round:
1688 case Intrinsic::nearbyint:
1689 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00001690 Value *ExtSrc;
1691 if (match(II->getArgOperand(0), m_FPExt(m_Value(ExtSrc))) &&
1692 II->getArgOperand(0)->hasOneUse()) {
1693 // fabs (fpext x) -> fpext (fabs x)
Matt Arsenault954a6242017-01-23 23:55:08 +00001694 Value *F = Intrinsic::getDeclaration(II->getModule(), II->getIntrinsicID(),
Matt Arsenault72333442017-01-17 00:10:40 +00001695 { ExtSrc->getType() });
1696 CallInst *NewFabs = Builder->CreateCall(F, ExtSrc);
1697 NewFabs->copyFastMathFlags(II);
1698 NewFabs->takeName(II);
1699 return new FPExtInst(NewFabs, II->getType());
1700 }
1701
Matt Arsenault56ff4832017-01-03 22:40:34 +00001702 break;
1703 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00001704 case Intrinsic::cos:
1705 case Intrinsic::amdgcn_cos: {
1706 Value *SrcSrc;
1707 Value *Src = II->getArgOperand(0);
1708 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
1709 match(Src, m_Intrinsic<Intrinsic::fabs>(m_Value(SrcSrc)))) {
1710 // cos(-x) -> cos(x)
1711 // cos(fabs(x)) -> cos(x)
1712 II->setArgOperand(0, SrcSrc);
1713 return II;
1714 }
1715
1716 break;
1717 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001718 case Intrinsic::ppc_altivec_lvx:
1719 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001720 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001721 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001722 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001723 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001724 PointerType::getUnqual(II->getType()));
1725 return new LoadInst(Ptr);
1726 }
1727 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001728 case Intrinsic::ppc_vsx_lxvw4x:
1729 case Intrinsic::ppc_vsx_lxvd2x: {
1730 // Turn PPC VSX loads into normal loads.
1731 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1732 PointerType::getUnqual(II->getType()));
1733 return new LoadInst(Ptr, Twine(""), false, 1);
1734 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001735 case Intrinsic::ppc_altivec_stvx:
1736 case Intrinsic::ppc_altivec_stvxl:
1737 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001738 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001739 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001740 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001741 PointerType::getUnqual(II->getArgOperand(0)->getType());
1742 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1743 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001744 }
1745 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001746 case Intrinsic::ppc_vsx_stxvw4x:
1747 case Intrinsic::ppc_vsx_stxvd2x: {
1748 // Turn PPC VSX stores into normal stores.
1749 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1750 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1751 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1752 }
Hal Finkel221f4672015-02-26 18:56:03 +00001753 case Intrinsic::ppc_qpx_qvlfs:
1754 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001755 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001756 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001757 Type *VTy = VectorType::get(Builder->getFloatTy(),
1758 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001759 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001760 PointerType::getUnqual(VTy));
1761 Value *Load = Builder->CreateLoad(Ptr);
1762 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001763 }
1764 break;
1765 case Intrinsic::ppc_qpx_qvlfd:
1766 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001767 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001768 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001769 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1770 PointerType::getUnqual(II->getType()));
1771 return new LoadInst(Ptr);
1772 }
1773 break;
1774 case Intrinsic::ppc_qpx_qvstfs:
1775 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001776 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001777 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001778 Type *VTy = VectorType::get(Builder->getFloatTy(),
1779 II->getArgOperand(0)->getType()->getVectorNumElements());
1780 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1781 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001782 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001783 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001784 }
1785 break;
1786 case Intrinsic::ppc_qpx_qvstfd:
1787 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001788 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001789 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001790 Type *OpPtrTy =
1791 PointerType::getUnqual(II->getArgOperand(0)->getType());
1792 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1793 return new StoreInst(II->getArgOperand(0), Ptr);
1794 }
1795 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001796
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001797 case Intrinsic::x86_vcvtph2ps_128:
1798 case Intrinsic::x86_vcvtph2ps_256: {
1799 auto Arg = II->getArgOperand(0);
1800 auto ArgType = cast<VectorType>(Arg->getType());
1801 auto RetType = cast<VectorType>(II->getType());
1802 unsigned ArgWidth = ArgType->getNumElements();
1803 unsigned RetWidth = RetType->getNumElements();
1804 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1805 assert(ArgType->isIntOrIntVectorTy() &&
1806 ArgType->getScalarSizeInBits() == 16 &&
1807 "CVTPH2PS input type should be 16-bit integer vector");
1808 assert(RetType->getScalarType()->isFloatTy() &&
1809 "CVTPH2PS output type should be 32-bit float vector");
1810
1811 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001812 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001813 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001814
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001815 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001816 auto VectorHalfAsShorts = Arg;
1817 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00001818 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001819 for (unsigned i = 0; i != RetWidth; ++i)
1820 SubVecMask.push_back((int)i);
1821 VectorHalfAsShorts = Builder->CreateShuffleVector(
1822 Arg, UndefValue::get(ArgType), SubVecMask);
1823 }
1824
1825 auto VectorHalfType =
1826 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1827 auto VectorHalfs =
1828 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1829 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001830 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001831 }
1832
1833 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001834 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001835 II->setArgOperand(0, V);
1836 return II;
1837 }
1838 break;
1839 }
1840
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001841 case Intrinsic::x86_sse_cvtss2si:
1842 case Intrinsic::x86_sse_cvtss2si64:
1843 case Intrinsic::x86_sse_cvttss2si:
1844 case Intrinsic::x86_sse_cvttss2si64:
1845 case Intrinsic::x86_sse2_cvtsd2si:
1846 case Intrinsic::x86_sse2_cvtsd2si64:
1847 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00001848 case Intrinsic::x86_sse2_cvttsd2si64:
1849 case Intrinsic::x86_avx512_vcvtss2si32:
1850 case Intrinsic::x86_avx512_vcvtss2si64:
1851 case Intrinsic::x86_avx512_vcvtss2usi32:
1852 case Intrinsic::x86_avx512_vcvtss2usi64:
1853 case Intrinsic::x86_avx512_vcvtsd2si32:
1854 case Intrinsic::x86_avx512_vcvtsd2si64:
1855 case Intrinsic::x86_avx512_vcvtsd2usi32:
1856 case Intrinsic::x86_avx512_vcvtsd2usi64:
1857 case Intrinsic::x86_avx512_cvttss2si:
1858 case Intrinsic::x86_avx512_cvttss2si64:
1859 case Intrinsic::x86_avx512_cvttss2usi:
1860 case Intrinsic::x86_avx512_cvttss2usi64:
1861 case Intrinsic::x86_avx512_cvttsd2si:
1862 case Intrinsic::x86_avx512_cvttsd2si64:
1863 case Intrinsic::x86_avx512_cvttsd2usi:
1864 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001865 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001866 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001867 Value *Arg = II->getArgOperand(0);
1868 unsigned VWidth = Arg->getType()->getVectorNumElements();
1869 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001870 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001871 return II;
1872 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001873 break;
1874 }
1875
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00001876 case Intrinsic::x86_mmx_pmovmskb:
1877 case Intrinsic::x86_sse_movmsk_ps:
1878 case Intrinsic::x86_sse2_movmsk_pd:
1879 case Intrinsic::x86_sse2_pmovmskb_128:
1880 case Intrinsic::x86_avx_movmsk_pd_256:
1881 case Intrinsic::x86_avx_movmsk_ps_256:
1882 case Intrinsic::x86_avx2_pmovmskb: {
1883 if (Value *V = simplifyX86movmsk(*II, *Builder))
1884 return replaceInstUsesWith(*II, V);
1885 break;
1886 }
1887
Simon Pilgrim471efd22016-02-20 23:17:35 +00001888 case Intrinsic::x86_sse_comieq_ss:
1889 case Intrinsic::x86_sse_comige_ss:
1890 case Intrinsic::x86_sse_comigt_ss:
1891 case Intrinsic::x86_sse_comile_ss:
1892 case Intrinsic::x86_sse_comilt_ss:
1893 case Intrinsic::x86_sse_comineq_ss:
1894 case Intrinsic::x86_sse_ucomieq_ss:
1895 case Intrinsic::x86_sse_ucomige_ss:
1896 case Intrinsic::x86_sse_ucomigt_ss:
1897 case Intrinsic::x86_sse_ucomile_ss:
1898 case Intrinsic::x86_sse_ucomilt_ss:
1899 case Intrinsic::x86_sse_ucomineq_ss:
1900 case Intrinsic::x86_sse2_comieq_sd:
1901 case Intrinsic::x86_sse2_comige_sd:
1902 case Intrinsic::x86_sse2_comigt_sd:
1903 case Intrinsic::x86_sse2_comile_sd:
1904 case Intrinsic::x86_sse2_comilt_sd:
1905 case Intrinsic::x86_sse2_comineq_sd:
1906 case Intrinsic::x86_sse2_ucomieq_sd:
1907 case Intrinsic::x86_sse2_ucomige_sd:
1908 case Intrinsic::x86_sse2_ucomigt_sd:
1909 case Intrinsic::x86_sse2_ucomile_sd:
1910 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00001911 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00001912 case Intrinsic::x86_avx512_vcomi_ss:
1913 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00001914 case Intrinsic::x86_avx512_mask_cmp_ss:
1915 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00001916 // These intrinsics only demand the 0th element of their input vectors. If
1917 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001918 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001919 Value *Arg0 = II->getArgOperand(0);
1920 Value *Arg1 = II->getArgOperand(1);
1921 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1922 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1923 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001924 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001925 }
1926 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1927 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001928 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001929 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001930 if (MadeChange)
1931 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001932 break;
1933 }
1934
Craig Topper020b2282016-12-27 00:23:16 +00001935 case Intrinsic::x86_avx512_mask_add_ps_512:
1936 case Intrinsic::x86_avx512_mask_div_ps_512:
1937 case Intrinsic::x86_avx512_mask_mul_ps_512:
1938 case Intrinsic::x86_avx512_mask_sub_ps_512:
1939 case Intrinsic::x86_avx512_mask_add_pd_512:
1940 case Intrinsic::x86_avx512_mask_div_pd_512:
1941 case Intrinsic::x86_avx512_mask_mul_pd_512:
1942 case Intrinsic::x86_avx512_mask_sub_pd_512:
1943 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
1944 // IR operations.
1945 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
1946 if (R->getValue() == 4) {
1947 Value *Arg0 = II->getArgOperand(0);
1948 Value *Arg1 = II->getArgOperand(1);
1949
1950 Value *V;
1951 switch (II->getIntrinsicID()) {
1952 default: llvm_unreachable("Case stmts out of sync!");
1953 case Intrinsic::x86_avx512_mask_add_ps_512:
1954 case Intrinsic::x86_avx512_mask_add_pd_512:
1955 V = Builder->CreateFAdd(Arg0, Arg1);
1956 break;
1957 case Intrinsic::x86_avx512_mask_sub_ps_512:
1958 case Intrinsic::x86_avx512_mask_sub_pd_512:
1959 V = Builder->CreateFSub(Arg0, Arg1);
1960 break;
1961 case Intrinsic::x86_avx512_mask_mul_ps_512:
1962 case Intrinsic::x86_avx512_mask_mul_pd_512:
1963 V = Builder->CreateFMul(Arg0, Arg1);
1964 break;
1965 case Intrinsic::x86_avx512_mask_div_ps_512:
1966 case Intrinsic::x86_avx512_mask_div_pd_512:
1967 V = Builder->CreateFDiv(Arg0, Arg1);
1968 break;
1969 }
1970
1971 // Create a select for the masking.
1972 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
1973 *Builder);
1974 return replaceInstUsesWith(*II, V);
1975 }
1976 }
1977 break;
1978
Craig Topper790d0fa2016-12-11 07:42:01 +00001979 case Intrinsic::x86_avx512_mask_add_ss_round:
1980 case Intrinsic::x86_avx512_mask_div_ss_round:
1981 case Intrinsic::x86_avx512_mask_mul_ss_round:
1982 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00001983 case Intrinsic::x86_avx512_mask_add_sd_round:
1984 case Intrinsic::x86_avx512_mask_div_sd_round:
1985 case Intrinsic::x86_avx512_mask_mul_sd_round:
1986 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00001987 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
1988 // IR operations.
1989 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
1990 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00001991 // Extract the element as scalars.
1992 Value *Arg0 = II->getArgOperand(0);
1993 Value *Arg1 = II->getArgOperand(1);
1994 Value *LHS = Builder->CreateExtractElement(Arg0, (uint64_t)0);
1995 Value *RHS = Builder->CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00001996
Craig Topper7f8540b2016-12-27 01:56:30 +00001997 Value *V;
1998 switch (II->getIntrinsicID()) {
1999 default: llvm_unreachable("Case stmts out of sync!");
2000 case Intrinsic::x86_avx512_mask_add_ss_round:
2001 case Intrinsic::x86_avx512_mask_add_sd_round:
2002 V = Builder->CreateFAdd(LHS, RHS);
2003 break;
2004 case Intrinsic::x86_avx512_mask_sub_ss_round:
2005 case Intrinsic::x86_avx512_mask_sub_sd_round:
2006 V = Builder->CreateFSub(LHS, RHS);
2007 break;
2008 case Intrinsic::x86_avx512_mask_mul_ss_round:
2009 case Intrinsic::x86_avx512_mask_mul_sd_round:
2010 V = Builder->CreateFMul(LHS, RHS);
2011 break;
2012 case Intrinsic::x86_avx512_mask_div_ss_round:
2013 case Intrinsic::x86_avx512_mask_div_sd_round:
2014 V = Builder->CreateFDiv(LHS, RHS);
2015 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002016 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002017
2018 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002019 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002020 auto *C = dyn_cast<ConstantInt>(Mask);
2021 // We don't need a select if we know the mask bit is a 1.
2022 if (!C || !C->getValue()[0]) {
2023 // Cast the mask to an i1 vector and then extract the lowest element.
2024 auto *MaskTy = VectorType::get(Builder->getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002025 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topper99163632016-12-30 23:06:28 +00002026 Mask = Builder->CreateBitCast(Mask, MaskTy);
2027 Mask = Builder->CreateExtractElement(Mask, (uint64_t)0);
2028 // Extract the lowest element from the passthru operand.
2029 Value *Passthru = Builder->CreateExtractElement(II->getArgOperand(2),
2030 (uint64_t)0);
2031 V = Builder->CreateSelect(Mask, V, Passthru);
2032 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002033
2034 // Insert the result back into the original argument 0.
2035 V = Builder->CreateInsertElement(Arg0, V, (uint64_t)0);
2036
2037 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002038 }
2039 }
2040 LLVM_FALLTHROUGH;
2041
2042 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2043 case Intrinsic::x86_avx512_mask_max_ss_round:
2044 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002045 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002046 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Topperab5f3552016-12-15 03:49:45 +00002047 case Intrinsic::x86_avx512_mask_vfmadd_ss:
2048 case Intrinsic::x86_avx512_mask_vfmadd_sd:
2049 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
2050 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
2051 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
2052 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
2053 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
2054 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
2055 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
2056 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
Craig Topperdfd268d2016-12-14 05:43:05 +00002057 case Intrinsic::x86_fma_vfmadd_ss:
2058 case Intrinsic::x86_fma_vfmsub_ss:
2059 case Intrinsic::x86_fma_vfnmadd_ss:
2060 case Intrinsic::x86_fma_vfnmsub_ss:
2061 case Intrinsic::x86_fma_vfmadd_sd:
2062 case Intrinsic::x86_fma_vfmsub_sd:
2063 case Intrinsic::x86_fma_vfnmadd_sd:
2064 case Intrinsic::x86_fma_vfnmsub_sd:
Craig Toppera0372de2016-12-14 03:17:27 +00002065 case Intrinsic::x86_sse_cmp_ss:
2066 case Intrinsic::x86_sse_min_ss:
2067 case Intrinsic::x86_sse_max_ss:
2068 case Intrinsic::x86_sse2_cmp_sd:
2069 case Intrinsic::x86_sse2_min_sd:
2070 case Intrinsic::x86_sse2_max_sd:
Craig Toppereb6a20e2016-12-14 03:17:30 +00002071 case Intrinsic::x86_sse41_round_ss:
2072 case Intrinsic::x86_sse41_round_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002073 case Intrinsic::x86_xop_vfrcz_ss:
2074 case Intrinsic::x86_xop_vfrcz_sd: {
2075 unsigned VWidth = II->getType()->getVectorNumElements();
2076 APInt UndefElts(VWidth, 0);
2077 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2078 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2079 if (V != II)
2080 return replaceInstUsesWith(*II, V);
2081 return II;
2082 }
2083 break;
2084 }
2085
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002086 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002087 // Constant fold lshr( <A x Bi>, Ci ).
2088 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002089 case Intrinsic::x86_sse2_psrai_d:
2090 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002091 case Intrinsic::x86_avx2_psrai_d:
2092 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002093 case Intrinsic::x86_avx512_psrai_q_128:
2094 case Intrinsic::x86_avx512_psrai_q_256:
2095 case Intrinsic::x86_avx512_psrai_d_512:
2096 case Intrinsic::x86_avx512_psrai_q_512:
2097 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002098 case Intrinsic::x86_sse2_psrli_d:
2099 case Intrinsic::x86_sse2_psrli_q:
2100 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002101 case Intrinsic::x86_avx2_psrli_d:
2102 case Intrinsic::x86_avx2_psrli_q:
2103 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002104 case Intrinsic::x86_avx512_psrli_d_512:
2105 case Intrinsic::x86_avx512_psrli_q_512:
2106 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002107 case Intrinsic::x86_sse2_pslli_d:
2108 case Intrinsic::x86_sse2_pslli_q:
2109 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002110 case Intrinsic::x86_avx2_pslli_d:
2111 case Intrinsic::x86_avx2_pslli_q:
2112 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002113 case Intrinsic::x86_avx512_pslli_d_512:
2114 case Intrinsic::x86_avx512_pslli_q_512:
2115 case Intrinsic::x86_avx512_pslli_w_512:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002116 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002117 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002118 break;
2119
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002120 case Intrinsic::x86_sse2_psra_d:
2121 case Intrinsic::x86_sse2_psra_w:
2122 case Intrinsic::x86_avx2_psra_d:
2123 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002124 case Intrinsic::x86_avx512_psra_q_128:
2125 case Intrinsic::x86_avx512_psra_q_256:
2126 case Intrinsic::x86_avx512_psra_d_512:
2127 case Intrinsic::x86_avx512_psra_q_512:
2128 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002129 case Intrinsic::x86_sse2_psrl_d:
2130 case Intrinsic::x86_sse2_psrl_q:
2131 case Intrinsic::x86_sse2_psrl_w:
2132 case Intrinsic::x86_avx2_psrl_d:
2133 case Intrinsic::x86_avx2_psrl_q:
2134 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002135 case Intrinsic::x86_avx512_psrl_d_512:
2136 case Intrinsic::x86_avx512_psrl_q_512:
2137 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002138 case Intrinsic::x86_sse2_psll_d:
2139 case Intrinsic::x86_sse2_psll_q:
2140 case Intrinsic::x86_sse2_psll_w:
2141 case Intrinsic::x86_avx2_psll_d:
2142 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002143 case Intrinsic::x86_avx2_psll_w:
2144 case Intrinsic::x86_avx512_psll_d_512:
2145 case Intrinsic::x86_avx512_psll_q_512:
2146 case Intrinsic::x86_avx512_psll_w_512: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002147 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002148 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002149
2150 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2151 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002152 Value *Arg1 = II->getArgOperand(1);
2153 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002154 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002155 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002156
Simon Pilgrim996725e2015-09-19 11:41:53 +00002157 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002158 II->setArgOperand(1, V);
2159 return II;
2160 }
2161 break;
2162 }
2163
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002164 case Intrinsic::x86_avx2_psllv_d:
2165 case Intrinsic::x86_avx2_psllv_d_256:
2166 case Intrinsic::x86_avx2_psllv_q:
2167 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002168 case Intrinsic::x86_avx512_psllv_d_512:
2169 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002170 case Intrinsic::x86_avx512_psllv_w_128:
2171 case Intrinsic::x86_avx512_psllv_w_256:
2172 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002173 case Intrinsic::x86_avx2_psrav_d:
2174 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002175 case Intrinsic::x86_avx512_psrav_q_128:
2176 case Intrinsic::x86_avx512_psrav_q_256:
2177 case Intrinsic::x86_avx512_psrav_d_512:
2178 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002179 case Intrinsic::x86_avx512_psrav_w_128:
2180 case Intrinsic::x86_avx512_psrav_w_256:
2181 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002182 case Intrinsic::x86_avx2_psrlv_d:
2183 case Intrinsic::x86_avx2_psrlv_d_256:
2184 case Intrinsic::x86_avx2_psrlv_q:
2185 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002186 case Intrinsic::x86_avx512_psrlv_d_512:
2187 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002188 case Intrinsic::x86_avx512_psrlv_w_128:
2189 case Intrinsic::x86_avx512_psrlv_w_256:
2190 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002191 if (Value *V = simplifyX86varShift(*II, *Builder))
2192 return replaceInstUsesWith(*II, V);
2193 break;
2194
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002195 case Intrinsic::x86_sse2_pmulu_dq:
2196 case Intrinsic::x86_sse41_pmuldq:
2197 case Intrinsic::x86_avx2_pmul_dq:
Craig Topper72f2d4e2016-12-27 05:30:09 +00002198 case Intrinsic::x86_avx2_pmulu_dq:
2199 case Intrinsic::x86_avx512_pmul_dq_512:
2200 case Intrinsic::x86_avx512_pmulu_dq_512: {
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +00002201 if (Value *V = simplifyX86muldq(*II, *Builder))
Simon Pilgrima50a93f2017-01-20 18:20:30 +00002202 return replaceInstUsesWith(*II, V);
2203
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002204 unsigned VWidth = II->getType()->getVectorNumElements();
2205 APInt UndefElts(VWidth, 0);
2206 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
2207 if (Value *V = SimplifyDemandedVectorElts(II, DemandedElts, UndefElts)) {
2208 if (V != II)
2209 return replaceInstUsesWith(*II, V);
2210 return II;
2211 }
2212 break;
2213 }
2214
Sanjay Patelc86867c2015-04-16 17:52:13 +00002215 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002216 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002217 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002218 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002219
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002220 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002221 Value *Op0 = II->getArgOperand(0);
2222 Value *Op1 = II->getArgOperand(1);
2223 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2224 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002225 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2226 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2227 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002228
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002229 // See if we're dealing with constant values.
2230 Constant *C1 = dyn_cast<Constant>(Op1);
2231 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002232 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002233 : nullptr;
2234 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002235 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002236 : nullptr;
2237
2238 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002239 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002240 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002241
2242 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2243 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002244 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002245 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2246 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002247 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002248 }
2249 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2250 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002251 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002252 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002253 if (MadeChange)
2254 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002255 break;
2256 }
2257
2258 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002259 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2260 // bits of the lower 64-bits. The upper 64-bits are undefined.
2261 Value *Op0 = II->getArgOperand(0);
2262 unsigned VWidth = Op0->getType()->getVectorNumElements();
2263 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2264 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002265
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002266 // See if we're dealing with constant values.
2267 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2268 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2269
2270 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002271 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002272 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002273
2274 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2275 // operand.
2276 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002277 II->setArgOperand(0, V);
2278 return II;
2279 }
2280 break;
2281 }
2282
2283 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002284 Value *Op0 = II->getArgOperand(0);
2285 Value *Op1 = II->getArgOperand(1);
2286 unsigned VWidth = Op0->getType()->getVectorNumElements();
2287 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2288 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2289 Op1->getType()->getVectorNumElements() == 2 &&
2290 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002291
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002292 // See if we're dealing with constant values.
2293 Constant *C1 = dyn_cast<Constant>(Op1);
2294 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002295 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002296 : nullptr;
2297
2298 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2299 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002300 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002301 APInt Len = V11.zextOrTrunc(6);
2302 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002303 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002304 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002305 }
2306
2307 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2308 // operand.
2309 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002310 II->setArgOperand(0, V);
2311 return II;
2312 }
2313 break;
2314 }
2315
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002316 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002317 // INSERTQI: Extract lowest Length bits from lower half of second source and
2318 // insert over first source starting at Index bit. The upper 64-bits are
2319 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002320 Value *Op0 = II->getArgOperand(0);
2321 Value *Op1 = II->getArgOperand(1);
2322 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2323 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002324 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2325 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2326 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002327
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002328 // See if we're dealing with constant values.
2329 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2330 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2331
2332 // Attempt to simplify to a constant or shuffle vector.
2333 if (CILength && CIIndex) {
2334 APInt Len = CILength->getValue().zextOrTrunc(6);
2335 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002336 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002337 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002338 }
2339
2340 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2341 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002342 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002343 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2344 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002345 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002346 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002347 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2348 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002349 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002350 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002351 if (MadeChange)
2352 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002353 break;
2354 }
2355
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002356 case Intrinsic::x86_sse41_pblendvb:
2357 case Intrinsic::x86_sse41_blendvps:
2358 case Intrinsic::x86_sse41_blendvpd:
2359 case Intrinsic::x86_avx_blendv_ps_256:
2360 case Intrinsic::x86_avx_blendv_pd_256:
2361 case Intrinsic::x86_avx2_pblendvb: {
2362 // Convert blendv* to vector selects if the mask is constant.
2363 // This optimization is convoluted because the intrinsic is defined as
2364 // getting a vector of floats or doubles for the ps and pd versions.
2365 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002366
2367 Value *Op0 = II->getArgOperand(0);
2368 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002369 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002370
2371 // fold (blend A, A, Mask) -> A
2372 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002373 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002374
2375 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002376 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002377 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002378
2379 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002380 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2381 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002382 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002383 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002384 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002385 }
2386
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002387 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002388 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002389 case Intrinsic::x86_avx512_pshuf_b_512:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002390 if (Value *V = simplifyX86pshufb(*II, *Builder))
2391 return replaceInstUsesWith(*II, V);
2392 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002393
Rafael Espindolabad3f772014-04-21 22:06:04 +00002394 case Intrinsic::x86_avx_vpermilvar_ps:
2395 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002396 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002397 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002398 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002399 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002400 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2401 return replaceInstUsesWith(*II, V);
2402 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002403
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002404 case Intrinsic::x86_avx2_permd:
2405 case Intrinsic::x86_avx2_permps:
2406 if (Value *V = simplifyX86vpermv(*II, *Builder))
2407 return replaceInstUsesWith(*II, V);
2408 break;
2409
Craig Toppere3280452016-12-25 23:58:57 +00002410 case Intrinsic::x86_avx512_mask_permvar_df_256:
2411 case Intrinsic::x86_avx512_mask_permvar_df_512:
2412 case Intrinsic::x86_avx512_mask_permvar_di_256:
2413 case Intrinsic::x86_avx512_mask_permvar_di_512:
2414 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2415 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2416 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2417 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2418 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2419 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2420 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2421 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2422 case Intrinsic::x86_avx512_mask_permvar_si_256:
2423 case Intrinsic::x86_avx512_mask_permvar_si_512:
2424 if (Value *V = simplifyX86vpermv(*II, *Builder)) {
2425 // We simplified the permuting, now create a select for the masking.
2426 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2427 *Builder);
2428 return replaceInstUsesWith(*II, V);
2429 }
2430 break;
2431
Sanjay Patelccf5f242015-03-20 21:47:56 +00002432 case Intrinsic::x86_avx_vperm2f128_pd_256:
2433 case Intrinsic::x86_avx_vperm2f128_ps_256:
2434 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002435 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002436 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002437 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002438 break;
2439
Sanjay Patel98a71502016-02-29 23:16:48 +00002440 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002441 case Intrinsic::x86_avx_maskload_pd:
2442 case Intrinsic::x86_avx_maskload_ps_256:
2443 case Intrinsic::x86_avx_maskload_pd_256:
2444 case Intrinsic::x86_avx2_maskload_d:
2445 case Intrinsic::x86_avx2_maskload_q:
2446 case Intrinsic::x86_avx2_maskload_d_256:
2447 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002448 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2449 return I;
2450 break;
2451
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002452 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002453 case Intrinsic::x86_avx_maskstore_ps:
2454 case Intrinsic::x86_avx_maskstore_pd:
2455 case Intrinsic::x86_avx_maskstore_ps_256:
2456 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002457 case Intrinsic::x86_avx2_maskstore_d:
2458 case Intrinsic::x86_avx2_maskstore_q:
2459 case Intrinsic::x86_avx2_maskstore_d_256:
2460 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002461 if (simplifyX86MaskedStore(*II, *this))
2462 return nullptr;
2463 break;
2464
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002465 case Intrinsic::x86_xop_vpcomb:
2466 case Intrinsic::x86_xop_vpcomd:
2467 case Intrinsic::x86_xop_vpcomq:
2468 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002469 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002470 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002471 break;
2472
2473 case Intrinsic::x86_xop_vpcomub:
2474 case Intrinsic::x86_xop_vpcomud:
2475 case Intrinsic::x86_xop_vpcomuq:
2476 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002477 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002478 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002479 break;
2480
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002481 case Intrinsic::ppc_altivec_vperm:
2482 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002483 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2484 // a vectorshuffle for little endian, we must undo the transformation
2485 // performed on vec_perm in altivec.h. That is, we must complement
2486 // the permutation mask with respect to 31 and reverse the order of
2487 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002488 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2489 assert(Mask->getType()->getVectorNumElements() == 16 &&
2490 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002491
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002492 // Check that all of the elements are integer constants or undefs.
2493 bool AllEltsOk = true;
2494 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002495 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002496 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002497 AllEltsOk = false;
2498 break;
2499 }
2500 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002501
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002502 if (AllEltsOk) {
2503 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002504 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2505 Mask->getType());
2506 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2507 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002508 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002509
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002510 // Only extract each element once.
2511 Value *ExtractedElts[32];
2512 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002513
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002514 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002515 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002516 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002517 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002518 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002519 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002520 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002521 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002522
Craig Topperf40110f2014-04-25 05:29:35 +00002523 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002524 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2525 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002526 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002527 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002528 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002529 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002530
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002531 // Insert this value into the result vector.
2532 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002533 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002534 }
2535 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2536 }
2537 }
2538 break;
2539
Bob Wilsona4e231c2010-10-22 21:41:48 +00002540 case Intrinsic::arm_neon_vld1:
2541 case Intrinsic::arm_neon_vld2:
2542 case Intrinsic::arm_neon_vld3:
2543 case Intrinsic::arm_neon_vld4:
2544 case Intrinsic::arm_neon_vld2lane:
2545 case Intrinsic::arm_neon_vld3lane:
2546 case Intrinsic::arm_neon_vld4lane:
2547 case Intrinsic::arm_neon_vst1:
2548 case Intrinsic::arm_neon_vst2:
2549 case Intrinsic::arm_neon_vst3:
2550 case Intrinsic::arm_neon_vst4:
2551 case Intrinsic::arm_neon_vst2lane:
2552 case Intrinsic::arm_neon_vst3lane:
2553 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00002554 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002555 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002556 unsigned AlignArg = II->getNumArgOperands() - 1;
2557 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2558 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2559 II->setArgOperand(AlignArg,
2560 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2561 MemAlign, false));
2562 return II;
2563 }
2564 break;
2565 }
2566
Lang Hames3a90fab2012-05-01 00:20:38 +00002567 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00002568 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00002569 case Intrinsic::aarch64_neon_smull:
2570 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00002571 Value *Arg0 = II->getArgOperand(0);
2572 Value *Arg1 = II->getArgOperand(1);
2573
2574 // Handle mul by zero first:
2575 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002576 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00002577 }
2578
2579 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00002580 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00002581 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00002582 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00002583 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2584 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2585 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2586 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2587
Sanjay Patel4b198802016-02-01 22:23:39 +00002588 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00002589 }
2590
Alp Tokercb402912014-01-24 17:20:08 +00002591 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00002592 std::swap(Arg0, Arg1);
2593 }
2594
2595 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00002596 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00002597 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00002598 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2599 if (Splat->isOne())
2600 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2601 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00002602
2603 break;
2604 }
2605
Matt Arsenaultbef34e22016-01-22 21:30:34 +00002606 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002607 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2608 const APFloat &ArgVal = C->getValueAPF();
2609 APFloat Val(ArgVal.getSemantics(), 1.0);
2610 APFloat::opStatus Status = Val.divide(ArgVal,
2611 APFloat::rmNearestTiesToEven);
2612 // Only do this if it was exact and therefore not dependent on the
2613 // rounding mode.
2614 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00002615 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002616 }
2617
2618 break;
2619 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002620 case Intrinsic::amdgcn_frexp_mant:
2621 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002622 Value *Src = II->getArgOperand(0);
2623 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2624 int Exp;
2625 APFloat Significand = frexp(C->getValueAPF(), Exp,
2626 APFloat::rmNearestTiesToEven);
2627
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002628 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2629 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2630 Significand));
2631 }
2632
2633 // Match instruction special case behavior.
2634 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2635 Exp = 0;
2636
2637 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2638 }
2639
2640 if (isa<UndefValue>(Src))
2641 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002642
2643 break;
2644 }
Matt Arsenault46a03822016-09-03 07:06:58 +00002645 case Intrinsic::amdgcn_class: {
2646 enum {
2647 S_NAN = 1 << 0, // Signaling NaN
2648 Q_NAN = 1 << 1, // Quiet NaN
2649 N_INFINITY = 1 << 2, // Negative infinity
2650 N_NORMAL = 1 << 3, // Negative normal
2651 N_SUBNORMAL = 1 << 4, // Negative subnormal
2652 N_ZERO = 1 << 5, // Negative zero
2653 P_ZERO = 1 << 6, // Positive zero
2654 P_SUBNORMAL = 1 << 7, // Positive subnormal
2655 P_NORMAL = 1 << 8, // Positive normal
2656 P_INFINITY = 1 << 9 // Positive infinity
2657 };
2658
2659 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
2660 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
2661
2662 Value *Src0 = II->getArgOperand(0);
2663 Value *Src1 = II->getArgOperand(1);
2664 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
2665 if (!CMask) {
2666 if (isa<UndefValue>(Src0))
2667 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2668
2669 if (isa<UndefValue>(Src1))
2670 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2671 break;
2672 }
2673
2674 uint32_t Mask = CMask->getZExtValue();
2675
2676 // If all tests are made, it doesn't matter what the value is.
2677 if ((Mask & FullMask) == FullMask)
2678 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
2679
2680 if ((Mask & FullMask) == 0)
2681 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2682
2683 if (Mask == (S_NAN | Q_NAN)) {
2684 // Equivalent of isnan. Replace with standard fcmp.
2685 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
2686 FCmp->takeName(II);
2687 return replaceInstUsesWith(*II, FCmp);
2688 }
2689
2690 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
2691 if (!CVal) {
2692 if (isa<UndefValue>(Src0))
2693 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2694
2695 // Clamp mask to used bits
2696 if ((Mask & FullMask) != Mask) {
2697 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
2698 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
2699 );
2700
2701 NewCall->takeName(II);
2702 return replaceInstUsesWith(*II, NewCall);
2703 }
2704
2705 break;
2706 }
2707
2708 const APFloat &Val = CVal->getValueAPF();
2709
2710 bool Result =
2711 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
2712 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
2713 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
2714 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
2715 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
2716 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
2717 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
2718 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
2719 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
2720 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
2721
2722 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
2723 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002724 case Intrinsic::stackrestore: {
2725 // If the save is right next to the restore, remove the restore. This can
2726 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002727 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002728 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002729 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002730 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002731 }
2732 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002733
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002734 // Scan down this block to see if there is another stack restore in the
2735 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002736 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002737 TerminatorInst *TI = II->getParent()->getTerminator();
2738 bool CannotRemove = false;
2739 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002740 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002741 CannotRemove = true;
2742 break;
2743 }
2744 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2745 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2746 // If there is a stackrestore below this one, remove this one.
2747 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002748 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002749
2750 // Bail if we cross over an intrinsic with side effects, such as
2751 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2752 if (II->mayHaveSideEffects()) {
2753 CannotRemove = true;
2754 break;
2755 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002756 } else {
2757 // If we found a non-intrinsic call, we can't remove the stack
2758 // restore.
2759 CannotRemove = true;
2760 break;
2761 }
2762 }
2763 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002764
Bill Wendlingf891bf82011-07-31 06:30:59 +00002765 // If the stack restore is in a return, resume, or unwind block and if there
2766 // are no allocas or calls between the restore and the return, nuke the
2767 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002768 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002769 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002770 break;
2771 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00002772 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00002773 // Asan needs to poison memory to detect invalid access which is possible
2774 // even for empty lifetime range.
2775 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2776 break;
2777
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00002778 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2779 Intrinsic::lifetime_end, *this))
2780 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002781 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00002782 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002783 Value *IIOperand = II->getArgOperand(0);
2784 // Remove an assume if it is immediately followed by an identical assume.
2785 if (match(II->getNextNode(),
2786 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2787 return eraseInstFromFunction(CI);
2788
Hal Finkelf5867a72014-07-25 21:45:17 +00002789 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002790 // Note: New assumption intrinsics created here are registered by
2791 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002792 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002793 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2794 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2795 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002796 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002797 }
2798 // assume(!(a || b)) -> assume(!a); assume(!b);
2799 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002800 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2801 II->getName());
2802 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2803 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002804 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002805 }
Hal Finkel04a15612014-10-04 21:27:06 +00002806
Philip Reames66c6de62014-11-11 23:33:19 +00002807 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2808 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00002809 CmpInst::Predicate Pred;
2810 Instruction *LHS;
2811 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
2812 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
2813 LHS->getType()->isPointerTy() &&
2814 isValidAssumeForContext(II, LHS, &DT)) {
2815 MDNode *MD = MDNode::get(II->getContext(), None);
2816 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
2817 return eraseInstFromFunction(*II);
2818
Chandler Carruth24969102015-02-10 08:07:32 +00002819 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002820 // TODO: apply range metadata for range check patterns?
2821 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00002822
Hal Finkel04a15612014-10-04 21:27:06 +00002823 // If there is a dominating assume with the same condition as this one,
2824 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002825 APInt KnownZero(1, 0), KnownOne(1, 0);
2826 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2827 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002828 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002829
Hal Finkel8a9a7832017-01-11 13:24:24 +00002830 // Update the cache of affected values for this assumption (we might be
2831 // here because we just simplified the condition).
2832 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002833 break;
2834 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002835 case Intrinsic::experimental_gc_relocate: {
2836 // Translate facts known about a pointer before relocating into
2837 // facts about the relocate value, while being careful to
2838 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002839 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002840
2841 // Remove the relocation if unused, note that this check is required
2842 // to prevent the cases below from looping forever.
2843 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002844 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002845
2846 // Undef is undef, even after relocation.
2847 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2848 // most practical collectors, but there was discussion in the review thread
2849 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002850 if (isa<UndefValue>(DerivedPtr))
2851 // Use undef of gc_relocate's type to replace it.
2852 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002853
Philip Reamesea4d8e82016-02-09 21:09:22 +00002854 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2855 // The relocation of null will be null for most any collector.
2856 // TODO: provide a hook for this in GCStrategy. There might be some
2857 // weird collector this property does not hold for.
2858 if (isa<ConstantPointerNull>(DerivedPtr))
2859 // Use null-pointer of gc_relocate's type to replace it.
2860 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002861
Philip Reamesea4d8e82016-02-09 21:09:22 +00002862 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00002863 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00002864 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002865 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002866
2867 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2868 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002869
Philip Reames9db26ff2014-12-29 23:27:30 +00002870 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002871 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002872 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00002873
2874 case Intrinsic::experimental_guard: {
2875 Value *IIOperand = II->getArgOperand(0);
2876
2877 // Remove a guard if it is immediately followed by an identical guard.
2878 if (match(II->getNextNode(),
2879 m_Intrinsic<Intrinsic::experimental_guard>(m_Specific(IIOperand))))
2880 return eraseInstFromFunction(*II);
Artur Pilipenko4df4c4a2017-01-25 14:20:52 +00002881
2882 // Canonicalize guard(a && b) -> guard(a); guard(b);
2883 // Note: New guard intrinsics created here are registered by
2884 // the InstCombineIRInserter object.
2885 Function *GuardIntrinsic = II->getCalledFunction();
2886 Value *A, *B;
2887 OperandBundleDef DeoptOB(*II->getOperandBundle(LLVMContext::OB_deopt));
2888 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2889 CallInst *GuardA =
2890 Builder->CreateCall(GuardIntrinsic, A, {DeoptOB}, II->getName());
2891 CallInst *GuardB =
2892 Builder->CreateCall(GuardIntrinsic, B, {DeoptOB}, II->getName());
2893 auto CC = II->getCallingConv();
2894 GuardA->setCallingConv(CC);
2895 GuardB->setCallingConv(CC);
2896 return eraseInstFromFunction(*II);
2897 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00002898 break;
2899 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002900 }
2901
2902 return visitCallSite(II);
2903}
2904
2905// InvokeInst simplification
2906//
2907Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2908 return visitCallSite(&II);
2909}
2910
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002911/// If this cast does not affect the value passed through the varargs area, we
2912/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002913static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002914 const DataLayout &DL,
2915 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002916 const int ix) {
2917 if (!CI->isLosslessCast())
2918 return false;
2919
Philip Reames1a1bdb22014-12-02 18:50:36 +00002920 // If this is a GC intrinsic, avoid munging types. We need types for
2921 // statepoint reconstruction in SelectionDAG.
2922 // TODO: This is probably something which should be expanded to all
2923 // intrinsics since the entire point of intrinsics is that
2924 // they are understandable by the optimizer.
2925 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2926 return false;
2927
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002928 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002929 // can't change to a type with a different size. If the size were
2930 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002931 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002932 return true;
2933
Jim Grosbach7815f562012-02-03 00:07:04 +00002934 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002935 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002936 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002937 if (!SrcTy->isSized() || !DstTy->isSized())
2938 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002939 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002940 return false;
2941 return true;
2942}
2943
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002944Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002945 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002946
Chandler Carruthba4c5172015-01-21 11:23:40 +00002947 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002948 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002949 };
Justin Bogner99798402016-08-05 01:06:44 +00002950 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002951 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002952 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002953 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002954 }
Meador Ingedf796f82012-10-13 16:45:24 +00002955
Craig Topperf40110f2014-04-25 05:29:35 +00002956 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002957}
2958
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002959static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002960 // Strip off at most one level of pointer casts, looking for an alloca. This
2961 // is good enough in practice and simpler than handling any number of casts.
2962 Value *Underlying = TrampMem->stripPointerCasts();
2963 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002964 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002965 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002966 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002967 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002968
Craig Topperf40110f2014-04-25 05:29:35 +00002969 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002970 for (User *U : TrampMem->users()) {
2971 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002972 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002973 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002974 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2975 if (InitTrampoline)
2976 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002977 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002978 InitTrampoline = II;
2979 continue;
2980 }
2981 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2982 // Allow any number of calls to adjust.trampoline.
2983 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002984 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002985 }
2986
2987 // No call to init.trampoline found.
2988 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002989 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002990
2991 // Check that the alloca is being used in the expected way.
2992 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002993 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002994
2995 return InitTrampoline;
2996}
2997
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002998static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002999 Value *TrampMem) {
3000 // Visit all the previous instructions in the basic block, and try to find a
3001 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003002 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3003 E = AdjustTramp->getParent()->begin();
3004 I != E;) {
3005 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00003006 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3007 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3008 II->getOperand(0) == TrampMem)
3009 return II;
3010 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00003011 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003012 }
Craig Topperf40110f2014-04-25 05:29:35 +00003013 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003014}
3015
3016// Given a call to llvm.adjust.trampoline, find and return the corresponding
3017// call to llvm.init.trampoline if the call to the trampoline can be optimized
3018// to a direct call to a function. Otherwise return NULL.
3019//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003020static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003021 Callee = Callee->stripPointerCasts();
3022 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3023 if (!AdjustTramp ||
3024 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003025 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003026
3027 Value *TrampMem = AdjustTramp->getOperand(0);
3028
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003029 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003030 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003031 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003032 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00003033 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003034}
3035
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003036/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003037Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00003038 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00003039 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00003040
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003041 bool Changed = false;
3042
Philip Reamesc25df112015-06-16 20:24:25 +00003043 // Mark any parameters that are known to be non-null with the nonnull
3044 // attribute. This is helpful for inlining calls to functions with null
3045 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00003046 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00003047 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00003048
Philip Reamesc25df112015-06-16 20:24:25 +00003049 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00003050 if (V->getType()->isPointerTy() &&
3051 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00003052 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00003053 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00003054 ArgNo++;
3055 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00003056
Philip Reamesc25df112015-06-16 20:24:25 +00003057 assert(ArgNo == CS.arg_size() && "sanity check");
3058
Akira Hatanaka237916b2015-12-02 06:58:49 +00003059 if (!Indices.empty()) {
3060 AttributeSet AS = CS.getAttributes();
3061 LLVMContext &Ctx = CS.getInstruction()->getContext();
3062 AS = AS.addAttribute(Ctx, Indices,
3063 Attribute::get(Ctx, Attribute::NonNull));
3064 CS.setAttributes(AS);
3065 Changed = true;
3066 }
3067
Chris Lattner73989652010-12-20 08:25:06 +00003068 // If the callee is a pointer to a function, attempt to move any casts to the
3069 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003070 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00003071 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00003072 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003073
Justin Lebar9d943972016-03-14 20:18:54 +00003074 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
3075 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00003076 if (CS.isConvergent() && !CalleeF->isConvergent() &&
3077 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00003078 DEBUG(dbgs() << "Removing convergent attr from instr "
3079 << CS.getInstruction() << "\n");
3080 CS.setNotConvergent();
3081 return CS.getInstruction();
3082 }
3083
Chris Lattner846a52e2010-02-01 18:11:34 +00003084 // If the call and callee calling conventions don't match, this call must
3085 // be unreachable, as the call is undefined.
3086 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
3087 // Only do this for calls to a function with a body. A prototype may
3088 // not actually end up matching the implementation's calling conv for a
3089 // variety of reasons (e.g. it may be written in assembly).
3090 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003091 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003092 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00003093 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003094 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00003095 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003096 // This allows ValueHandlers and custom metadata to adjust itself.
3097 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003098 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00003099 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00003100 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00003101
Chris Lattner2cecedf2010-02-01 18:04:58 +00003102 // We cannot remove an invoke, because it would change the CFG, just
3103 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00003104 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00003105 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00003106 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003107 }
Justin Lebar9d943972016-03-14 20:18:54 +00003108 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003109
3110 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00003111 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003112 // This allows ValueHandlers and custom metadata to adjust itself.
3113 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003114 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003115 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003116
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003117 if (isa<InvokeInst>(CS.getInstruction())) {
3118 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00003119 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003120 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003121
3122 // This instruction is not reachable, just remove it. We insert a store to
3123 // undef so that we know that this code is not reachable, despite the fact
3124 // that we can't modify the CFG here.
3125 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3126 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3127 CS.getInstruction());
3128
Sanjay Patel4b198802016-02-01 22:23:39 +00003129 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003130 }
3131
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003132 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00003133 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003134
Chris Lattner229907c2011-07-18 04:54:35 +00003135 PointerType *PTy = cast<PointerType>(Callee->getType());
3136 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003137 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00003138 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003139 // See if we can optimize any arguments passed through the varargs area of
3140 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003141 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003142 E = CS.arg_end(); I != E; ++I, ++ix) {
3143 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003144 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003145 *I = CI->getOperand(0);
3146 Changed = true;
3147 }
3148 }
3149 }
3150
3151 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
3152 // Inline asm calls cannot throw - mark them 'nounwind'.
3153 CS.setDoesNotThrow();
3154 Changed = true;
3155 }
3156
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003157 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00003158 // this. None of these calls are seen as possibly dead so go ahead and
3159 // delete the instruction now.
3160 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003161 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00003162 // If we changed something return the result, etc. Otherwise let
3163 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00003164 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00003165 }
3166
Craig Topperf40110f2014-04-25 05:29:35 +00003167 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003168}
3169
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003170/// If the callee is a constexpr cast of a function, attempt to move the cast to
3171/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003172bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00003173 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00003174 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003175 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003176
3177 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00003178 if (Callee->hasFnAttribute("thunk"))
3179 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003180
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003181 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00003182 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003183
3184 // Okay, this is a cast from a function to a different type. Unless doing so
3185 // would cause a type conversion of one of our arguments, change this call to
3186 // be a direct call with arguments casted to the appropriate types.
3187 //
Chris Lattner229907c2011-07-18 04:54:35 +00003188 FunctionType *FT = Callee->getFunctionType();
3189 Type *OldRetTy = Caller->getType();
3190 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003191
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003192 // Check to see if we are changing the return type...
3193 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00003194
3195 if (NewRetTy->isStructTy())
3196 return false; // TODO: Handle multiple return values.
3197
David Majnemer9b6b8222015-01-06 08:41:31 +00003198 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003199 if (Callee->isDeclaration())
3200 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003201
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003202 if (!Caller->use_empty() &&
3203 // void -> non-void is handled specially
3204 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00003205 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003206 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003207
3208 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00003209 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00003210 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003211 return false; // Attribute not compatible with transformed value.
3212 }
3213
3214 // If the callsite is an invoke instruction, and the return value is used by
3215 // a PHI node in a successor, we cannot change the return type of the call
3216 // because there is no place to put the cast instruction (without breaking
3217 // the critical edge). Bail out in this case.
3218 if (!Caller->use_empty())
3219 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00003220 for (User *U : II->users())
3221 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003222 if (PN->getParent() == II->getNormalDest() ||
3223 PN->getParent() == II->getUnwindDest())
3224 return false;
3225 }
3226
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003227 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003228 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3229
David Majnemer9b6b8222015-01-06 08:41:31 +00003230 // Prevent us turning:
3231 // declare void @takes_i32_inalloca(i32* inalloca)
3232 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3233 //
3234 // into:
3235 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00003236 //
3237 // Similarly, avoid folding away bitcasts of byval calls.
3238 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3239 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00003240 return false;
3241
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003242 CallSite::arg_iterator AI = CS.arg_begin();
3243 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003244 Type *ParamTy = FT->getParamType(i);
3245 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003246
David Majnemer9b6b8222015-01-06 08:41:31 +00003247 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003248 return false; // Cannot transform this parameter value.
3249
Bill Wendling49bc76c2013-01-23 06:14:59 +00003250 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00003251 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003252 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00003253
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003254 if (CS.isInAllocaArgument(i))
3255 return false; // Cannot transform to and from inalloca.
3256
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003257 // If the parameter is passed as a byval argument, then we have to have a
3258 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003259 if (ParamTy != ActTy &&
3260 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
3261 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00003262 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003263 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003264 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00003265
Matt Arsenaultfa252722013-09-27 22:18:51 +00003266 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003267 if (DL.getTypeAllocSize(CurElTy) !=
3268 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003269 return false;
3270 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003271 }
3272
Chris Lattneradf38b32011-02-24 05:10:56 +00003273 if (Callee->isDeclaration()) {
3274 // Do not delete arguments unless we have a function body.
3275 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3276 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003277
Chris Lattneradf38b32011-02-24 05:10:56 +00003278 // If the callee is just a declaration, don't change the varargsness of the
3279 // call. We don't want to introduce a varargs call where one doesn't
3280 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00003281 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00003282 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
3283 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003284
3285 // If both the callee and the cast type are varargs, we still have to make
3286 // sure the number of fixed parameters are the same or we have the same
3287 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00003288 if (FT->isVarArg() &&
3289 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
3290 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003291 cast<FunctionType>(APTy->getElementType())->getNumParams())
3292 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00003293 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003294
Jim Grosbach0ab54182012-02-03 00:00:50 +00003295 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3296 !CallerPAL.isEmpty())
3297 // In this case we have more arguments than the new function type, but we
3298 // won't be dropping them. Check that these extra arguments have attributes
3299 // that are compatible with being a vararg call argument.
3300 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00003301 unsigned Index = CallerPAL.getSlotIndex(i - 1);
3302 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00003303 break;
Bill Wendling57625a42013-01-25 23:09:36 +00003304
Bill Wendlingd97b75d2012-12-19 08:57:40 +00003305 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00003306 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
3307 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00003308 return false;
3309 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003310
Jim Grosbach7815f562012-02-03 00:07:04 +00003311
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003312 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00003313 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003314 std::vector<Value*> Args;
3315 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003316 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003317 attrVec.reserve(NumCommonArgs);
3318
3319 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003320 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003321
3322 // If the return value is not being used, the type may not be compatible
3323 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00003324 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003325
3326 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00003327 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003328 attrVec.push_back(AttributeSet::get(Caller->getContext(),
3329 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003330
3331 AI = CS.arg_begin();
3332 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003333 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00003334
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003335 if ((*AI)->getType() == ParamTy) {
3336 Args.push_back(*AI);
3337 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00003338 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003339 }
3340
3341 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003342 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003343 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003344 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
3345 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003346 }
3347
3348 // If the function takes more arguments than the call was taking, add them
3349 // now.
3350 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3351 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3352
3353 // If we are removing arguments to the function, emit an obnoxious warning.
3354 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00003355 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3356 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003357 // Add all of the arguments in their promoted form to the arg list.
3358 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003359 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003360 if (PTy != (*AI)->getType()) {
3361 // Must promote to pass through va_arg area!
3362 Instruction::CastOps opcode =
3363 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003364 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003365 } else {
3366 Args.push_back(*AI);
3367 }
3368
3369 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003370 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003371 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003372 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
3373 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003374 }
3375 }
3376 }
3377
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003378 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00003379 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003380 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003381
3382 if (NewRetTy->isVoidTy())
3383 Caller->setName(""); // Void type should not have a name.
3384
Bill Wendlinge94d8432012-12-07 23:16:57 +00003385 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003386 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003387
Sanjoy Das76293462015-11-25 00:42:19 +00003388 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00003389 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00003390
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003391 Instruction *NC;
3392 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00003393 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
3394 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003395 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003396 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
3397 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
3398 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003399 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00003400 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003401 NC->takeName(CI);
David Majnemerd5648c72016-11-25 22:35:09 +00003402 cast<CallInst>(NC)->setTailCallKind(CI->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003403 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
3404 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
3405 }
3406
3407 // Insert a cast of the return type as necessary.
3408 Value *NV = NC;
3409 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3410 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00003411 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00003412 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003413
3414 // If this is an invoke instruction, we should insert it after the first
3415 // non-phi, instruction in the normal successor block.
3416 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00003417 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003418 InsertNewInstBefore(NC, *I);
3419 } else {
Chris Lattner73989652010-12-20 08:25:06 +00003420 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003421 InsertNewInstBefore(NC, *Caller);
3422 }
3423 Worklist.AddUsersToWorkList(*Caller);
3424 } else {
3425 NV = UndefValue::get(Caller->getType());
3426 }
3427 }
3428
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003429 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003430 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00003431 else if (Caller->hasValueHandle()) {
3432 if (OldRetTy == NV->getType())
3433 ValueHandleBase::ValueIsRAUWd(Caller, NV);
3434 else
3435 // We cannot call ValueIsRAUWd with a different type, and the
3436 // actual tracked value will disappear.
3437 ValueHandleBase::ValueIsDeleted(Caller);
3438 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003439
Sanjay Patel4b198802016-02-01 22:23:39 +00003440 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003441 return true;
3442}
3443
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003444/// Turn a call to a function created by init_trampoline / adjust_trampoline
3445/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00003446Instruction *
3447InstCombiner::transformCallThroughTrampoline(CallSite CS,
3448 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003449 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00003450 PointerType *PTy = cast<PointerType>(Callee->getType());
3451 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00003452 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003453
3454 // If the call already has the 'nest' attribute somewhere then give up -
3455 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00003456 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00003457 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003458
Duncan Sandsa0984362011-09-06 13:37:06 +00003459 assert(Tramp &&
3460 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003461
Gabor Greif3e44ea12010-07-22 10:37:47 +00003462 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003463 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003464
Bill Wendlinge94d8432012-12-07 23:16:57 +00003465 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003466 if (!NestAttrs.isEmpty()) {
3467 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00003468 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00003469 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003470
3471 // Look for a parameter marked with the 'nest' attribute.
3472 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3473 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00003474 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003475 // Record the parameter type and any other attributes.
3476 NestTy = *I;
3477 NestAttr = NestAttrs.getParamAttributes(NestIdx);
3478 break;
3479 }
3480
3481 if (NestTy) {
3482 Instruction *Caller = CS.getInstruction();
3483 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003484 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003485
Bill Wendling3575c8c2013-01-27 02:08:22 +00003486 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003487 NewAttrs.reserve(Attrs.getNumSlots() + 1);
3488
3489 // Insert the nest argument into the call argument list, which may
3490 // mean appending it. Likewise for attributes.
3491
3492 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003493 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003494 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3495 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003496
3497 {
3498 unsigned Idx = 1;
3499 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3500 do {
3501 if (Idx == NestIdx) {
3502 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00003503 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003504 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00003505 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003506 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003507 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3508 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003509 }
3510
3511 if (I == E)
3512 break;
3513
3514 // Add the original argument and attributes.
3515 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00003516 AttributeSet Attr = Attrs.getParamAttributes(Idx);
3517 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00003518 AttrBuilder B(Attr, Idx);
3519 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3520 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00003521 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003522
Richard Trieu7a083812016-02-18 22:09:30 +00003523 ++Idx;
3524 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003525 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003526 }
3527
3528 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00003529 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003530 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3531 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003532
3533 // The trampoline may have been bitcast to a bogus type (FTy).
3534 // Handle this by synthesizing a new function type, equal to FTy
3535 // with the chain parameter inserted.
3536
Jay Foadb804a2b2011-07-12 14:06:48 +00003537 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003538 NewTypes.reserve(FTy->getNumParams()+1);
3539
3540 // Insert the chain's type into the list of parameter types, which may
3541 // mean appending it.
3542 {
3543 unsigned Idx = 1;
3544 FunctionType::param_iterator I = FTy->param_begin(),
3545 E = FTy->param_end();
3546
3547 do {
3548 if (Idx == NestIdx)
3549 // Add the chain's type.
3550 NewTypes.push_back(NestTy);
3551
3552 if (I == E)
3553 break;
3554
3555 // Add the original type.
3556 NewTypes.push_back(*I);
3557
Richard Trieu7a083812016-02-18 22:09:30 +00003558 ++Idx;
3559 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003560 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003561 }
3562
3563 // Replace the trampoline call with a direct call. Let the generic
3564 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00003565 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003566 FTy->isVarArg());
3567 Constant *NewCallee =
3568 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00003569 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003570 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00003571 const AttributeSet &NewPAL =
3572 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003573
David Majnemer231a68c2016-04-29 08:07:20 +00003574 SmallVector<OperandBundleDef, 1> OpBundles;
3575 CS.getOperandBundlesAsDefs(OpBundles);
3576
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003577 Instruction *NewCaller;
3578 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3579 NewCaller = InvokeInst::Create(NewCallee,
3580 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00003581 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003582 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3583 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3584 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00003585 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00003586 cast<CallInst>(NewCaller)->setTailCallKind(
3587 cast<CallInst>(Caller)->getTailCallKind());
3588 cast<CallInst>(NewCaller)->setCallingConv(
3589 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003590 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3591 }
Eli Friedman49346012011-05-18 19:57:14 +00003592
3593 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003594 }
3595 }
3596
3597 // Replace the trampoline call with a direct call. Since there is no 'nest'
3598 // parameter, there is no need to adjust the argument list. Let the generic
3599 // code sort out any function type mismatches.
3600 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00003601 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003602 ConstantExpr::getBitCast(NestF, PTy);
3603 CS.setCalledFunction(NewCallee);
3604 return CS.getInstruction();
3605}