blob: 9b8f696da7477c2d0a801d30485b08dee728ee8d [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 Pilgrim91e3ac82016-06-07 08:18:35 +0000513static Value *simplifyX86movmsk(const IntrinsicInst &II,
514 InstCombiner::BuilderTy &Builder) {
515 Value *Arg = II.getArgOperand(0);
516 Type *ResTy = II.getType();
517 Type *ArgTy = Arg->getType();
518
519 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
520 if (isa<UndefValue>(Arg))
521 return Constant::getNullValue(ResTy);
522
523 // We can't easily peek through x86_mmx types.
524 if (!ArgTy->isVectorTy())
525 return nullptr;
526
527 auto *C = dyn_cast<Constant>(Arg);
528 if (!C)
529 return nullptr;
530
531 // Extract signbits of the vector input and pack into integer result.
532 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
533 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
534 auto *COp = C->getAggregateElement(I);
535 if (!COp)
536 return nullptr;
537 if (isa<UndefValue>(COp))
538 continue;
539
540 auto *CInt = dyn_cast<ConstantInt>(COp);
541 auto *CFp = dyn_cast<ConstantFP>(COp);
542 if (!CInt && !CFp)
543 return nullptr;
544
545 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
546 Result.setBit(I);
547 }
548
549 return Constant::getIntegerValue(ResTy, Result);
550}
551
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000552static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000553 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000554 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
555 if (!CInt)
556 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000557
Sanjay Patel03c03f52016-01-28 00:03:16 +0000558 VectorType *VecTy = cast<VectorType>(II.getType());
559 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000560
Sanjay Patel03c03f52016-01-28 00:03:16 +0000561 // The immediate permute control byte looks like this:
562 // [3:0] - zero mask for each 32-bit lane
563 // [5:4] - select one 32-bit destination lane
564 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000565
Sanjay Patel03c03f52016-01-28 00:03:16 +0000566 uint8_t Imm = CInt->getZExtValue();
567 uint8_t ZMask = Imm & 0xf;
568 uint8_t DestLane = (Imm >> 4) & 0x3;
569 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000570
Sanjay Patel03c03f52016-01-28 00:03:16 +0000571 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000572
Sanjay Patel03c03f52016-01-28 00:03:16 +0000573 // If all zero mask bits are set, this was just a weird way to
574 // generate a zero vector.
575 if (ZMask == 0xf)
576 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000577
Sanjay Patel03c03f52016-01-28 00:03:16 +0000578 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000579 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000580
Sanjay Patel03c03f52016-01-28 00:03:16 +0000581 // We may replace the second operand with the zero vector.
582 Value *V1 = II.getArgOperand(1);
583
584 if (ZMask) {
585 // If the zero mask is being used with a single input or the zero mask
586 // overrides the destination lane, this is a shuffle with the zero vector.
587 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
588 (ZMask & (1 << DestLane))) {
589 V1 = ZeroVector;
590 // We may still move 32-bits of the first source vector from one lane
591 // to another.
592 ShuffleMask[DestLane] = SourceLane;
593 // The zero mask may override the previous insert operation.
594 for (unsigned i = 0; i < 4; ++i)
595 if ((ZMask >> i) & 0x1)
596 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000597 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000598 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
599 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000600 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000601 } else {
602 // Replace the selected destination lane with the selected source lane.
603 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000604 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000605
606 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000607}
608
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000609/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
610/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000611static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000612 ConstantInt *CILength, ConstantInt *CIIndex,
613 InstCombiner::BuilderTy &Builder) {
614 auto LowConstantHighUndef = [&](uint64_t Val) {
615 Type *IntTy64 = Type::getInt64Ty(II.getContext());
616 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
617 UndefValue::get(IntTy64)};
618 return ConstantVector::get(Args);
619 };
620
621 // See if we're dealing with constant values.
622 Constant *C0 = dyn_cast<Constant>(Op0);
623 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000624 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000625 : nullptr;
626
627 // Attempt to constant fold.
628 if (CILength && CIIndex) {
629 // From AMD documentation: "The bit index and field length are each six
630 // bits in length other bits of the field are ignored."
631 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
632 APInt APLength = CILength->getValue().zextOrTrunc(6);
633
634 unsigned Index = APIndex.getZExtValue();
635
636 // From AMD documentation: "a value of zero in the field length is
637 // defined as length of 64".
638 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
639
640 // From AMD documentation: "If the sum of the bit index + length field
641 // is greater than 64, the results are undefined".
642 unsigned End = Index + Length;
643
644 // Note that both field index and field length are 8-bit quantities.
645 // Since variables 'Index' and 'Length' are unsigned values
646 // obtained from zero-extending field index and field length
647 // respectively, their sum should never wrap around.
648 if (End > 64)
649 return UndefValue::get(II.getType());
650
651 // If we are inserting whole bytes, we can convert this to a shuffle.
652 // Lowering can recognize EXTRQI shuffle masks.
653 if ((Length % 8) == 0 && (Index % 8) == 0) {
654 // Convert bit indices to byte indices.
655 Length /= 8;
656 Index /= 8;
657
658 Type *IntTy8 = Type::getInt8Ty(II.getContext());
659 Type *IntTy32 = Type::getInt32Ty(II.getContext());
660 VectorType *ShufTy = VectorType::get(IntTy8, 16);
661
662 SmallVector<Constant *, 16> ShuffleMask;
663 for (int i = 0; i != (int)Length; ++i)
664 ShuffleMask.push_back(
665 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
666 for (int i = Length; i != 8; ++i)
667 ShuffleMask.push_back(
668 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
669 for (int i = 8; i != 16; ++i)
670 ShuffleMask.push_back(UndefValue::get(IntTy32));
671
672 Value *SV = Builder.CreateShuffleVector(
673 Builder.CreateBitCast(Op0, ShufTy),
674 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
675 return Builder.CreateBitCast(SV, II.getType());
676 }
677
678 // Constant Fold - shift Index'th bit to lowest position and mask off
679 // Length bits.
680 if (CI0) {
681 APInt Elt = CI0->getValue();
682 Elt = Elt.lshr(Index).zextOrTrunc(Length);
683 return LowConstantHighUndef(Elt.getZExtValue());
684 }
685
686 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
687 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
688 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000689 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000690 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
691 return Builder.CreateCall(F, Args);
692 }
693 }
694
695 // Constant Fold - extraction from zero is always {zero, undef}.
696 if (CI0 && CI0->equalsInt(0))
697 return LowConstantHighUndef(0);
698
699 return nullptr;
700}
701
702/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
703/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000704static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000705 APInt APLength, APInt APIndex,
706 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000707 // From AMD documentation: "The bit index and field length are each six bits
708 // in length other bits of the field are ignored."
709 APIndex = APIndex.zextOrTrunc(6);
710 APLength = APLength.zextOrTrunc(6);
711
712 // Attempt to constant fold.
713 unsigned Index = APIndex.getZExtValue();
714
715 // From AMD documentation: "a value of zero in the field length is
716 // defined as length of 64".
717 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
718
719 // From AMD documentation: "If the sum of the bit index + length field
720 // is greater than 64, the results are undefined".
721 unsigned End = Index + Length;
722
723 // Note that both field index and field length are 8-bit quantities.
724 // Since variables 'Index' and 'Length' are unsigned values
725 // obtained from zero-extending field index and field length
726 // respectively, their sum should never wrap around.
727 if (End > 64)
728 return UndefValue::get(II.getType());
729
730 // If we are inserting whole bytes, we can convert this to a shuffle.
731 // Lowering can recognize INSERTQI shuffle masks.
732 if ((Length % 8) == 0 && (Index % 8) == 0) {
733 // Convert bit indices to byte indices.
734 Length /= 8;
735 Index /= 8;
736
737 Type *IntTy8 = Type::getInt8Ty(II.getContext());
738 Type *IntTy32 = Type::getInt32Ty(II.getContext());
739 VectorType *ShufTy = VectorType::get(IntTy8, 16);
740
741 SmallVector<Constant *, 16> ShuffleMask;
742 for (int i = 0; i != (int)Index; ++i)
743 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
744 for (int i = 0; i != (int)Length; ++i)
745 ShuffleMask.push_back(
746 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
747 for (int i = Index + Length; i != 8; ++i)
748 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
749 for (int i = 8; i != 16; ++i)
750 ShuffleMask.push_back(UndefValue::get(IntTy32));
751
752 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
753 Builder.CreateBitCast(Op1, ShufTy),
754 ConstantVector::get(ShuffleMask));
755 return Builder.CreateBitCast(SV, II.getType());
756 }
757
758 // See if we're dealing with constant values.
759 Constant *C0 = dyn_cast<Constant>(Op0);
760 Constant *C1 = dyn_cast<Constant>(Op1);
761 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000762 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000763 : nullptr;
764 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000765 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000766 : nullptr;
767
768 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
769 if (CI00 && CI10) {
770 APInt V00 = CI00->getValue();
771 APInt V10 = CI10->getValue();
772 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
773 V00 = V00 & ~Mask;
774 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
775 APInt Val = V00 | V10;
776 Type *IntTy64 = Type::getInt64Ty(II.getContext());
777 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
778 UndefValue::get(IntTy64)};
779 return ConstantVector::get(Args);
780 }
781
782 // If we were an INSERTQ call, we'll save demanded elements if we convert to
783 // INSERTQI.
784 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
785 Type *IntTy8 = Type::getInt8Ty(II.getContext());
786 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
787 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
788
789 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000790 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000791 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
792 return Builder.CreateCall(F, Args);
793 }
794
795 return nullptr;
796}
797
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000798/// Attempt to convert pshufb* to shufflevector if the mask is constant.
799static Value *simplifyX86pshufb(const IntrinsicInst &II,
800 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000801 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
802 if (!V)
803 return nullptr;
804
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000805 auto *VecTy = cast<VectorType>(II.getType());
806 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
807 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000808 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000809 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000810
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000811 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000812 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000813
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000814 // Each byte in the shuffle control mask forms an index to permute the
815 // corresponding byte in the destination operand.
816 for (unsigned I = 0; I < NumElts; ++I) {
817 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000818 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000819 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000820
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000821 if (isa<UndefValue>(COp)) {
822 Indexes[I] = UndefValue::get(MaskEltTy);
823 continue;
824 }
825
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000826 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
827
828 // If the most significant bit (bit[7]) of each byte of the shuffle
829 // control mask is set, then zero is written in the result byte.
830 // The zero vector is in the right-hand side of the resulting
831 // shufflevector.
832
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000833 // The value of each index for the high 128-bit lane is the least
834 // significant 4 bits of the respective shuffle control byte.
835 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
836 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000837 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000838
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000839 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000840 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000841 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000842 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
843}
844
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000845/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
846static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
847 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000848 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
849 if (!V)
850 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000851
Craig Topper58917f32016-12-11 01:59:36 +0000852 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000853 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +0000854 unsigned NumElts = VecTy->getVectorNumElements();
855 bool IsPD = VecTy->getScalarType()->isDoubleTy();
856 unsigned NumLaneElts = IsPD ? 2 : 4;
857 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000858
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000859 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +0000860 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000861
862 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000863 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000864 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000865 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000866 return nullptr;
867
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000868 if (isa<UndefValue>(COp)) {
869 Indexes[I] = UndefValue::get(MaskEltTy);
870 continue;
871 }
872
873 APInt Index = cast<ConstantInt>(COp)->getValue();
874 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000875
876 // The PD variants uses bit 1 to select per-lane element index, so
877 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +0000878 if (IsPD)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000879 Index = Index.lshr(1);
880
881 // The _256 variants are a bit trickier since the mask bits always index
882 // into the corresponding 128 half. In order to convert to a generic
883 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +0000884 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000885
886 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000887 }
888
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000889 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000890 auto V1 = II.getArgOperand(0);
891 auto V2 = UndefValue::get(V1->getType());
892 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
893}
894
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000895/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
896static Value *simplifyX86vpermv(const IntrinsicInst &II,
897 InstCombiner::BuilderTy &Builder) {
898 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
899 if (!V)
900 return nullptr;
901
Simon Pilgrimca140b12016-05-01 20:43:02 +0000902 auto *VecTy = cast<VectorType>(II.getType());
903 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000904 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +0000905 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
906 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000907
Simon Pilgrimca140b12016-05-01 20:43:02 +0000908 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +0000909 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000910
911 for (unsigned I = 0; I < Size; ++I) {
912 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +0000913 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000914 return nullptr;
915
Simon Pilgrimca140b12016-05-01 20:43:02 +0000916 if (isa<UndefValue>(COp)) {
917 Indexes[I] = UndefValue::get(MaskEltTy);
918 continue;
919 }
920
Craig Toppere3280452016-12-25 23:58:57 +0000921 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
922 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +0000923 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000924 }
925
Simon Pilgrimca140b12016-05-01 20:43:02 +0000926 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000927 auto V1 = II.getArgOperand(0);
928 auto V2 = UndefValue::get(VecTy);
929 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
930}
931
Sanjay Patelccf5f242015-03-20 21:47:56 +0000932/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
933/// source vectors, unless a zero bit is set. If a zero bit is set,
934/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000935static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000936 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000937 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
938 if (!CInt)
939 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000940
Sanjay Patel03c03f52016-01-28 00:03:16 +0000941 VectorType *VecTy = cast<VectorType>(II.getType());
942 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000943
Sanjay Patel03c03f52016-01-28 00:03:16 +0000944 // The immediate permute control byte looks like this:
945 // [1:0] - select 128 bits from sources for low half of destination
946 // [2] - ignore
947 // [3] - zero low half of destination
948 // [5:4] - select 128 bits from sources for high half of destination
949 // [6] - ignore
950 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000951
Sanjay Patel03c03f52016-01-28 00:03:16 +0000952 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000953
Sanjay Patel03c03f52016-01-28 00:03:16 +0000954 bool LowHalfZero = Imm & 0x08;
955 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000956
Sanjay Patel03c03f52016-01-28 00:03:16 +0000957 // If both zero mask bits are set, this was just a weird way to
958 // generate a zero vector.
959 if (LowHalfZero && HighHalfZero)
960 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000961
Sanjay Patel03c03f52016-01-28 00:03:16 +0000962 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
963 unsigned NumElts = VecTy->getNumElements();
964 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +0000965 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000966
Sanjay Patel03c03f52016-01-28 00:03:16 +0000967 // The high bit of the selection field chooses the 1st or 2nd operand.
968 bool LowInputSelect = Imm & 0x02;
969 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000970
Sanjay Patel03c03f52016-01-28 00:03:16 +0000971 // The low bit of the selection field chooses the low or high half
972 // of the selected operand.
973 bool LowHalfSelect = Imm & 0x01;
974 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000975
Sanjay Patel03c03f52016-01-28 00:03:16 +0000976 // Determine which operand(s) are actually in use for this instruction.
977 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
978 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000979
Sanjay Patel03c03f52016-01-28 00:03:16 +0000980 // If needed, replace operands based on zero mask.
981 V0 = LowHalfZero ? ZeroVector : V0;
982 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000983
Sanjay Patel03c03f52016-01-28 00:03:16 +0000984 // Permute low half of result.
985 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
986 for (unsigned i = 0; i < HalfSize; ++i)
987 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000988
Sanjay Patel03c03f52016-01-28 00:03:16 +0000989 // Permute high half of result.
990 StartIndex = HighHalfSelect ? HalfSize : 0;
991 StartIndex += NumElts;
992 for (unsigned i = 0; i < HalfSize; ++i)
993 ShuffleMask[i + HalfSize] = StartIndex + i;
994
995 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +0000996}
997
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000998/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000999static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001000 InstCombiner::BuilderTy &Builder,
1001 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001002 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1003 uint64_t Imm = CInt->getZExtValue() & 0x7;
1004 VectorType *VecTy = cast<VectorType>(II.getType());
1005 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1006
1007 switch (Imm) {
1008 case 0x0:
1009 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1010 break;
1011 case 0x1:
1012 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1013 break;
1014 case 0x2:
1015 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1016 break;
1017 case 0x3:
1018 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1019 break;
1020 case 0x4:
1021 Pred = ICmpInst::ICMP_EQ; break;
1022 case 0x5:
1023 Pred = ICmpInst::ICMP_NE; break;
1024 case 0x6:
1025 return ConstantInt::getSigned(VecTy, 0); // FALSE
1026 case 0x7:
1027 return ConstantInt::getSigned(VecTy, -1); // TRUE
1028 }
1029
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001030 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1031 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001032 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1033 }
1034 return nullptr;
1035}
1036
Craig Toppere3280452016-12-25 23:58:57 +00001037// Emit a select instruction and appropriate bitcasts to help simplify
1038// masked intrinsics.
1039static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1040 InstCombiner::BuilderTy &Builder) {
1041 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1042 cast<IntegerType>(Mask->getType())->getBitWidth());
1043 Mask = Builder.CreateBitCast(Mask, MaskTy);
1044
1045 // If we have less than 8 elements, then the starting mask was an i8 and
1046 // we need to extract down to the right number of elements.
1047 unsigned VWidth = Op0->getType()->getVectorNumElements();
1048 if (VWidth < 8) {
1049 uint32_t Indices[4];
1050 for (unsigned i = 0; i != VWidth; ++i)
1051 Indices[i] = i;
1052 Mask = Builder.CreateShuffleVector(Mask, Mask,
1053 makeArrayRef(Indices, VWidth),
1054 "extract");
1055 }
1056
1057 return Builder.CreateSelect(Mask, Op0, Op1);
1058}
1059
Sanjay Patel0069f562016-01-31 16:35:23 +00001060static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1061 Value *Arg0 = II.getArgOperand(0);
1062 Value *Arg1 = II.getArgOperand(1);
1063
1064 // fmin(x, x) -> x
1065 if (Arg0 == Arg1)
1066 return Arg0;
1067
1068 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1069
1070 // fmin(x, nan) -> x
1071 if (C1 && C1->isNaN())
1072 return Arg0;
1073
1074 // This is the value because if undef were NaN, we would return the other
1075 // value and cannot return a NaN unless both operands are.
1076 //
1077 // fmin(undef, x) -> x
1078 if (isa<UndefValue>(Arg0))
1079 return Arg1;
1080
1081 // fmin(x, undef) -> x
1082 if (isa<UndefValue>(Arg1))
1083 return Arg0;
1084
1085 Value *X = nullptr;
1086 Value *Y = nullptr;
1087 if (II.getIntrinsicID() == Intrinsic::minnum) {
1088 // fmin(x, fmin(x, y)) -> fmin(x, y)
1089 // fmin(y, fmin(x, y)) -> fmin(x, y)
1090 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1091 if (Arg0 == X || Arg0 == Y)
1092 return Arg1;
1093 }
1094
1095 // fmin(fmin(x, y), x) -> fmin(x, y)
1096 // fmin(fmin(x, y), y) -> fmin(x, y)
1097 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1098 if (Arg1 == X || Arg1 == Y)
1099 return Arg0;
1100 }
1101
1102 // TODO: fmin(nnan x, inf) -> x
1103 // TODO: fmin(nnan ninf x, flt_max) -> x
1104 if (C1 && C1->isInfinity()) {
1105 // fmin(x, -inf) -> -inf
1106 if (C1->isNegative())
1107 return Arg1;
1108 }
1109 } else {
1110 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1111 // fmax(x, fmax(x, y)) -> fmax(x, y)
1112 // fmax(y, fmax(x, y)) -> fmax(x, y)
1113 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1114 if (Arg0 == X || Arg0 == Y)
1115 return Arg1;
1116 }
1117
1118 // fmax(fmax(x, y), x) -> fmax(x, y)
1119 // fmax(fmax(x, y), y) -> fmax(x, y)
1120 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1121 if (Arg1 == X || Arg1 == Y)
1122 return Arg0;
1123 }
1124
1125 // TODO: fmax(nnan x, -inf) -> x
1126 // TODO: fmax(nnan ninf x, -flt_max) -> x
1127 if (C1 && C1->isInfinity()) {
1128 // fmax(x, inf) -> inf
1129 if (!C1->isNegative())
1130 return Arg1;
1131 }
1132 }
1133 return nullptr;
1134}
1135
David Majnemer666aa942016-07-14 06:58:42 +00001136static bool maskIsAllOneOrUndef(Value *Mask) {
1137 auto *ConstMask = dyn_cast<Constant>(Mask);
1138 if (!ConstMask)
1139 return false;
1140 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1141 return true;
1142 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1143 ++I) {
1144 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1145 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1146 continue;
1147 return false;
1148 }
1149 return true;
1150}
1151
Sanjay Patelb695c552016-02-01 17:00:10 +00001152static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1153 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001154 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1155 // argument.
1156 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001157 Value *LoadPtr = II.getArgOperand(0);
1158 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1159 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1160 }
1161
1162 return nullptr;
1163}
1164
Sanjay Patel04f792b2016-02-01 19:39:52 +00001165static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1166 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1167 if (!ConstMask)
1168 return nullptr;
1169
1170 // If the mask is all zeros, this instruction does nothing.
1171 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001172 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001173
1174 // If the mask is all ones, this is a plain vector store of the 1st argument.
1175 if (ConstMask->isAllOnesValue()) {
1176 Value *StorePtr = II.getArgOperand(1);
1177 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1178 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1179 }
1180
1181 return nullptr;
1182}
1183
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001184static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1185 // If the mask is all zeros, return the "passthru" argument of the gather.
1186 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1187 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001188 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001189
1190 return nullptr;
1191}
1192
1193static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1194 // If the mask is all zeros, a scatter does nothing.
1195 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1196 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001197 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001198
1199 return nullptr;
1200}
1201
Amaury Sechet763c59d2016-08-18 20:43:50 +00001202static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1203 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1204 II.getIntrinsicID() == Intrinsic::ctlz) &&
1205 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001206 Value *Op0 = II.getArgOperand(0);
1207 // FIXME: Try to simplify vectors of integers.
1208 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1209 if (!IT)
1210 return nullptr;
1211
1212 unsigned BitWidth = IT->getBitWidth();
1213 APInt KnownZero(BitWidth, 0);
1214 APInt KnownOne(BitWidth, 0);
1215 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1216
1217 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1218 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1219 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1220 : KnownOne.countLeadingZeros();
1221 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1222 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1223
1224 // If all bits above (ctlz) or below (cttz) the first known one are known
1225 // zero, this value is constant.
1226 // FIXME: This should be in InstSimplify because we're replacing an
1227 // instruction with a constant.
Amaury Sechet763c59d2016-08-18 20:43:50 +00001228 if ((Mask & KnownZero) == Mask) {
1229 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1230 return IC.replaceInstUsesWith(II, C);
1231 }
1232
1233 // If the input to cttz/ctlz is known to be non-zero,
1234 // then change the 'ZeroIsUndef' parameter to 'true'
1235 // because we know the zero behavior can't affect the result.
1236 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1237 if (!match(II.getArgOperand(1), m_One())) {
1238 II.setOperand(1, IC.Builder->getTrue());
1239 return &II;
1240 }
1241 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001242
1243 return nullptr;
1244}
1245
Sanjay Patel1ace9932016-02-26 21:04:14 +00001246// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1247// XMM register mask efficiently, we could transform all x86 masked intrinsics
1248// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001249static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1250 Value *Ptr = II.getOperand(0);
1251 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001252 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001253
1254 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001255 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001256 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001257 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001258
1259 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1260 if (!ConstMask)
1261 return nullptr;
1262
1263 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1264 // to allow target-independent optimizations.
1265
1266 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1267 // the LLVM intrinsic definition for the pointer argument.
1268 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1269 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1270 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1271
1272 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1273 // on each element's most significant bit (the sign bit).
1274 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1275
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001276 // The pass-through vector for an x86 masked load is a zero vector.
1277 CallInst *NewMaskedLoad =
1278 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001279 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1280}
1281
1282// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1283// XMM register mask efficiently, we could transform all x86 masked intrinsics
1284// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001285static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1286 Value *Ptr = II.getOperand(0);
1287 Value *Mask = II.getOperand(1);
1288 Value *Vec = II.getOperand(2);
1289
1290 // Special case a zero mask since that's not a ConstantDataVector:
1291 // this masked store instruction does nothing.
1292 if (isa<ConstantAggregateZero>(Mask)) {
1293 IC.eraseInstFromFunction(II);
1294 return true;
1295 }
1296
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001297 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1298 // anything else at this level.
1299 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1300 return false;
1301
Sanjay Patel1ace9932016-02-26 21:04:14 +00001302 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1303 if (!ConstMask)
1304 return false;
1305
1306 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1307 // to allow target-independent optimizations.
1308
1309 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1310 // the LLVM intrinsic definition for the pointer argument.
1311 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1312 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001313 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1314
1315 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1316 // on each element's most significant bit (the sign bit).
1317 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1318
1319 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1320
1321 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1322 IC.eraseInstFromFunction(II);
1323 return true;
1324}
1325
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001326// Returns true iff the 2 intrinsics have the same operands, limiting the
1327// comparison to the first NumOperands.
1328static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1329 unsigned NumOperands) {
1330 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1331 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1332 for (unsigned i = 0; i < NumOperands; i++)
1333 if (I.getArgOperand(i) != E.getArgOperand(i))
1334 return false;
1335 return true;
1336}
1337
1338// Remove trivially empty start/end intrinsic ranges, i.e. a start
1339// immediately followed by an end (ignoring debuginfo or other
1340// start/end intrinsics in between). As this handles only the most trivial
1341// cases, tracking the nesting level is not needed:
1342//
1343// call @llvm.foo.start(i1 0) ; &I
1344// call @llvm.foo.start(i1 0)
1345// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1346// call @llvm.foo.end(i1 0)
1347static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1348 unsigned EndID, InstCombiner &IC) {
1349 assert(I.getIntrinsicID() == StartID &&
1350 "Start intrinsic does not have expected ID");
1351 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1352 for (++BI; BI != BE; ++BI) {
1353 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1354 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1355 continue;
1356 if (E->getIntrinsicID() == EndID &&
1357 haveSameOperands(I, *E, E->getNumArgOperands())) {
1358 IC.eraseInstFromFunction(*E);
1359 IC.eraseInstFromFunction(I);
1360 return true;
1361 }
1362 }
1363 break;
1364 }
1365
1366 return false;
1367}
1368
1369Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1370 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1371 return nullptr;
1372}
1373
1374Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1375 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1376 return nullptr;
1377}
1378
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001379/// CallInst simplification. This mostly only handles folding of intrinsic
1380/// instructions. For normal calls, it allows visitCallSite to do the heavy
1381/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001382Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001383 auto Args = CI.arg_operands();
1384 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001385 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001386 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001387
Justin Bogner99798402016-08-05 01:06:44 +00001388 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001389 return visitFree(CI);
1390
1391 // If the caller function is nounwind, mark the call as nounwind, even if the
1392 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001393 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001394 CI.setDoesNotThrow();
1395 return &CI;
1396 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001397
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001398 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1399 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001400
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001401 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1402 // visitCallSite.
1403 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1404 bool Changed = false;
1405
1406 // memmove/cpy/set of zero bytes is a noop.
1407 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001408 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001409 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001410
1411 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1412 if (CI->getZExtValue() == 1) {
1413 // Replace the instruction with just byte operations. We would
1414 // transform other cases to loads/stores, but we don't know if
1415 // alignment is sufficient.
1416 }
1417 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001418
Chris Lattnerc663a672010-10-01 05:51:02 +00001419 // No other transformations apply to volatile transfers.
1420 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001421 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001422
1423 // If we have a memmove and the source operation is a constant global,
1424 // then the source and dest pointers can't alias, so we can change this
1425 // into a call to memcpy.
1426 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1427 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1428 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001429 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001430 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001431 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1432 CI.getArgOperand(1)->getType(),
1433 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001434 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001435 Changed = true;
1436 }
1437 }
1438
1439 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1440 // memmove(x,x,size) -> noop.
1441 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001442 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001443 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001444
Eric Christopher7258dcd2010-04-16 23:37:20 +00001445 // If we can determine a pointer alignment that is bigger than currently
1446 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001447 if (isa<MemTransferInst>(MI)) {
1448 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001449 return I;
1450 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1451 if (Instruction *I = SimplifyMemSet(MSI))
1452 return I;
1453 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001454
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001455 if (Changed) return II;
1456 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001457
Sanjay Patel1c600c62016-01-20 16:41:43 +00001458 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1459 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001460 APInt UndefElts(Width, 0);
1461 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1462 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1463 };
1464
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001465 switch (II->getIntrinsicID()) {
1466 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001467 case Intrinsic::objectsize:
1468 if (ConstantInt *N =
1469 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1470 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001471 return nullptr;
George Burgess IV3f089142016-12-20 23:46:36 +00001472
Michael Ilseman536cc322012-12-13 03:13:36 +00001473 case Intrinsic::bswap: {
1474 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001475 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001476
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001477 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001478 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001479 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001480
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001481 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001482 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1483 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1484 IIOperand->getType()->getPrimitiveSizeInBits();
1485 Value *CV = ConstantInt::get(X->getType(), C);
1486 Value *V = Builder->CreateLShr(X, CV);
1487 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001488 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001489 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001490 }
1491
James Molloy2d09c002015-11-12 12:39:41 +00001492 case Intrinsic::bitreverse: {
1493 Value *IIOperand = II->getArgOperand(0);
1494 Value *X = nullptr;
1495
1496 // bitreverse(bitreverse(x)) -> x
1497 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001498 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001499 break;
1500 }
1501
Sanjay Patelb695c552016-02-01 17:00:10 +00001502 case Intrinsic::masked_load:
1503 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001504 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001505 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001506 case Intrinsic::masked_store:
1507 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001508 case Intrinsic::masked_gather:
1509 return simplifyMaskedGather(*II, *this);
1510 case Intrinsic::masked_scatter:
1511 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001512
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001513 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001514 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001515 // powi(x, 0) -> 1.0
1516 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001517 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001518 // powi(x, 1) -> x
1519 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001520 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001521 // powi(x, -1) -> 1/x
1522 if (Power->isAllOnesValue())
1523 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001524 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001525 }
1526 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001527
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001528 case Intrinsic::cttz:
1529 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001530 if (auto *I = foldCttzCtlz(*II, *this))
1531 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001532 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001533
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001534 case Intrinsic::uadd_with_overflow:
1535 case Intrinsic::sadd_with_overflow:
1536 case Intrinsic::umul_with_overflow:
1537 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001538 if (isa<Constant>(II->getArgOperand(0)) &&
1539 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001540 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001541 Value *LHS = II->getArgOperand(0);
1542 II->setArgOperand(0, II->getArgOperand(1));
1543 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001544 return II;
1545 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001546 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001547
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001548 case Intrinsic::usub_with_overflow:
1549 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001550 OverflowCheckFlavor OCF =
1551 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1552 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001553
Sanjoy Dasb0984472015-04-08 04:27:22 +00001554 Value *OperationResult = nullptr;
1555 Constant *OverflowResult = nullptr;
1556 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1557 *II, OperationResult, OverflowResult))
1558 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001559
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001560 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001561 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001562
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001563 case Intrinsic::minnum:
1564 case Intrinsic::maxnum: {
1565 Value *Arg0 = II->getArgOperand(0);
1566 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001567 // Canonicalize constants to the RHS.
1568 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001569 II->setArgOperand(0, Arg1);
1570 II->setArgOperand(1, Arg0);
1571 return II;
1572 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001573 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001574 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001575 break;
1576 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001577 case Intrinsic::ppc_altivec_lvx:
1578 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001579 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001580 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001581 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001582 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001583 PointerType::getUnqual(II->getType()));
1584 return new LoadInst(Ptr);
1585 }
1586 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001587 case Intrinsic::ppc_vsx_lxvw4x:
1588 case Intrinsic::ppc_vsx_lxvd2x: {
1589 // Turn PPC VSX loads into normal loads.
1590 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1591 PointerType::getUnqual(II->getType()));
1592 return new LoadInst(Ptr, Twine(""), false, 1);
1593 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001594 case Intrinsic::ppc_altivec_stvx:
1595 case Intrinsic::ppc_altivec_stvxl:
1596 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001597 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001598 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001599 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001600 PointerType::getUnqual(II->getArgOperand(0)->getType());
1601 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1602 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001603 }
1604 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001605 case Intrinsic::ppc_vsx_stxvw4x:
1606 case Intrinsic::ppc_vsx_stxvd2x: {
1607 // Turn PPC VSX stores into normal stores.
1608 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1609 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1610 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1611 }
Hal Finkel221f4672015-02-26 18:56:03 +00001612 case Intrinsic::ppc_qpx_qvlfs:
1613 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001614 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001615 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001616 Type *VTy = VectorType::get(Builder->getFloatTy(),
1617 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001618 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001619 PointerType::getUnqual(VTy));
1620 Value *Load = Builder->CreateLoad(Ptr);
1621 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001622 }
1623 break;
1624 case Intrinsic::ppc_qpx_qvlfd:
1625 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001626 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001627 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001628 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1629 PointerType::getUnqual(II->getType()));
1630 return new LoadInst(Ptr);
1631 }
1632 break;
1633 case Intrinsic::ppc_qpx_qvstfs:
1634 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001635 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001636 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001637 Type *VTy = VectorType::get(Builder->getFloatTy(),
1638 II->getArgOperand(0)->getType()->getVectorNumElements());
1639 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1640 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001641 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001642 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001643 }
1644 break;
1645 case Intrinsic::ppc_qpx_qvstfd:
1646 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001647 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00001648 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001649 Type *OpPtrTy =
1650 PointerType::getUnqual(II->getArgOperand(0)->getType());
1651 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1652 return new StoreInst(II->getArgOperand(0), Ptr);
1653 }
1654 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001655
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001656 case Intrinsic::x86_vcvtph2ps_128:
1657 case Intrinsic::x86_vcvtph2ps_256: {
1658 auto Arg = II->getArgOperand(0);
1659 auto ArgType = cast<VectorType>(Arg->getType());
1660 auto RetType = cast<VectorType>(II->getType());
1661 unsigned ArgWidth = ArgType->getNumElements();
1662 unsigned RetWidth = RetType->getNumElements();
1663 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1664 assert(ArgType->isIntOrIntVectorTy() &&
1665 ArgType->getScalarSizeInBits() == 16 &&
1666 "CVTPH2PS input type should be 16-bit integer vector");
1667 assert(RetType->getScalarType()->isFloatTy() &&
1668 "CVTPH2PS output type should be 32-bit float vector");
1669
1670 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001671 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001672 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001673
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001674 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001675 auto VectorHalfAsShorts = Arg;
1676 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00001677 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001678 for (unsigned i = 0; i != RetWidth; ++i)
1679 SubVecMask.push_back((int)i);
1680 VectorHalfAsShorts = Builder->CreateShuffleVector(
1681 Arg, UndefValue::get(ArgType), SubVecMask);
1682 }
1683
1684 auto VectorHalfType =
1685 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1686 auto VectorHalfs =
1687 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1688 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001689 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001690 }
1691
1692 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001693 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001694 II->setArgOperand(0, V);
1695 return II;
1696 }
1697 break;
1698 }
1699
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001700 case Intrinsic::x86_sse_cvtss2si:
1701 case Intrinsic::x86_sse_cvtss2si64:
1702 case Intrinsic::x86_sse_cvttss2si:
1703 case Intrinsic::x86_sse_cvttss2si64:
1704 case Intrinsic::x86_sse2_cvtsd2si:
1705 case Intrinsic::x86_sse2_cvtsd2si64:
1706 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00001707 case Intrinsic::x86_sse2_cvttsd2si64:
1708 case Intrinsic::x86_avx512_vcvtss2si32:
1709 case Intrinsic::x86_avx512_vcvtss2si64:
1710 case Intrinsic::x86_avx512_vcvtss2usi32:
1711 case Intrinsic::x86_avx512_vcvtss2usi64:
1712 case Intrinsic::x86_avx512_vcvtsd2si32:
1713 case Intrinsic::x86_avx512_vcvtsd2si64:
1714 case Intrinsic::x86_avx512_vcvtsd2usi32:
1715 case Intrinsic::x86_avx512_vcvtsd2usi64:
1716 case Intrinsic::x86_avx512_cvttss2si:
1717 case Intrinsic::x86_avx512_cvttss2si64:
1718 case Intrinsic::x86_avx512_cvttss2usi:
1719 case Intrinsic::x86_avx512_cvttss2usi64:
1720 case Intrinsic::x86_avx512_cvttsd2si:
1721 case Intrinsic::x86_avx512_cvttsd2si64:
1722 case Intrinsic::x86_avx512_cvttsd2usi:
1723 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001724 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001725 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001726 Value *Arg = II->getArgOperand(0);
1727 unsigned VWidth = Arg->getType()->getVectorNumElements();
1728 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001729 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001730 return II;
1731 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001732 break;
1733 }
1734
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00001735 case Intrinsic::x86_mmx_pmovmskb:
1736 case Intrinsic::x86_sse_movmsk_ps:
1737 case Intrinsic::x86_sse2_movmsk_pd:
1738 case Intrinsic::x86_sse2_pmovmskb_128:
1739 case Intrinsic::x86_avx_movmsk_pd_256:
1740 case Intrinsic::x86_avx_movmsk_ps_256:
1741 case Intrinsic::x86_avx2_pmovmskb: {
1742 if (Value *V = simplifyX86movmsk(*II, *Builder))
1743 return replaceInstUsesWith(*II, V);
1744 break;
1745 }
1746
Simon Pilgrim471efd22016-02-20 23:17:35 +00001747 case Intrinsic::x86_sse_comieq_ss:
1748 case Intrinsic::x86_sse_comige_ss:
1749 case Intrinsic::x86_sse_comigt_ss:
1750 case Intrinsic::x86_sse_comile_ss:
1751 case Intrinsic::x86_sse_comilt_ss:
1752 case Intrinsic::x86_sse_comineq_ss:
1753 case Intrinsic::x86_sse_ucomieq_ss:
1754 case Intrinsic::x86_sse_ucomige_ss:
1755 case Intrinsic::x86_sse_ucomigt_ss:
1756 case Intrinsic::x86_sse_ucomile_ss:
1757 case Intrinsic::x86_sse_ucomilt_ss:
1758 case Intrinsic::x86_sse_ucomineq_ss:
1759 case Intrinsic::x86_sse2_comieq_sd:
1760 case Intrinsic::x86_sse2_comige_sd:
1761 case Intrinsic::x86_sse2_comigt_sd:
1762 case Intrinsic::x86_sse2_comile_sd:
1763 case Intrinsic::x86_sse2_comilt_sd:
1764 case Intrinsic::x86_sse2_comineq_sd:
1765 case Intrinsic::x86_sse2_ucomieq_sd:
1766 case Intrinsic::x86_sse2_ucomige_sd:
1767 case Intrinsic::x86_sse2_ucomigt_sd:
1768 case Intrinsic::x86_sse2_ucomile_sd:
1769 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00001770 case Intrinsic::x86_sse2_ucomineq_sd:
1771 case Intrinsic::x86_avx512_mask_cmp_ss:
1772 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00001773 // These intrinsics only demand the 0th element of their input vectors. If
1774 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001775 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001776 Value *Arg0 = II->getArgOperand(0);
1777 Value *Arg1 = II->getArgOperand(1);
1778 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1779 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1780 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001781 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001782 }
1783 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1784 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001785 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001786 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001787 if (MadeChange)
1788 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001789 break;
1790 }
1791
Craig Topper790d0fa2016-12-11 07:42:01 +00001792 case Intrinsic::x86_avx512_mask_add_ss_round:
1793 case Intrinsic::x86_avx512_mask_div_ss_round:
1794 case Intrinsic::x86_avx512_mask_mul_ss_round:
1795 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00001796 case Intrinsic::x86_avx512_mask_add_sd_round:
1797 case Intrinsic::x86_avx512_mask_div_sd_round:
1798 case Intrinsic::x86_avx512_mask_mul_sd_round:
1799 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00001800 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
1801 // IR operations.
1802 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
1803 if (R->getValue() == 4) {
1804 // Only do this if the mask bit is 1 so that we don't need a select.
1805 // TODO: Improve this to handle masking cases. Isel doesn't fold
1806 // the mask correctly right now.
1807 if (auto *M = dyn_cast<ConstantInt>(II->getArgOperand(3))) {
1808 if (M->getValue()[0]) {
1809 // Extract the element as scalars.
1810 Value *Arg0 = II->getArgOperand(0);
1811 Value *Arg1 = II->getArgOperand(1);
1812 Value *LHS = Builder->CreateExtractElement(Arg0, (uint64_t)0);
1813 Value *RHS = Builder->CreateExtractElement(Arg1, (uint64_t)0);
1814
1815 Value *V;
1816 switch (II->getIntrinsicID()) {
1817 default: llvm_unreachable("Case stmts out of sync!");
1818 case Intrinsic::x86_avx512_mask_add_ss_round:
1819 case Intrinsic::x86_avx512_mask_add_sd_round:
1820 V = Builder->CreateFAdd(LHS, RHS);
1821 break;
1822 case Intrinsic::x86_avx512_mask_sub_ss_round:
1823 case Intrinsic::x86_avx512_mask_sub_sd_round:
1824 V = Builder->CreateFSub(LHS, RHS);
1825 break;
1826 case Intrinsic::x86_avx512_mask_mul_ss_round:
1827 case Intrinsic::x86_avx512_mask_mul_sd_round:
1828 V = Builder->CreateFMul(LHS, RHS);
1829 break;
1830 case Intrinsic::x86_avx512_mask_div_ss_round:
1831 case Intrinsic::x86_avx512_mask_div_sd_round:
1832 V = Builder->CreateFDiv(LHS, RHS);
1833 break;
1834 }
1835
1836 // Insert the result back into the original argument 0.
1837 V = Builder->CreateInsertElement(Arg0, V, (uint64_t)0);
1838
1839 return replaceInstUsesWith(*II, V);
1840 }
1841 }
1842 }
1843 }
1844 LLVM_FALLTHROUGH;
1845
1846 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
1847 case Intrinsic::x86_avx512_mask_max_ss_round:
1848 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00001849 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00001850 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Topperab5f3552016-12-15 03:49:45 +00001851 case Intrinsic::x86_avx512_mask_vfmadd_ss:
1852 case Intrinsic::x86_avx512_mask_vfmadd_sd:
1853 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
1854 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
1855 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
1856 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
1857 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
1858 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
1859 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
1860 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
Craig Topperdfd268d2016-12-14 05:43:05 +00001861 case Intrinsic::x86_fma_vfmadd_ss:
1862 case Intrinsic::x86_fma_vfmsub_ss:
1863 case Intrinsic::x86_fma_vfnmadd_ss:
1864 case Intrinsic::x86_fma_vfnmsub_ss:
1865 case Intrinsic::x86_fma_vfmadd_sd:
1866 case Intrinsic::x86_fma_vfmsub_sd:
1867 case Intrinsic::x86_fma_vfnmadd_sd:
1868 case Intrinsic::x86_fma_vfnmsub_sd:
Craig Toppera0372de2016-12-14 03:17:27 +00001869 case Intrinsic::x86_sse_cmp_ss:
1870 case Intrinsic::x86_sse_min_ss:
1871 case Intrinsic::x86_sse_max_ss:
1872 case Intrinsic::x86_sse2_cmp_sd:
1873 case Intrinsic::x86_sse2_min_sd:
1874 case Intrinsic::x86_sse2_max_sd:
Craig Toppereb6a20e2016-12-14 03:17:30 +00001875 case Intrinsic::x86_sse41_round_ss:
1876 case Intrinsic::x86_sse41_round_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00001877 case Intrinsic::x86_xop_vfrcz_ss:
1878 case Intrinsic::x86_xop_vfrcz_sd: {
1879 unsigned VWidth = II->getType()->getVectorNumElements();
1880 APInt UndefElts(VWidth, 0);
1881 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1882 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
1883 if (V != II)
1884 return replaceInstUsesWith(*II, V);
1885 return II;
1886 }
1887 break;
1888 }
1889
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001890 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001891 // Constant fold lshr( <A x Bi>, Ci ).
1892 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001893 case Intrinsic::x86_sse2_psrai_d:
1894 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001895 case Intrinsic::x86_avx2_psrai_d:
1896 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001897 case Intrinsic::x86_avx512_psrai_q_128:
1898 case Intrinsic::x86_avx512_psrai_q_256:
1899 case Intrinsic::x86_avx512_psrai_d_512:
1900 case Intrinsic::x86_avx512_psrai_q_512:
1901 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001902 case Intrinsic::x86_sse2_psrli_d:
1903 case Intrinsic::x86_sse2_psrli_q:
1904 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001905 case Intrinsic::x86_avx2_psrli_d:
1906 case Intrinsic::x86_avx2_psrli_q:
1907 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001908 case Intrinsic::x86_avx512_psrli_d_512:
1909 case Intrinsic::x86_avx512_psrli_q_512:
1910 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00001911 case Intrinsic::x86_sse2_pslli_d:
1912 case Intrinsic::x86_sse2_pslli_q:
1913 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001914 case Intrinsic::x86_avx2_pslli_d:
1915 case Intrinsic::x86_avx2_pslli_q:
1916 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001917 case Intrinsic::x86_avx512_pslli_d_512:
1918 case Intrinsic::x86_avx512_pslli_q_512:
1919 case Intrinsic::x86_avx512_pslli_w_512:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001920 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001921 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00001922 break;
1923
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001924 case Intrinsic::x86_sse2_psra_d:
1925 case Intrinsic::x86_sse2_psra_w:
1926 case Intrinsic::x86_avx2_psra_d:
1927 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001928 case Intrinsic::x86_avx512_psra_q_128:
1929 case Intrinsic::x86_avx512_psra_q_256:
1930 case Intrinsic::x86_avx512_psra_d_512:
1931 case Intrinsic::x86_avx512_psra_q_512:
1932 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001933 case Intrinsic::x86_sse2_psrl_d:
1934 case Intrinsic::x86_sse2_psrl_q:
1935 case Intrinsic::x86_sse2_psrl_w:
1936 case Intrinsic::x86_avx2_psrl_d:
1937 case Intrinsic::x86_avx2_psrl_q:
1938 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001939 case Intrinsic::x86_avx512_psrl_d_512:
1940 case Intrinsic::x86_avx512_psrl_q_512:
1941 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001942 case Intrinsic::x86_sse2_psll_d:
1943 case Intrinsic::x86_sse2_psll_q:
1944 case Intrinsic::x86_sse2_psll_w:
1945 case Intrinsic::x86_avx2_psll_d:
1946 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00001947 case Intrinsic::x86_avx2_psll_w:
1948 case Intrinsic::x86_avx512_psll_d_512:
1949 case Intrinsic::x86_avx512_psll_q_512:
1950 case Intrinsic::x86_avx512_psll_w_512: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001951 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001952 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001953
1954 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1955 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001956 Value *Arg1 = II->getArgOperand(1);
1957 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001958 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00001959 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001960
Simon Pilgrim996725e2015-09-19 11:41:53 +00001961 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001962 II->setArgOperand(1, V);
1963 return II;
1964 }
1965 break;
1966 }
1967
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001968 case Intrinsic::x86_avx2_psllv_d:
1969 case Intrinsic::x86_avx2_psllv_d_256:
1970 case Intrinsic::x86_avx2_psllv_q:
1971 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00001972 case Intrinsic::x86_avx512_psllv_d_512:
1973 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00001974 case Intrinsic::x86_avx512_psllv_w_128:
1975 case Intrinsic::x86_avx512_psllv_w_256:
1976 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001977 case Intrinsic::x86_avx2_psrav_d:
1978 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00001979 case Intrinsic::x86_avx512_psrav_q_128:
1980 case Intrinsic::x86_avx512_psrav_q_256:
1981 case Intrinsic::x86_avx512_psrav_d_512:
1982 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00001983 case Intrinsic::x86_avx512_psrav_w_128:
1984 case Intrinsic::x86_avx512_psrav_w_256:
1985 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001986 case Intrinsic::x86_avx2_psrlv_d:
1987 case Intrinsic::x86_avx2_psrlv_d_256:
1988 case Intrinsic::x86_avx2_psrlv_q:
1989 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00001990 case Intrinsic::x86_avx512_psrlv_d_512:
1991 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00001992 case Intrinsic::x86_avx512_psrlv_w_128:
1993 case Intrinsic::x86_avx512_psrlv_w_256:
1994 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001995 if (Value *V = simplifyX86varShift(*II, *Builder))
1996 return replaceInstUsesWith(*II, V);
1997 break;
1998
Sanjay Patelc86867c2015-04-16 17:52:13 +00001999 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002000 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002001 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002002 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002003
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002004 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002005 Value *Op0 = II->getArgOperand(0);
2006 Value *Op1 = II->getArgOperand(1);
2007 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2008 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002009 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2010 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2011 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002012
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002013 // See if we're dealing with constant values.
2014 Constant *C1 = dyn_cast<Constant>(Op1);
2015 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002016 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002017 : nullptr;
2018 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002019 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002020 : nullptr;
2021
2022 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002023 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002024 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002025
2026 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2027 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002028 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002029 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2030 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002031 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002032 }
2033 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2034 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002035 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002036 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002037 if (MadeChange)
2038 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002039 break;
2040 }
2041
2042 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002043 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2044 // bits of the lower 64-bits. The upper 64-bits are undefined.
2045 Value *Op0 = II->getArgOperand(0);
2046 unsigned VWidth = Op0->getType()->getVectorNumElements();
2047 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2048 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002049
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002050 // See if we're dealing with constant values.
2051 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2052 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2053
2054 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002055 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002056 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002057
2058 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2059 // operand.
2060 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002061 II->setArgOperand(0, V);
2062 return II;
2063 }
2064 break;
2065 }
2066
2067 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002068 Value *Op0 = II->getArgOperand(0);
2069 Value *Op1 = II->getArgOperand(1);
2070 unsigned VWidth = Op0->getType()->getVectorNumElements();
2071 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2072 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2073 Op1->getType()->getVectorNumElements() == 2 &&
2074 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002075
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002076 // See if we're dealing with constant values.
2077 Constant *C1 = dyn_cast<Constant>(Op1);
2078 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002079 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002080 : nullptr;
2081
2082 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2083 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002084 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002085 APInt Len = V11.zextOrTrunc(6);
2086 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002087 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002088 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002089 }
2090
2091 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2092 // operand.
2093 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002094 II->setArgOperand(0, V);
2095 return II;
2096 }
2097 break;
2098 }
2099
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002100 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002101 // INSERTQI: Extract lowest Length bits from lower half of second source and
2102 // insert over first source starting at Index bit. The upper 64-bits are
2103 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002104 Value *Op0 = II->getArgOperand(0);
2105 Value *Op1 = II->getArgOperand(1);
2106 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2107 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002108 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2109 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2110 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002111
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002112 // See if we're dealing with constant values.
2113 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2114 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2115
2116 // Attempt to simplify to a constant or shuffle vector.
2117 if (CILength && CIIndex) {
2118 APInt Len = CILength->getValue().zextOrTrunc(6);
2119 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002120 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002121 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002122 }
2123
2124 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2125 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002126 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002127 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2128 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002129 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002130 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002131 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2132 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002133 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002134 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002135 if (MadeChange)
2136 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002137 break;
2138 }
2139
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002140 case Intrinsic::x86_sse41_pblendvb:
2141 case Intrinsic::x86_sse41_blendvps:
2142 case Intrinsic::x86_sse41_blendvpd:
2143 case Intrinsic::x86_avx_blendv_ps_256:
2144 case Intrinsic::x86_avx_blendv_pd_256:
2145 case Intrinsic::x86_avx2_pblendvb: {
2146 // Convert blendv* to vector selects if the mask is constant.
2147 // This optimization is convoluted because the intrinsic is defined as
2148 // getting a vector of floats or doubles for the ps and pd versions.
2149 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002150
2151 Value *Op0 = II->getArgOperand(0);
2152 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002153 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002154
2155 // fold (blend A, A, Mask) -> A
2156 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002157 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002158
2159 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002160 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002161 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002162
2163 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002164 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2165 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002166 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002167 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002168 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002169 }
2170
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002171 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002172 case Intrinsic::x86_avx2_pshuf_b:
Craig Topper9a63d7a2016-12-11 00:23:50 +00002173 case Intrinsic::x86_avx512_pshuf_b_512:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002174 if (Value *V = simplifyX86pshufb(*II, *Builder))
2175 return replaceInstUsesWith(*II, V);
2176 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002177
Rafael Espindolabad3f772014-04-21 22:06:04 +00002178 case Intrinsic::x86_avx_vpermilvar_ps:
2179 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002180 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002181 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002182 case Intrinsic::x86_avx_vpermilvar_pd_256:
Craig Topper58917f32016-12-11 01:59:36 +00002183 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002184 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2185 return replaceInstUsesWith(*II, V);
2186 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002187
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002188 case Intrinsic::x86_avx2_permd:
2189 case Intrinsic::x86_avx2_permps:
2190 if (Value *V = simplifyX86vpermv(*II, *Builder))
2191 return replaceInstUsesWith(*II, V);
2192 break;
2193
Craig Toppere3280452016-12-25 23:58:57 +00002194 case Intrinsic::x86_avx512_mask_permvar_df_256:
2195 case Intrinsic::x86_avx512_mask_permvar_df_512:
2196 case Intrinsic::x86_avx512_mask_permvar_di_256:
2197 case Intrinsic::x86_avx512_mask_permvar_di_512:
2198 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2199 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2200 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2201 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2202 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2203 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2204 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2205 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2206 case Intrinsic::x86_avx512_mask_permvar_si_256:
2207 case Intrinsic::x86_avx512_mask_permvar_si_512:
2208 if (Value *V = simplifyX86vpermv(*II, *Builder)) {
2209 // We simplified the permuting, now create a select for the masking.
2210 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2211 *Builder);
2212 return replaceInstUsesWith(*II, V);
2213 }
2214 break;
2215
Sanjay Patelccf5f242015-03-20 21:47:56 +00002216 case Intrinsic::x86_avx_vperm2f128_pd_256:
2217 case Intrinsic::x86_avx_vperm2f128_ps_256:
2218 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002219 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002220 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002221 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002222 break;
2223
Sanjay Patel98a71502016-02-29 23:16:48 +00002224 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002225 case Intrinsic::x86_avx_maskload_pd:
2226 case Intrinsic::x86_avx_maskload_ps_256:
2227 case Intrinsic::x86_avx_maskload_pd_256:
2228 case Intrinsic::x86_avx2_maskload_d:
2229 case Intrinsic::x86_avx2_maskload_q:
2230 case Intrinsic::x86_avx2_maskload_d_256:
2231 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002232 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2233 return I;
2234 break;
2235
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002236 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002237 case Intrinsic::x86_avx_maskstore_ps:
2238 case Intrinsic::x86_avx_maskstore_pd:
2239 case Intrinsic::x86_avx_maskstore_ps_256:
2240 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002241 case Intrinsic::x86_avx2_maskstore_d:
2242 case Intrinsic::x86_avx2_maskstore_q:
2243 case Intrinsic::x86_avx2_maskstore_d_256:
2244 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002245 if (simplifyX86MaskedStore(*II, *this))
2246 return nullptr;
2247 break;
2248
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002249 case Intrinsic::x86_xop_vpcomb:
2250 case Intrinsic::x86_xop_vpcomd:
2251 case Intrinsic::x86_xop_vpcomq:
2252 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002253 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002254 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002255 break;
2256
2257 case Intrinsic::x86_xop_vpcomub:
2258 case Intrinsic::x86_xop_vpcomud:
2259 case Intrinsic::x86_xop_vpcomuq:
2260 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002261 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002262 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002263 break;
2264
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002265 case Intrinsic::ppc_altivec_vperm:
2266 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002267 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2268 // a vectorshuffle for little endian, we must undo the transformation
2269 // performed on vec_perm in altivec.h. That is, we must complement
2270 // the permutation mask with respect to 31 and reverse the order of
2271 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002272 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2273 assert(Mask->getType()->getVectorNumElements() == 16 &&
2274 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002275
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002276 // Check that all of the elements are integer constants or undefs.
2277 bool AllEltsOk = true;
2278 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002279 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002280 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002281 AllEltsOk = false;
2282 break;
2283 }
2284 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002285
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002286 if (AllEltsOk) {
2287 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002288 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2289 Mask->getType());
2290 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2291 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002292 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002293
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002294 // Only extract each element once.
2295 Value *ExtractedElts[32];
2296 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002297
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002298 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002299 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002300 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002301 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002302 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002303 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002304 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002305 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002306
Craig Topperf40110f2014-04-25 05:29:35 +00002307 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002308 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2309 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002310 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002311 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002312 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002313 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002314
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002315 // Insert this value into the result vector.
2316 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002317 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002318 }
2319 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2320 }
2321 }
2322 break;
2323
Bob Wilsona4e231c2010-10-22 21:41:48 +00002324 case Intrinsic::arm_neon_vld1:
2325 case Intrinsic::arm_neon_vld2:
2326 case Intrinsic::arm_neon_vld3:
2327 case Intrinsic::arm_neon_vld4:
2328 case Intrinsic::arm_neon_vld2lane:
2329 case Intrinsic::arm_neon_vld3lane:
2330 case Intrinsic::arm_neon_vld4lane:
2331 case Intrinsic::arm_neon_vst1:
2332 case Intrinsic::arm_neon_vst2:
2333 case Intrinsic::arm_neon_vst3:
2334 case Intrinsic::arm_neon_vst4:
2335 case Intrinsic::arm_neon_vst2lane:
2336 case Intrinsic::arm_neon_vst3lane:
2337 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00002338 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002339 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002340 unsigned AlignArg = II->getNumArgOperands() - 1;
2341 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2342 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2343 II->setArgOperand(AlignArg,
2344 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2345 MemAlign, false));
2346 return II;
2347 }
2348 break;
2349 }
2350
Lang Hames3a90fab2012-05-01 00:20:38 +00002351 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00002352 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00002353 case Intrinsic::aarch64_neon_smull:
2354 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00002355 Value *Arg0 = II->getArgOperand(0);
2356 Value *Arg1 = II->getArgOperand(1);
2357
2358 // Handle mul by zero first:
2359 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002360 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00002361 }
2362
2363 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00002364 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00002365 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00002366 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00002367 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2368 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2369 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2370 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2371
Sanjay Patel4b198802016-02-01 22:23:39 +00002372 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00002373 }
2374
Alp Tokercb402912014-01-24 17:20:08 +00002375 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00002376 std::swap(Arg0, Arg1);
2377 }
2378
2379 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00002380 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00002381 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00002382 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2383 if (Splat->isOne())
2384 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2385 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00002386
2387 break;
2388 }
2389
Matt Arsenaultbef34e22016-01-22 21:30:34 +00002390 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002391 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2392 const APFloat &ArgVal = C->getValueAPF();
2393 APFloat Val(ArgVal.getSemantics(), 1.0);
2394 APFloat::opStatus Status = Val.divide(ArgVal,
2395 APFloat::rmNearestTiesToEven);
2396 // Only do this if it was exact and therefore not dependent on the
2397 // rounding mode.
2398 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00002399 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002400 }
2401
2402 break;
2403 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002404 case Intrinsic::amdgcn_frexp_mant:
2405 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002406 Value *Src = II->getArgOperand(0);
2407 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2408 int Exp;
2409 APFloat Significand = frexp(C->getValueAPF(), Exp,
2410 APFloat::rmNearestTiesToEven);
2411
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002412 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2413 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2414 Significand));
2415 }
2416
2417 // Match instruction special case behavior.
2418 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2419 Exp = 0;
2420
2421 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2422 }
2423
2424 if (isa<UndefValue>(Src))
2425 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002426
2427 break;
2428 }
Matt Arsenault46a03822016-09-03 07:06:58 +00002429 case Intrinsic::amdgcn_class: {
2430 enum {
2431 S_NAN = 1 << 0, // Signaling NaN
2432 Q_NAN = 1 << 1, // Quiet NaN
2433 N_INFINITY = 1 << 2, // Negative infinity
2434 N_NORMAL = 1 << 3, // Negative normal
2435 N_SUBNORMAL = 1 << 4, // Negative subnormal
2436 N_ZERO = 1 << 5, // Negative zero
2437 P_ZERO = 1 << 6, // Positive zero
2438 P_SUBNORMAL = 1 << 7, // Positive subnormal
2439 P_NORMAL = 1 << 8, // Positive normal
2440 P_INFINITY = 1 << 9 // Positive infinity
2441 };
2442
2443 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
2444 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
2445
2446 Value *Src0 = II->getArgOperand(0);
2447 Value *Src1 = II->getArgOperand(1);
2448 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
2449 if (!CMask) {
2450 if (isa<UndefValue>(Src0))
2451 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2452
2453 if (isa<UndefValue>(Src1))
2454 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2455 break;
2456 }
2457
2458 uint32_t Mask = CMask->getZExtValue();
2459
2460 // If all tests are made, it doesn't matter what the value is.
2461 if ((Mask & FullMask) == FullMask)
2462 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
2463
2464 if ((Mask & FullMask) == 0)
2465 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2466
2467 if (Mask == (S_NAN | Q_NAN)) {
2468 // Equivalent of isnan. Replace with standard fcmp.
2469 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
2470 FCmp->takeName(II);
2471 return replaceInstUsesWith(*II, FCmp);
2472 }
2473
2474 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
2475 if (!CVal) {
2476 if (isa<UndefValue>(Src0))
2477 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2478
2479 // Clamp mask to used bits
2480 if ((Mask & FullMask) != Mask) {
2481 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
2482 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
2483 );
2484
2485 NewCall->takeName(II);
2486 return replaceInstUsesWith(*II, NewCall);
2487 }
2488
2489 break;
2490 }
2491
2492 const APFloat &Val = CVal->getValueAPF();
2493
2494 bool Result =
2495 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
2496 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
2497 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
2498 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
2499 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
2500 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
2501 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
2502 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
2503 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
2504 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
2505
2506 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
2507 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002508 case Intrinsic::stackrestore: {
2509 // If the save is right next to the restore, remove the restore. This can
2510 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002511 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002512 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002513 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002514 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002515 }
2516 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002517
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002518 // Scan down this block to see if there is another stack restore in the
2519 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002520 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002521 TerminatorInst *TI = II->getParent()->getTerminator();
2522 bool CannotRemove = false;
2523 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002524 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002525 CannotRemove = true;
2526 break;
2527 }
2528 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2529 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2530 // If there is a stackrestore below this one, remove this one.
2531 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002532 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002533
2534 // Bail if we cross over an intrinsic with side effects, such as
2535 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2536 if (II->mayHaveSideEffects()) {
2537 CannotRemove = true;
2538 break;
2539 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002540 } else {
2541 // If we found a non-intrinsic call, we can't remove the stack
2542 // restore.
2543 CannotRemove = true;
2544 break;
2545 }
2546 }
2547 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002548
Bill Wendlingf891bf82011-07-31 06:30:59 +00002549 // If the stack restore is in a return, resume, or unwind block and if there
2550 // are no allocas or calls between the restore and the return, nuke the
2551 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002552 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002553 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002554 break;
2555 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00002556 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00002557 // Asan needs to poison memory to detect invalid access which is possible
2558 // even for empty lifetime range.
2559 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2560 break;
2561
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00002562 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2563 Intrinsic::lifetime_end, *this))
2564 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002565 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00002566 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002567 Value *IIOperand = II->getArgOperand(0);
2568 // Remove an assume if it is immediately followed by an identical assume.
2569 if (match(II->getNextNode(),
2570 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2571 return eraseInstFromFunction(CI);
2572
Hal Finkelf5867a72014-07-25 21:45:17 +00002573 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002574 // Note: New assumption intrinsics created here are registered by
2575 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002576 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002577 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2578 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2579 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002580 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002581 }
2582 // assume(!(a || b)) -> assume(!a); assume(!b);
2583 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002584 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2585 II->getName());
2586 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2587 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002588 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002589 }
Hal Finkel04a15612014-10-04 21:27:06 +00002590
Philip Reames66c6de62014-11-11 23:33:19 +00002591 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2592 // (if assume is valid at the load)
2593 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2594 Value *LHS = ICmp->getOperand(0);
2595 Value *RHS = ICmp->getOperand(1);
2596 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2597 isa<LoadInst>(LHS) &&
2598 isa<Constant>(RHS) &&
2599 RHS->getType()->isPointerTy() &&
2600 cast<Constant>(RHS)->isNullValue()) {
2601 LoadInst* LI = cast<LoadInst>(LHS);
Justin Bogner99798402016-08-05 01:06:44 +00002602 if (isValidAssumeForContext(II, LI, &DT)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002603 MDNode *MD = MDNode::get(II->getContext(), None);
Philip Reames66c6de62014-11-11 23:33:19 +00002604 LI->setMetadata(LLVMContext::MD_nonnull, MD);
Sanjay Patel4b198802016-02-01 22:23:39 +00002605 return eraseInstFromFunction(*II);
Philip Reames66c6de62014-11-11 23:33:19 +00002606 }
2607 }
Chandler Carruth24969102015-02-10 08:07:32 +00002608 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002609 // TODO: apply range metadata for range check patterns?
2610 }
Hal Finkel04a15612014-10-04 21:27:06 +00002611 // If there is a dominating assume with the same condition as this one,
2612 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002613 APInt KnownZero(1, 0), KnownOne(1, 0);
2614 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2615 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002616 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002617
Hal Finkelf5867a72014-07-25 21:45:17 +00002618 break;
2619 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002620 case Intrinsic::experimental_gc_relocate: {
2621 // Translate facts known about a pointer before relocating into
2622 // facts about the relocate value, while being careful to
2623 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002624 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002625
2626 // Remove the relocation if unused, note that this check is required
2627 // to prevent the cases below from looping forever.
2628 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002629 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002630
2631 // Undef is undef, even after relocation.
2632 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2633 // most practical collectors, but there was discussion in the review thread
2634 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002635 if (isa<UndefValue>(DerivedPtr))
2636 // Use undef of gc_relocate's type to replace it.
2637 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002638
Philip Reamesea4d8e82016-02-09 21:09:22 +00002639 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2640 // The relocation of null will be null for most any collector.
2641 // TODO: provide a hook for this in GCStrategy. There might be some
2642 // weird collector this property does not hold for.
2643 if (isa<ConstantPointerNull>(DerivedPtr))
2644 // Use null-pointer of gc_relocate's type to replace it.
2645 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002646
Philip Reamesea4d8e82016-02-09 21:09:22 +00002647 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00002648 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00002649 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002650 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002651
2652 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2653 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002654
Philip Reames9db26ff2014-12-29 23:27:30 +00002655 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002656 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002657 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002658 }
2659
2660 return visitCallSite(II);
2661}
2662
2663// InvokeInst simplification
2664//
2665Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2666 return visitCallSite(&II);
2667}
2668
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002669/// If this cast does not affect the value passed through the varargs area, we
2670/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002671static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002672 const DataLayout &DL,
2673 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002674 const int ix) {
2675 if (!CI->isLosslessCast())
2676 return false;
2677
Philip Reames1a1bdb22014-12-02 18:50:36 +00002678 // If this is a GC intrinsic, avoid munging types. We need types for
2679 // statepoint reconstruction in SelectionDAG.
2680 // TODO: This is probably something which should be expanded to all
2681 // intrinsics since the entire point of intrinsics is that
2682 // they are understandable by the optimizer.
2683 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2684 return false;
2685
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002686 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002687 // can't change to a type with a different size. If the size were
2688 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002689 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002690 return true;
2691
Jim Grosbach7815f562012-02-03 00:07:04 +00002692 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002693 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002694 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002695 if (!SrcTy->isSized() || !DstTy->isSized())
2696 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002697 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002698 return false;
2699 return true;
2700}
2701
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002702Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002703 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002704
Chandler Carruthba4c5172015-01-21 11:23:40 +00002705 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002706 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002707 };
Justin Bogner99798402016-08-05 01:06:44 +00002708 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002709 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002710 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002711 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002712 }
Meador Ingedf796f82012-10-13 16:45:24 +00002713
Craig Topperf40110f2014-04-25 05:29:35 +00002714 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002715}
2716
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002717static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002718 // Strip off at most one level of pointer casts, looking for an alloca. This
2719 // is good enough in practice and simpler than handling any number of casts.
2720 Value *Underlying = TrampMem->stripPointerCasts();
2721 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002722 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002723 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002724 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002725 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002726
Craig Topperf40110f2014-04-25 05:29:35 +00002727 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002728 for (User *U : TrampMem->users()) {
2729 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002730 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002731 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002732 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2733 if (InitTrampoline)
2734 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002735 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002736 InitTrampoline = II;
2737 continue;
2738 }
2739 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2740 // Allow any number of calls to adjust.trampoline.
2741 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002742 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002743 }
2744
2745 // No call to init.trampoline found.
2746 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002747 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002748
2749 // Check that the alloca is being used in the expected way.
2750 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002751 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002752
2753 return InitTrampoline;
2754}
2755
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002756static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002757 Value *TrampMem) {
2758 // Visit all the previous instructions in the basic block, and try to find a
2759 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002760 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2761 E = AdjustTramp->getParent()->begin();
2762 I != E;) {
2763 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00002764 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2765 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2766 II->getOperand(0) == TrampMem)
2767 return II;
2768 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00002769 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002770 }
Craig Topperf40110f2014-04-25 05:29:35 +00002771 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002772}
2773
2774// Given a call to llvm.adjust.trampoline, find and return the corresponding
2775// call to llvm.init.trampoline if the call to the trampoline can be optimized
2776// to a direct call to a function. Otherwise return NULL.
2777//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002778static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002779 Callee = Callee->stripPointerCasts();
2780 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2781 if (!AdjustTramp ||
2782 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002783 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002784
2785 Value *TrampMem = AdjustTramp->getOperand(0);
2786
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002787 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002788 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002789 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002790 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00002791 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002792}
2793
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002794/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002795Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00002796 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002797 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002798
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002799 bool Changed = false;
2800
Philip Reamesc25df112015-06-16 20:24:25 +00002801 // Mark any parameters that are known to be non-null with the nonnull
2802 // attribute. This is helpful for inlining calls to functions with null
2803 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00002804 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00002805 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00002806
Philip Reamesc25df112015-06-16 20:24:25 +00002807 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00002808 if (V->getType()->isPointerTy() &&
2809 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00002810 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00002811 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00002812 ArgNo++;
2813 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00002814
Philip Reamesc25df112015-06-16 20:24:25 +00002815 assert(ArgNo == CS.arg_size() && "sanity check");
2816
Akira Hatanaka237916b2015-12-02 06:58:49 +00002817 if (!Indices.empty()) {
2818 AttributeSet AS = CS.getAttributes();
2819 LLVMContext &Ctx = CS.getInstruction()->getContext();
2820 AS = AS.addAttribute(Ctx, Indices,
2821 Attribute::get(Ctx, Attribute::NonNull));
2822 CS.setAttributes(AS);
2823 Changed = true;
2824 }
2825
Chris Lattner73989652010-12-20 08:25:06 +00002826 // If the callee is a pointer to a function, attempt to move any casts to the
2827 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002828 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00002829 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00002830 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002831
Justin Lebar9d943972016-03-14 20:18:54 +00002832 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2833 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00002834 if (CS.isConvergent() && !CalleeF->isConvergent() &&
2835 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00002836 DEBUG(dbgs() << "Removing convergent attr from instr "
2837 << CS.getInstruction() << "\n");
2838 CS.setNotConvergent();
2839 return CS.getInstruction();
2840 }
2841
Chris Lattner846a52e2010-02-01 18:11:34 +00002842 // If the call and callee calling conventions don't match, this call must
2843 // be unreachable, as the call is undefined.
2844 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2845 // Only do this for calls to a function with a body. A prototype may
2846 // not actually end up matching the implementation's calling conv for a
2847 // variety of reasons (e.g. it may be written in assembly).
2848 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002849 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002850 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00002851 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002852 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00002853 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002854 // This allows ValueHandlers and custom metadata to adjust itself.
2855 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002856 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00002857 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00002858 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00002859
Chris Lattner2cecedf2010-02-01 18:04:58 +00002860 // We cannot remove an invoke, because it would change the CFG, just
2861 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00002862 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00002863 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00002864 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002865 }
Justin Lebar9d943972016-03-14 20:18:54 +00002866 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002867
2868 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002869 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002870 // This allows ValueHandlers and custom metadata to adjust itself.
2871 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002872 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002873 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002874
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002875 if (isa<InvokeInst>(CS.getInstruction())) {
2876 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00002877 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002878 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002879
2880 // This instruction is not reachable, just remove it. We insert a store to
2881 // undef so that we know that this code is not reachable, despite the fact
2882 // that we can't modify the CFG here.
2883 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2884 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2885 CS.getInstruction());
2886
Sanjay Patel4b198802016-02-01 22:23:39 +00002887 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002888 }
2889
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002890 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00002891 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002892
Chris Lattner229907c2011-07-18 04:54:35 +00002893 PointerType *PTy = cast<PointerType>(Callee->getType());
2894 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002895 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00002896 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002897 // See if we can optimize any arguments passed through the varargs area of
2898 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002899 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002900 E = CS.arg_end(); I != E; ++I, ++ix) {
2901 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002902 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002903 *I = CI->getOperand(0);
2904 Changed = true;
2905 }
2906 }
2907 }
2908
2909 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2910 // Inline asm calls cannot throw - mark them 'nounwind'.
2911 CS.setDoesNotThrow();
2912 Changed = true;
2913 }
2914
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002915 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00002916 // this. None of these calls are seen as possibly dead so go ahead and
2917 // delete the instruction now.
2918 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002919 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00002920 // If we changed something return the result, etc. Otherwise let
2921 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00002922 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00002923 }
2924
Craig Topperf40110f2014-04-25 05:29:35 +00002925 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002926}
2927
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002928/// If the callee is a constexpr cast of a function, attempt to move the cast to
2929/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002930bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00002931 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00002932 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002933 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002934
2935 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00002936 if (Callee->hasFnAttribute("thunk"))
2937 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002938
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002939 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00002940 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002941
2942 // Okay, this is a cast from a function to a different type. Unless doing so
2943 // would cause a type conversion of one of our arguments, change this call to
2944 // be a direct call with arguments casted to the appropriate types.
2945 //
Chris Lattner229907c2011-07-18 04:54:35 +00002946 FunctionType *FT = Callee->getFunctionType();
2947 Type *OldRetTy = Caller->getType();
2948 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002949
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002950 // Check to see if we are changing the return type...
2951 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00002952
2953 if (NewRetTy->isStructTy())
2954 return false; // TODO: Handle multiple return values.
2955
David Majnemer9b6b8222015-01-06 08:41:31 +00002956 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002957 if (Callee->isDeclaration())
2958 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002959
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002960 if (!Caller->use_empty() &&
2961 // void -> non-void is handled specially
2962 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00002963 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002964 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002965
2966 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00002967 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00002968 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002969 return false; // Attribute not compatible with transformed value.
2970 }
2971
2972 // If the callsite is an invoke instruction, and the return value is used by
2973 // a PHI node in a successor, we cannot change the return type of the call
2974 // because there is no place to put the cast instruction (without breaking
2975 // the critical edge). Bail out in this case.
2976 if (!Caller->use_empty())
2977 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002978 for (User *U : II->users())
2979 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002980 if (PN->getParent() == II->getNormalDest() ||
2981 PN->getParent() == II->getUnwindDest())
2982 return false;
2983 }
2984
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002985 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002986 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2987
David Majnemer9b6b8222015-01-06 08:41:31 +00002988 // Prevent us turning:
2989 // declare void @takes_i32_inalloca(i32* inalloca)
2990 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2991 //
2992 // into:
2993 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00002994 //
2995 // Similarly, avoid folding away bitcasts of byval calls.
2996 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2997 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00002998 return false;
2999
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003000 CallSite::arg_iterator AI = CS.arg_begin();
3001 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003002 Type *ParamTy = FT->getParamType(i);
3003 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003004
David Majnemer9b6b8222015-01-06 08:41:31 +00003005 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003006 return false; // Cannot transform this parameter value.
3007
Bill Wendling49bc76c2013-01-23 06:14:59 +00003008 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00003009 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003010 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00003011
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003012 if (CS.isInAllocaArgument(i))
3013 return false; // Cannot transform to and from inalloca.
3014
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003015 // If the parameter is passed as a byval argument, then we have to have a
3016 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003017 if (ParamTy != ActTy &&
3018 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
3019 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00003020 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003021 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003022 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00003023
Matt Arsenaultfa252722013-09-27 22:18:51 +00003024 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003025 if (DL.getTypeAllocSize(CurElTy) !=
3026 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003027 return false;
3028 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003029 }
3030
Chris Lattneradf38b32011-02-24 05:10:56 +00003031 if (Callee->isDeclaration()) {
3032 // Do not delete arguments unless we have a function body.
3033 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3034 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003035
Chris Lattneradf38b32011-02-24 05:10:56 +00003036 // If the callee is just a declaration, don't change the varargsness of the
3037 // call. We don't want to introduce a varargs call where one doesn't
3038 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00003039 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00003040 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
3041 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003042
3043 // If both the callee and the cast type are varargs, we still have to make
3044 // sure the number of fixed parameters are the same or we have the same
3045 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00003046 if (FT->isVarArg() &&
3047 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
3048 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003049 cast<FunctionType>(APTy->getElementType())->getNumParams())
3050 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00003051 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003052
Jim Grosbach0ab54182012-02-03 00:00:50 +00003053 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3054 !CallerPAL.isEmpty())
3055 // In this case we have more arguments than the new function type, but we
3056 // won't be dropping them. Check that these extra arguments have attributes
3057 // that are compatible with being a vararg call argument.
3058 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00003059 unsigned Index = CallerPAL.getSlotIndex(i - 1);
3060 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00003061 break;
Bill Wendling57625a42013-01-25 23:09:36 +00003062
Bill Wendlingd97b75d2012-12-19 08:57:40 +00003063 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00003064 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
3065 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00003066 return false;
3067 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003068
Jim Grosbach7815f562012-02-03 00:07:04 +00003069
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003070 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00003071 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003072 std::vector<Value*> Args;
3073 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003074 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003075 attrVec.reserve(NumCommonArgs);
3076
3077 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003078 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003079
3080 // If the return value is not being used, the type may not be compatible
3081 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00003082 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003083
3084 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00003085 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003086 attrVec.push_back(AttributeSet::get(Caller->getContext(),
3087 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003088
3089 AI = CS.arg_begin();
3090 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003091 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00003092
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003093 if ((*AI)->getType() == ParamTy) {
3094 Args.push_back(*AI);
3095 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00003096 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003097 }
3098
3099 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003100 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003101 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003102 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
3103 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003104 }
3105
3106 // If the function takes more arguments than the call was taking, add them
3107 // now.
3108 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3109 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3110
3111 // If we are removing arguments to the function, emit an obnoxious warning.
3112 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00003113 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3114 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003115 // Add all of the arguments in their promoted form to the arg list.
3116 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003117 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003118 if (PTy != (*AI)->getType()) {
3119 // Must promote to pass through va_arg area!
3120 Instruction::CastOps opcode =
3121 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003122 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003123 } else {
3124 Args.push_back(*AI);
3125 }
3126
3127 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003128 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003129 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003130 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
3131 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003132 }
3133 }
3134 }
3135
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003136 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00003137 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003138 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003139
3140 if (NewRetTy->isVoidTy())
3141 Caller->setName(""); // Void type should not have a name.
3142
Bill Wendlinge94d8432012-12-07 23:16:57 +00003143 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003144 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003145
Sanjoy Das76293462015-11-25 00:42:19 +00003146 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00003147 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00003148
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003149 Instruction *NC;
3150 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00003151 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
3152 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003153 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003154 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
3155 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
3156 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003157 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00003158 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003159 NC->takeName(CI);
David Majnemerd5648c72016-11-25 22:35:09 +00003160 cast<CallInst>(NC)->setTailCallKind(CI->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003161 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
3162 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
3163 }
3164
3165 // Insert a cast of the return type as necessary.
3166 Value *NV = NC;
3167 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3168 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00003169 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00003170 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003171
3172 // If this is an invoke instruction, we should insert it after the first
3173 // non-phi, instruction in the normal successor block.
3174 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00003175 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003176 InsertNewInstBefore(NC, *I);
3177 } else {
Chris Lattner73989652010-12-20 08:25:06 +00003178 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003179 InsertNewInstBefore(NC, *Caller);
3180 }
3181 Worklist.AddUsersToWorkList(*Caller);
3182 } else {
3183 NV = UndefValue::get(Caller->getType());
3184 }
3185 }
3186
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003187 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003188 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00003189 else if (Caller->hasValueHandle()) {
3190 if (OldRetTy == NV->getType())
3191 ValueHandleBase::ValueIsRAUWd(Caller, NV);
3192 else
3193 // We cannot call ValueIsRAUWd with a different type, and the
3194 // actual tracked value will disappear.
3195 ValueHandleBase::ValueIsDeleted(Caller);
3196 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003197
Sanjay Patel4b198802016-02-01 22:23:39 +00003198 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003199 return true;
3200}
3201
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003202/// Turn a call to a function created by init_trampoline / adjust_trampoline
3203/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00003204Instruction *
3205InstCombiner::transformCallThroughTrampoline(CallSite CS,
3206 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003207 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00003208 PointerType *PTy = cast<PointerType>(Callee->getType());
3209 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00003210 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003211
3212 // If the call already has the 'nest' attribute somewhere then give up -
3213 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00003214 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00003215 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003216
Duncan Sandsa0984362011-09-06 13:37:06 +00003217 assert(Tramp &&
3218 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003219
Gabor Greif3e44ea12010-07-22 10:37:47 +00003220 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003221 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003222
Bill Wendlinge94d8432012-12-07 23:16:57 +00003223 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003224 if (!NestAttrs.isEmpty()) {
3225 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00003226 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00003227 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003228
3229 // Look for a parameter marked with the 'nest' attribute.
3230 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3231 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00003232 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003233 // Record the parameter type and any other attributes.
3234 NestTy = *I;
3235 NestAttr = NestAttrs.getParamAttributes(NestIdx);
3236 break;
3237 }
3238
3239 if (NestTy) {
3240 Instruction *Caller = CS.getInstruction();
3241 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003242 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003243
Bill Wendling3575c8c2013-01-27 02:08:22 +00003244 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003245 NewAttrs.reserve(Attrs.getNumSlots() + 1);
3246
3247 // Insert the nest argument into the call argument list, which may
3248 // mean appending it. Likewise for attributes.
3249
3250 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003251 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003252 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3253 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003254
3255 {
3256 unsigned Idx = 1;
3257 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3258 do {
3259 if (Idx == NestIdx) {
3260 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00003261 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003262 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00003263 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003264 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003265 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3266 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003267 }
3268
3269 if (I == E)
3270 break;
3271
3272 // Add the original argument and attributes.
3273 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00003274 AttributeSet Attr = Attrs.getParamAttributes(Idx);
3275 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00003276 AttrBuilder B(Attr, Idx);
3277 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3278 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00003279 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003280
Richard Trieu7a083812016-02-18 22:09:30 +00003281 ++Idx;
3282 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003283 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003284 }
3285
3286 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00003287 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003288 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3289 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003290
3291 // The trampoline may have been bitcast to a bogus type (FTy).
3292 // Handle this by synthesizing a new function type, equal to FTy
3293 // with the chain parameter inserted.
3294
Jay Foadb804a2b2011-07-12 14:06:48 +00003295 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003296 NewTypes.reserve(FTy->getNumParams()+1);
3297
3298 // Insert the chain's type into the list of parameter types, which may
3299 // mean appending it.
3300 {
3301 unsigned Idx = 1;
3302 FunctionType::param_iterator I = FTy->param_begin(),
3303 E = FTy->param_end();
3304
3305 do {
3306 if (Idx == NestIdx)
3307 // Add the chain's type.
3308 NewTypes.push_back(NestTy);
3309
3310 if (I == E)
3311 break;
3312
3313 // Add the original type.
3314 NewTypes.push_back(*I);
3315
Richard Trieu7a083812016-02-18 22:09:30 +00003316 ++Idx;
3317 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003318 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003319 }
3320
3321 // Replace the trampoline call with a direct call. Let the generic
3322 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00003323 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003324 FTy->isVarArg());
3325 Constant *NewCallee =
3326 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00003327 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003328 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00003329 const AttributeSet &NewPAL =
3330 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003331
David Majnemer231a68c2016-04-29 08:07:20 +00003332 SmallVector<OperandBundleDef, 1> OpBundles;
3333 CS.getOperandBundlesAsDefs(OpBundles);
3334
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003335 Instruction *NewCaller;
3336 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3337 NewCaller = InvokeInst::Create(NewCallee,
3338 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00003339 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003340 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3341 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3342 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00003343 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00003344 cast<CallInst>(NewCaller)->setTailCallKind(
3345 cast<CallInst>(Caller)->getTailCallKind());
3346 cast<CallInst>(NewCaller)->setCallingConv(
3347 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003348 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3349 }
Eli Friedman49346012011-05-18 19:57:14 +00003350
3351 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003352 }
3353 }
3354
3355 // Replace the trampoline call with a direct call. Since there is no 'nest'
3356 // parameter, there is no need to adjust the argument list. Let the generic
3357 // code sort out any function type mismatches.
3358 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00003359 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003360 ConstantExpr::getBitCast(NestF, PTy);
3361 CS.setCalledFunction(NewCallee);
3362 return CS.getInstruction();
3363}