blob: 9de103a6a1185c5fd7646fc155b9b51357828d46 [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Meador Ingee3f2b262012-11-30 04:05:06 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Twine.h"
David Majnemer15032582015-05-22 03:56:46 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000025#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/IR/Constant.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Intrinsics.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000041#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000042#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
44#include "llvm/IR/ValueHandle.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/MathExtras.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000048#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include <algorithm>
51#include <cassert>
52#include <cstdint>
53#include <cstring>
54#include <vector>
55
Chris Lattner7a9e47a2010-01-05 07:32:13 +000056using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000057using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000058
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "instcombine"
60
Meador Ingee3f2b262012-11-30 04:05:06 +000061STATISTIC(NumSimplified, "Number of library calls simplified");
62
Sanjay Patelcd4377c2016-01-20 22:24:38 +000063/// Return the specified type promoted as it would be to pass though a va_arg
64/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000065static Type *getPromotedType(Type *Ty) {
66 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000067 if (ITy->getBitWidth() < 32)
68 return Type::getInt32Ty(Ty->getContext());
69 }
70 return Ty;
71}
72
Sanjay Patelcd4377c2016-01-20 22:24:38 +000073/// Given an aggregate type which ultimately holds a single scalar element,
74/// like {{{type}}} or [1 x type], return type.
Dan Gohmand0080c42012-09-13 18:19:06 +000075static Type *reduceToSingleValueType(Type *T) {
76 while (!T->isSingleValueType()) {
77 if (StructType *STy = dyn_cast<StructType>(T)) {
78 if (STy->getNumElements() == 1)
79 T = STy->getElementType(0);
80 else
81 break;
82 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
83 if (ATy->getNumElements() == 1)
84 T = ATy->getElementType();
85 else
86 break;
87 } else
88 break;
89 }
90
91 return T;
92}
Chris Lattner7a9e47a2010-01-05 07:32:13 +000093
Sanjay Patel368ac5d2016-02-21 17:29:33 +000094/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000095/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000096static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
97 SmallVector<Constant *, 32> BoolVec;
98 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
99 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
100 Constant *Elt = V->getElementAsConstant(I);
101 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
102 "Unexpected constant data vector element type");
103 bool Sign = V->getElementType()->isIntegerTy()
104 ? cast<ConstantInt>(Elt)->isNegative()
105 : cast<ConstantFP>(Elt)->isNegative();
106 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
107 }
108 return ConstantVector::get(BoolVec);
109}
110
Pete Cooper67cf9a72015-11-19 05:56:52 +0000111Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Justin Bogner99798402016-08-05 01:06:44 +0000112 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
113 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000114 unsigned MinAlign = std::min(DstAlign, SrcAlign);
115 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000116
Pete Cooper67cf9a72015-11-19 05:56:52 +0000117 if (CopyAlign < MinAlign) {
118 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000119 return MI;
120 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000121
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000122 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
123 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000124 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000125 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000126
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000127 // Source and destination pointer types are always "i8*" for intrinsic. See
128 // if the size is something we can handle with a single primitive load/store.
129 // A single load+store correctly handles overlapping memory in the memmove
130 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000131 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000132 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000133
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000134 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000135 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000136
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000137 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000138 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000139 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000140 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000141 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000142
Chris Lattner229907c2011-07-18 04:54:35 +0000143 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000144 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
145 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000146
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000147 // Memcpy forces the use of i8* for the source and destination. That means
148 // that if you're using memcpy to move one double around, you'll get a cast
149 // from double* to i8*. We'd much rather use a double load+store rather than
150 // an i64 load+store, here because this improves the odds that the source or
151 // dest address will be promotable. See if we can find a better type than the
152 // integer datatype.
Gabor Greif589a0b92010-06-24 12:58:35 +0000153 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Craig Topperf40110f2014-04-25 05:29:35 +0000154 MDNode *CopyMD = nullptr;
Gabor Greif589a0b92010-06-24 12:58:35 +0000155 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000156 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000157 ->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000158 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000159 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
160 // down through these levels if so.
Dan Gohmand0080c42012-09-13 18:19:06 +0000161 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach7815f562012-02-03 00:07:04 +0000162
Mon P Wangc576ee92010-04-04 03:10:48 +0000163 if (SrcETy->isSingleValueType()) {
164 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
165 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohman3f553c22012-09-13 21:51:01 +0000166
167 // If the memcpy has metadata describing the members, see if we can
168 // get the TBAA tag describing our copy.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000169 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000170 if (M->getNumOperands() == 3 && M->getOperand(0) &&
171 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
172 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000173 M->getOperand(1) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000174 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
175 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
176 Size &&
177 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
Dan Gohman3f553c22012-09-13 21:51:01 +0000178 CopyMD = cast<MDNode>(M->getOperand(2));
179 }
Mon P Wangc576ee92010-04-04 03:10:48 +0000180 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000181 }
182 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000183
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000184 // If the memcpy/memmove provides better alignment info than we can
185 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000186 SrcAlign = std::max(SrcAlign, CopyAlign);
187 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000188
Gabor Greif5f3e6562010-06-25 07:57:14 +0000189 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
190 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000191 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
192 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000193 if (CopyMD)
194 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
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) {
Justin Bogner99798402016-08-05 01:06:44 +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:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000402 LogicalShift = false;
403 ShiftLeft = false;
404 break;
405 case Intrinsic::x86_avx2_psrlv_d:
406 case Intrinsic::x86_avx2_psrlv_d_256:
407 case Intrinsic::x86_avx2_psrlv_q:
408 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000409 case Intrinsic::x86_avx512_psrlv_d_512:
410 case Intrinsic::x86_avx512_psrlv_q_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000411 LogicalShift = true;
412 ShiftLeft = false;
413 break;
414 case Intrinsic::x86_avx2_psllv_d:
415 case Intrinsic::x86_avx2_psllv_d_256:
416 case Intrinsic::x86_avx2_psllv_q:
417 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000418 case Intrinsic::x86_avx512_psllv_d_512:
419 case Intrinsic::x86_avx512_psllv_q_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000420 LogicalShift = true;
421 ShiftLeft = true;
422 break;
423 }
424 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
425
426 // Simplify if all shift amounts are constant/undef.
427 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
428 if (!CShift)
429 return nullptr;
430
431 auto Vec = II.getArgOperand(0);
432 auto VT = cast<VectorType>(II.getType());
433 auto SVT = VT->getVectorElementType();
434 int NumElts = VT->getNumElements();
435 int BitWidth = SVT->getIntegerBitWidth();
436
437 // Collect each element's shift amount.
438 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
439 bool AnyOutOfRange = false;
440 SmallVector<int, 8> ShiftAmts;
441 for (int I = 0; I < NumElts; ++I) {
442 auto *CElt = CShift->getAggregateElement(I);
443 if (CElt && isa<UndefValue>(CElt)) {
444 ShiftAmts.push_back(-1);
445 continue;
446 }
447
448 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
449 if (!COp)
450 return nullptr;
451
452 // Handle out of range shifts.
453 // If LogicalShift - set to BitWidth (special case).
454 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
455 APInt ShiftVal = COp->getValue();
456 if (ShiftVal.uge(BitWidth)) {
457 AnyOutOfRange = LogicalShift;
458 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
459 continue;
460 }
461
462 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
463 }
464
465 // If all elements out of range or UNDEF, return vector of zeros/undefs.
466 // ArithmeticShift should only hit this if they are all UNDEF.
467 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000468 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000469 SmallVector<Constant *, 8> ConstantVec;
470 for (int Idx : ShiftAmts) {
471 if (Idx < 0) {
472 ConstantVec.push_back(UndefValue::get(SVT));
473 } else {
474 assert(LogicalShift && "Logical shift expected");
475 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
476 }
477 }
478 return ConstantVector::get(ConstantVec);
479 }
480
481 // We can't handle only some out of range values with generic logical shifts.
482 if (AnyOutOfRange)
483 return nullptr;
484
485 // Build the shift amount constant vector.
486 SmallVector<Constant *, 8> ShiftVecAmts;
487 for (int Idx : ShiftAmts) {
488 if (Idx < 0)
489 ShiftVecAmts.push_back(UndefValue::get(SVT));
490 else
491 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
492 }
493 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
494
495 if (ShiftLeft)
496 return Builder.CreateShl(Vec, ShiftVec);
497
498 if (LogicalShift)
499 return Builder.CreateLShr(Vec, ShiftVec);
500
501 return Builder.CreateAShr(Vec, ShiftVec);
502}
503
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000504static Value *simplifyX86movmsk(const IntrinsicInst &II,
505 InstCombiner::BuilderTy &Builder) {
506 Value *Arg = II.getArgOperand(0);
507 Type *ResTy = II.getType();
508 Type *ArgTy = Arg->getType();
509
510 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
511 if (isa<UndefValue>(Arg))
512 return Constant::getNullValue(ResTy);
513
514 // We can't easily peek through x86_mmx types.
515 if (!ArgTy->isVectorTy())
516 return nullptr;
517
518 auto *C = dyn_cast<Constant>(Arg);
519 if (!C)
520 return nullptr;
521
522 // Extract signbits of the vector input and pack into integer result.
523 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
524 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
525 auto *COp = C->getAggregateElement(I);
526 if (!COp)
527 return nullptr;
528 if (isa<UndefValue>(COp))
529 continue;
530
531 auto *CInt = dyn_cast<ConstantInt>(COp);
532 auto *CFp = dyn_cast<ConstantFP>(COp);
533 if (!CInt && !CFp)
534 return nullptr;
535
536 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
537 Result.setBit(I);
538 }
539
540 return Constant::getIntegerValue(ResTy, Result);
541}
542
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000543static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000544 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000545 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
546 if (!CInt)
547 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000548
Sanjay Patel03c03f52016-01-28 00:03:16 +0000549 VectorType *VecTy = cast<VectorType>(II.getType());
550 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000551
Sanjay Patel03c03f52016-01-28 00:03:16 +0000552 // The immediate permute control byte looks like this:
553 // [3:0] - zero mask for each 32-bit lane
554 // [5:4] - select one 32-bit destination lane
555 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000556
Sanjay Patel03c03f52016-01-28 00:03:16 +0000557 uint8_t Imm = CInt->getZExtValue();
558 uint8_t ZMask = Imm & 0xf;
559 uint8_t DestLane = (Imm >> 4) & 0x3;
560 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000561
Sanjay Patel03c03f52016-01-28 00:03:16 +0000562 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000563
Sanjay Patel03c03f52016-01-28 00:03:16 +0000564 // If all zero mask bits are set, this was just a weird way to
565 // generate a zero vector.
566 if (ZMask == 0xf)
567 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000568
Sanjay Patel03c03f52016-01-28 00:03:16 +0000569 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000570 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000571
Sanjay Patel03c03f52016-01-28 00:03:16 +0000572 // We may replace the second operand with the zero vector.
573 Value *V1 = II.getArgOperand(1);
574
575 if (ZMask) {
576 // If the zero mask is being used with a single input or the zero mask
577 // overrides the destination lane, this is a shuffle with the zero vector.
578 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
579 (ZMask & (1 << DestLane))) {
580 V1 = ZeroVector;
581 // We may still move 32-bits of the first source vector from one lane
582 // to another.
583 ShuffleMask[DestLane] = SourceLane;
584 // The zero mask may override the previous insert operation.
585 for (unsigned i = 0; i < 4; ++i)
586 if ((ZMask >> i) & 0x1)
587 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000588 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000589 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
590 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000591 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000592 } else {
593 // Replace the selected destination lane with the selected source lane.
594 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000595 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000596
597 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000598}
599
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000600/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
601/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000602static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000603 ConstantInt *CILength, ConstantInt *CIIndex,
604 InstCombiner::BuilderTy &Builder) {
605 auto LowConstantHighUndef = [&](uint64_t Val) {
606 Type *IntTy64 = Type::getInt64Ty(II.getContext());
607 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
608 UndefValue::get(IntTy64)};
609 return ConstantVector::get(Args);
610 };
611
612 // See if we're dealing with constant values.
613 Constant *C0 = dyn_cast<Constant>(Op0);
614 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000615 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000616 : nullptr;
617
618 // Attempt to constant fold.
619 if (CILength && CIIndex) {
620 // From AMD documentation: "The bit index and field length are each six
621 // bits in length other bits of the field are ignored."
622 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
623 APInt APLength = CILength->getValue().zextOrTrunc(6);
624
625 unsigned Index = APIndex.getZExtValue();
626
627 // From AMD documentation: "a value of zero in the field length is
628 // defined as length of 64".
629 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
630
631 // From AMD documentation: "If the sum of the bit index + length field
632 // is greater than 64, the results are undefined".
633 unsigned End = Index + Length;
634
635 // Note that both field index and field length are 8-bit quantities.
636 // Since variables 'Index' and 'Length' are unsigned values
637 // obtained from zero-extending field index and field length
638 // respectively, their sum should never wrap around.
639 if (End > 64)
640 return UndefValue::get(II.getType());
641
642 // If we are inserting whole bytes, we can convert this to a shuffle.
643 // Lowering can recognize EXTRQI shuffle masks.
644 if ((Length % 8) == 0 && (Index % 8) == 0) {
645 // Convert bit indices to byte indices.
646 Length /= 8;
647 Index /= 8;
648
649 Type *IntTy8 = Type::getInt8Ty(II.getContext());
650 Type *IntTy32 = Type::getInt32Ty(II.getContext());
651 VectorType *ShufTy = VectorType::get(IntTy8, 16);
652
653 SmallVector<Constant *, 16> ShuffleMask;
654 for (int i = 0; i != (int)Length; ++i)
655 ShuffleMask.push_back(
656 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
657 for (int i = Length; i != 8; ++i)
658 ShuffleMask.push_back(
659 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
660 for (int i = 8; i != 16; ++i)
661 ShuffleMask.push_back(UndefValue::get(IntTy32));
662
663 Value *SV = Builder.CreateShuffleVector(
664 Builder.CreateBitCast(Op0, ShufTy),
665 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
666 return Builder.CreateBitCast(SV, II.getType());
667 }
668
669 // Constant Fold - shift Index'th bit to lowest position and mask off
670 // Length bits.
671 if (CI0) {
672 APInt Elt = CI0->getValue();
673 Elt = Elt.lshr(Index).zextOrTrunc(Length);
674 return LowConstantHighUndef(Elt.getZExtValue());
675 }
676
677 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
678 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
679 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000680 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000681 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
682 return Builder.CreateCall(F, Args);
683 }
684 }
685
686 // Constant Fold - extraction from zero is always {zero, undef}.
687 if (CI0 && CI0->equalsInt(0))
688 return LowConstantHighUndef(0);
689
690 return nullptr;
691}
692
693/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
694/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000695static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000696 APInt APLength, APInt APIndex,
697 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000698 // From AMD documentation: "The bit index and field length are each six bits
699 // in length other bits of the field are ignored."
700 APIndex = APIndex.zextOrTrunc(6);
701 APLength = APLength.zextOrTrunc(6);
702
703 // Attempt to constant fold.
704 unsigned Index = APIndex.getZExtValue();
705
706 // From AMD documentation: "a value of zero in the field length is
707 // defined as length of 64".
708 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
709
710 // From AMD documentation: "If the sum of the bit index + length field
711 // is greater than 64, the results are undefined".
712 unsigned End = Index + Length;
713
714 // Note that both field index and field length are 8-bit quantities.
715 // Since variables 'Index' and 'Length' are unsigned values
716 // obtained from zero-extending field index and field length
717 // respectively, their sum should never wrap around.
718 if (End > 64)
719 return UndefValue::get(II.getType());
720
721 // If we are inserting whole bytes, we can convert this to a shuffle.
722 // Lowering can recognize INSERTQI shuffle masks.
723 if ((Length % 8) == 0 && (Index % 8) == 0) {
724 // Convert bit indices to byte indices.
725 Length /= 8;
726 Index /= 8;
727
728 Type *IntTy8 = Type::getInt8Ty(II.getContext());
729 Type *IntTy32 = Type::getInt32Ty(II.getContext());
730 VectorType *ShufTy = VectorType::get(IntTy8, 16);
731
732 SmallVector<Constant *, 16> ShuffleMask;
733 for (int i = 0; i != (int)Index; ++i)
734 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
735 for (int i = 0; i != (int)Length; ++i)
736 ShuffleMask.push_back(
737 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
738 for (int i = Index + Length; i != 8; ++i)
739 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
740 for (int i = 8; i != 16; ++i)
741 ShuffleMask.push_back(UndefValue::get(IntTy32));
742
743 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
744 Builder.CreateBitCast(Op1, ShufTy),
745 ConstantVector::get(ShuffleMask));
746 return Builder.CreateBitCast(SV, II.getType());
747 }
748
749 // See if we're dealing with constant values.
750 Constant *C0 = dyn_cast<Constant>(Op0);
751 Constant *C1 = dyn_cast<Constant>(Op1);
752 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000753 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000754 : nullptr;
755 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000756 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000757 : nullptr;
758
759 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
760 if (CI00 && CI10) {
761 APInt V00 = CI00->getValue();
762 APInt V10 = CI10->getValue();
763 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
764 V00 = V00 & ~Mask;
765 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
766 APInt Val = V00 | V10;
767 Type *IntTy64 = Type::getInt64Ty(II.getContext());
768 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
769 UndefValue::get(IntTy64)};
770 return ConstantVector::get(Args);
771 }
772
773 // If we were an INSERTQ call, we'll save demanded elements if we convert to
774 // INSERTQI.
775 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
776 Type *IntTy8 = Type::getInt8Ty(II.getContext());
777 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
778 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
779
780 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000781 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000782 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
783 return Builder.CreateCall(F, Args);
784 }
785
786 return nullptr;
787}
788
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000789/// Attempt to convert pshufb* to shufflevector if the mask is constant.
790static Value *simplifyX86pshufb(const IntrinsicInst &II,
791 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000792 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
793 if (!V)
794 return nullptr;
795
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000796 auto *VecTy = cast<VectorType>(II.getType());
797 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
798 unsigned NumElts = VecTy->getNumElements();
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000799 assert((NumElts == 16 || NumElts == 32) &&
800 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000801
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000802 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000803 Constant *Indexes[32] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000804
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000805 // Each byte in the shuffle control mask forms an index to permute the
806 // corresponding byte in the destination operand.
807 for (unsigned I = 0; I < NumElts; ++I) {
808 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000809 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000810 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000811
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000812 if (isa<UndefValue>(COp)) {
813 Indexes[I] = UndefValue::get(MaskEltTy);
814 continue;
815 }
816
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000817 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
818
819 // If the most significant bit (bit[7]) of each byte of the shuffle
820 // control mask is set, then zero is written in the result byte.
821 // The zero vector is in the right-hand side of the resulting
822 // shufflevector.
823
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000824 // The value of each index for the high 128-bit lane is the least
825 // significant 4 bits of the respective shuffle control byte.
826 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
827 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000828 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000829
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000830 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000831 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000832 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000833 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
834}
835
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000836/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
837static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
838 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000839 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
840 if (!V)
841 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000842
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000843 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
844 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
845 assert(NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000846
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000847 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000848 Constant *Indexes[8] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +0000849
850 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000851 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +0000852 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000853 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +0000854 return nullptr;
855
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000856 if (isa<UndefValue>(COp)) {
857 Indexes[I] = UndefValue::get(MaskEltTy);
858 continue;
859 }
860
861 APInt Index = cast<ConstantInt>(COp)->getValue();
862 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +0000863
864 // The PD variants uses bit 1 to select per-lane element index, so
865 // shift down to convert to generic shuffle mask index.
866 if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
867 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000868 Index = Index.lshr(1);
869
870 // The _256 variants are a bit trickier since the mask bits always index
871 // into the corresponding 128 half. In order to convert to a generic
872 // shuffle, we have to make that explicit.
873 if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
874 II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) &&
875 ((NumElts / 2) <= I)) {
876 Index += APInt(32, NumElts / 2);
877 }
878
879 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000880 }
881
Simon Pilgrimeeacc402016-05-01 20:22:42 +0000882 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +0000883 auto V1 = II.getArgOperand(0);
884 auto V2 = UndefValue::get(V1->getType());
885 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
886}
887
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000888/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
889static Value *simplifyX86vpermv(const IntrinsicInst &II,
890 InstCombiner::BuilderTy &Builder) {
891 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
892 if (!V)
893 return nullptr;
894
Simon Pilgrimca140b12016-05-01 20:43:02 +0000895 auto *VecTy = cast<VectorType>(II.getType());
896 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000897 unsigned Size = VecTy->getNumElements();
898 assert(Size == 8 && "Unexpected shuffle mask size");
899
Simon Pilgrimca140b12016-05-01 20:43:02 +0000900 // Construct a shuffle mask from constant integers or UNDEFs.
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000901 Constant *Indexes[8] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000902
903 for (unsigned I = 0; I < Size; ++I) {
904 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +0000905 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000906 return nullptr;
907
Simon Pilgrimca140b12016-05-01 20:43:02 +0000908 if (isa<UndefValue>(COp)) {
909 Indexes[I] = UndefValue::get(MaskEltTy);
910 continue;
911 }
912
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000913 APInt Index = cast<ConstantInt>(COp)->getValue();
Simon Pilgrimca140b12016-05-01 20:43:02 +0000914 Index = Index.zextOrTrunc(32).getLoBits(3);
915 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000916 }
917
Simon Pilgrimca140b12016-05-01 20:43:02 +0000918 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +0000919 auto V1 = II.getArgOperand(0);
920 auto V2 = UndefValue::get(VecTy);
921 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
922}
923
Sanjay Patelccf5f242015-03-20 21:47:56 +0000924/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
925/// source vectors, unless a zero bit is set. If a zero bit is set,
926/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000927static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +0000928 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000929 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
930 if (!CInt)
931 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000932
Sanjay Patel03c03f52016-01-28 00:03:16 +0000933 VectorType *VecTy = cast<VectorType>(II.getType());
934 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000935
Sanjay Patel03c03f52016-01-28 00:03:16 +0000936 // The immediate permute control byte looks like this:
937 // [1:0] - select 128 bits from sources for low half of destination
938 // [2] - ignore
939 // [3] - zero low half of destination
940 // [5:4] - select 128 bits from sources for high half of destination
941 // [6] - ignore
942 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000943
Sanjay Patel03c03f52016-01-28 00:03:16 +0000944 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000945
Sanjay Patel03c03f52016-01-28 00:03:16 +0000946 bool LowHalfZero = Imm & 0x08;
947 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000948
Sanjay Patel03c03f52016-01-28 00:03:16 +0000949 // If both zero mask bits are set, this was just a weird way to
950 // generate a zero vector.
951 if (LowHalfZero && HighHalfZero)
952 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000953
Sanjay Patel03c03f52016-01-28 00:03:16 +0000954 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
955 unsigned NumElts = VecTy->getNumElements();
956 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +0000957 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000958
Sanjay Patel03c03f52016-01-28 00:03:16 +0000959 // The high bit of the selection field chooses the 1st or 2nd operand.
960 bool LowInputSelect = Imm & 0x02;
961 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000962
Sanjay Patel03c03f52016-01-28 00:03:16 +0000963 // The low bit of the selection field chooses the low or high half
964 // of the selected operand.
965 bool LowHalfSelect = Imm & 0x01;
966 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000967
Sanjay Patel03c03f52016-01-28 00:03:16 +0000968 // Determine which operand(s) are actually in use for this instruction.
969 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
970 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000971
Sanjay Patel03c03f52016-01-28 00:03:16 +0000972 // If needed, replace operands based on zero mask.
973 V0 = LowHalfZero ? ZeroVector : V0;
974 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +0000975
Sanjay Patel03c03f52016-01-28 00:03:16 +0000976 // Permute low half of result.
977 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
978 for (unsigned i = 0; i < HalfSize; ++i)
979 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +0000980
Sanjay Patel03c03f52016-01-28 00:03:16 +0000981 // Permute high half of result.
982 StartIndex = HighHalfSelect ? HalfSize : 0;
983 StartIndex += NumElts;
984 for (unsigned i = 0; i < HalfSize; ++i)
985 ShuffleMask[i + HalfSize] = StartIndex + i;
986
987 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +0000988}
989
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000990/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000991static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +0000992 InstCombiner::BuilderTy &Builder,
993 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +0000994 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
995 uint64_t Imm = CInt->getZExtValue() & 0x7;
996 VectorType *VecTy = cast<VectorType>(II.getType());
997 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
998
999 switch (Imm) {
1000 case 0x0:
1001 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1002 break;
1003 case 0x1:
1004 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1005 break;
1006 case 0x2:
1007 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1008 break;
1009 case 0x3:
1010 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1011 break;
1012 case 0x4:
1013 Pred = ICmpInst::ICMP_EQ; break;
1014 case 0x5:
1015 Pred = ICmpInst::ICMP_NE; break;
1016 case 0x6:
1017 return ConstantInt::getSigned(VecTy, 0); // FALSE
1018 case 0x7:
1019 return ConstantInt::getSigned(VecTy, -1); // TRUE
1020 }
1021
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001022 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1023 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001024 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1025 }
1026 return nullptr;
1027}
1028
Sanjay Patel0069f562016-01-31 16:35:23 +00001029static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1030 Value *Arg0 = II.getArgOperand(0);
1031 Value *Arg1 = II.getArgOperand(1);
1032
1033 // fmin(x, x) -> x
1034 if (Arg0 == Arg1)
1035 return Arg0;
1036
1037 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1038
1039 // fmin(x, nan) -> x
1040 if (C1 && C1->isNaN())
1041 return Arg0;
1042
1043 // This is the value because if undef were NaN, we would return the other
1044 // value and cannot return a NaN unless both operands are.
1045 //
1046 // fmin(undef, x) -> x
1047 if (isa<UndefValue>(Arg0))
1048 return Arg1;
1049
1050 // fmin(x, undef) -> x
1051 if (isa<UndefValue>(Arg1))
1052 return Arg0;
1053
1054 Value *X = nullptr;
1055 Value *Y = nullptr;
1056 if (II.getIntrinsicID() == Intrinsic::minnum) {
1057 // fmin(x, fmin(x, y)) -> fmin(x, y)
1058 // fmin(y, fmin(x, y)) -> fmin(x, y)
1059 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1060 if (Arg0 == X || Arg0 == Y)
1061 return Arg1;
1062 }
1063
1064 // fmin(fmin(x, y), x) -> fmin(x, y)
1065 // fmin(fmin(x, y), y) -> fmin(x, y)
1066 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1067 if (Arg1 == X || Arg1 == Y)
1068 return Arg0;
1069 }
1070
1071 // TODO: fmin(nnan x, inf) -> x
1072 // TODO: fmin(nnan ninf x, flt_max) -> x
1073 if (C1 && C1->isInfinity()) {
1074 // fmin(x, -inf) -> -inf
1075 if (C1->isNegative())
1076 return Arg1;
1077 }
1078 } else {
1079 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1080 // fmax(x, fmax(x, y)) -> fmax(x, y)
1081 // fmax(y, fmax(x, y)) -> fmax(x, y)
1082 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1083 if (Arg0 == X || Arg0 == Y)
1084 return Arg1;
1085 }
1086
1087 // fmax(fmax(x, y), x) -> fmax(x, y)
1088 // fmax(fmax(x, y), y) -> fmax(x, y)
1089 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1090 if (Arg1 == X || Arg1 == Y)
1091 return Arg0;
1092 }
1093
1094 // TODO: fmax(nnan x, -inf) -> x
1095 // TODO: fmax(nnan ninf x, -flt_max) -> x
1096 if (C1 && C1->isInfinity()) {
1097 // fmax(x, inf) -> inf
1098 if (!C1->isNegative())
1099 return Arg1;
1100 }
1101 }
1102 return nullptr;
1103}
1104
David Majnemer666aa942016-07-14 06:58:42 +00001105static bool maskIsAllOneOrUndef(Value *Mask) {
1106 auto *ConstMask = dyn_cast<Constant>(Mask);
1107 if (!ConstMask)
1108 return false;
1109 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1110 return true;
1111 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1112 ++I) {
1113 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1114 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1115 continue;
1116 return false;
1117 }
1118 return true;
1119}
1120
Sanjay Patelb695c552016-02-01 17:00:10 +00001121static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1122 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001123 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1124 // argument.
1125 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001126 Value *LoadPtr = II.getArgOperand(0);
1127 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1128 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1129 }
1130
1131 return nullptr;
1132}
1133
Sanjay Patel04f792b2016-02-01 19:39:52 +00001134static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1135 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1136 if (!ConstMask)
1137 return nullptr;
1138
1139 // If the mask is all zeros, this instruction does nothing.
1140 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001141 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001142
1143 // If the mask is all ones, this is a plain vector store of the 1st argument.
1144 if (ConstMask->isAllOnesValue()) {
1145 Value *StorePtr = II.getArgOperand(1);
1146 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1147 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1148 }
1149
1150 return nullptr;
1151}
1152
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001153static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1154 // If the mask is all zeros, return the "passthru" argument of the gather.
1155 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1156 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001157 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001158
1159 return nullptr;
1160}
1161
1162static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1163 // If the mask is all zeros, a scatter does nothing.
1164 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1165 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001166 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001167
1168 return nullptr;
1169}
1170
Amaury Sechet763c59d2016-08-18 20:43:50 +00001171static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1172 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1173 II.getIntrinsicID() == Intrinsic::ctlz) &&
1174 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001175 Value *Op0 = II.getArgOperand(0);
1176 // FIXME: Try to simplify vectors of integers.
1177 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1178 if (!IT)
1179 return nullptr;
1180
1181 unsigned BitWidth = IT->getBitWidth();
1182 APInt KnownZero(BitWidth, 0);
1183 APInt KnownOne(BitWidth, 0);
1184 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1185
1186 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1187 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1188 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1189 : KnownOne.countLeadingZeros();
1190 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1191 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1192
1193 // If all bits above (ctlz) or below (cttz) the first known one are known
1194 // zero, this value is constant.
1195 // FIXME: This should be in InstSimplify because we're replacing an
1196 // instruction with a constant.
Amaury Sechet763c59d2016-08-18 20:43:50 +00001197 if ((Mask & KnownZero) == Mask) {
1198 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1199 return IC.replaceInstUsesWith(II, C);
1200 }
1201
1202 // If the input to cttz/ctlz is known to be non-zero,
1203 // then change the 'ZeroIsUndef' parameter to 'true'
1204 // because we know the zero behavior can't affect the result.
1205 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1206 if (!match(II.getArgOperand(1), m_One())) {
1207 II.setOperand(1, IC.Builder->getTrue());
1208 return &II;
1209 }
1210 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001211
1212 return nullptr;
1213}
1214
Sanjay Patel1ace9932016-02-26 21:04:14 +00001215// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1216// XMM register mask efficiently, we could transform all x86 masked intrinsics
1217// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001218static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1219 Value *Ptr = II.getOperand(0);
1220 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001221 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001222
1223 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001224 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001225 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001226 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001227
1228 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1229 if (!ConstMask)
1230 return nullptr;
1231
1232 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1233 // to allow target-independent optimizations.
1234
1235 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1236 // the LLVM intrinsic definition for the pointer argument.
1237 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1238 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1239 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1240
1241 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1242 // on each element's most significant bit (the sign bit).
1243 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1244
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001245 // The pass-through vector for an x86 masked load is a zero vector.
1246 CallInst *NewMaskedLoad =
1247 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001248 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1249}
1250
1251// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1252// XMM register mask efficiently, we could transform all x86 masked intrinsics
1253// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001254static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1255 Value *Ptr = II.getOperand(0);
1256 Value *Mask = II.getOperand(1);
1257 Value *Vec = II.getOperand(2);
1258
1259 // Special case a zero mask since that's not a ConstantDataVector:
1260 // this masked store instruction does nothing.
1261 if (isa<ConstantAggregateZero>(Mask)) {
1262 IC.eraseInstFromFunction(II);
1263 return true;
1264 }
1265
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001266 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1267 // anything else at this level.
1268 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1269 return false;
1270
Sanjay Patel1ace9932016-02-26 21:04:14 +00001271 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1272 if (!ConstMask)
1273 return false;
1274
1275 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1276 // to allow target-independent optimizations.
1277
1278 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1279 // the LLVM intrinsic definition for the pointer argument.
1280 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1281 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001282 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1283
1284 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1285 // on each element's most significant bit (the sign bit).
1286 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1287
1288 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1289
1290 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1291 IC.eraseInstFromFunction(II);
1292 return true;
1293}
1294
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001295// Returns true iff the 2 intrinsics have the same operands, limiting the
1296// comparison to the first NumOperands.
1297static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1298 unsigned NumOperands) {
1299 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1300 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1301 for (unsigned i = 0; i < NumOperands; i++)
1302 if (I.getArgOperand(i) != E.getArgOperand(i))
1303 return false;
1304 return true;
1305}
1306
1307// Remove trivially empty start/end intrinsic ranges, i.e. a start
1308// immediately followed by an end (ignoring debuginfo or other
1309// start/end intrinsics in between). As this handles only the most trivial
1310// cases, tracking the nesting level is not needed:
1311//
1312// call @llvm.foo.start(i1 0) ; &I
1313// call @llvm.foo.start(i1 0)
1314// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1315// call @llvm.foo.end(i1 0)
1316static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1317 unsigned EndID, InstCombiner &IC) {
1318 assert(I.getIntrinsicID() == StartID &&
1319 "Start intrinsic does not have expected ID");
1320 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1321 for (++BI; BI != BE; ++BI) {
1322 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1323 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1324 continue;
1325 if (E->getIntrinsicID() == EndID &&
1326 haveSameOperands(I, *E, E->getNumArgOperands())) {
1327 IC.eraseInstFromFunction(*E);
1328 IC.eraseInstFromFunction(I);
1329 return true;
1330 }
1331 }
1332 break;
1333 }
1334
1335 return false;
1336}
1337
1338Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1339 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1340 return nullptr;
1341}
1342
1343Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1344 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1345 return nullptr;
1346}
1347
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001348/// CallInst simplification. This mostly only handles folding of intrinsic
1349/// instructions. For normal calls, it allows visitCallSite to do the heavy
1350/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001351Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001352 auto Args = CI.arg_operands();
1353 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Justin Bogner99798402016-08-05 01:06:44 +00001354 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001355 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001356
Justin Bogner99798402016-08-05 01:06:44 +00001357 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001358 return visitFree(CI);
1359
1360 // If the caller function is nounwind, mark the call as nounwind, even if the
1361 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001362 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001363 CI.setDoesNotThrow();
1364 return &CI;
1365 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001366
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001367 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1368 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001369
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001370 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1371 // visitCallSite.
1372 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1373 bool Changed = false;
1374
1375 // memmove/cpy/set of zero bytes is a noop.
1376 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001377 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001378 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001379
1380 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1381 if (CI->getZExtValue() == 1) {
1382 // Replace the instruction with just byte operations. We would
1383 // transform other cases to loads/stores, but we don't know if
1384 // alignment is sufficient.
1385 }
1386 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001387
Chris Lattnerc663a672010-10-01 05:51:02 +00001388 // No other transformations apply to volatile transfers.
1389 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001390 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001391
1392 // If we have a memmove and the source operation is a constant global,
1393 // then the source and dest pointers can't alias, so we can change this
1394 // into a call to memcpy.
1395 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1396 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1397 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001398 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001399 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001400 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1401 CI.getArgOperand(1)->getType(),
1402 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001403 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001404 Changed = true;
1405 }
1406 }
1407
1408 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1409 // memmove(x,x,size) -> noop.
1410 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001411 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001412 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001413
Eric Christopher7258dcd2010-04-16 23:37:20 +00001414 // If we can determine a pointer alignment that is bigger than currently
1415 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001416 if (isa<MemTransferInst>(MI)) {
1417 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001418 return I;
1419 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1420 if (Instruction *I = SimplifyMemSet(MSI))
1421 return I;
1422 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001423
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001424 if (Changed) return II;
1425 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001426
Sanjay Patel1c600c62016-01-20 16:41:43 +00001427 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1428 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001429 APInt UndefElts(Width, 0);
1430 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1431 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1432 };
Simon Pilgrim424da162016-04-24 18:12:42 +00001433 auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1434 unsigned DemandedWidth) {
1435 APInt UndefElts(Width, 0);
1436 APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1437 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1438 };
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001439
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001440 switch (II->getIntrinsicID()) {
1441 default: break;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001442 case Intrinsic::objectsize: {
Nuno Lopes55fff832012-06-21 15:45:28 +00001443 uint64_t Size;
Justin Bogner99798402016-08-05 01:06:44 +00001444 if (getObjectSize(II->getArgOperand(0), Size, DL, &TLI)) {
George Burgess IV278199f2016-04-12 01:05:35 +00001445 APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1446 // Equality check to be sure that `Size` can fit in a value of type
1447 // `II->getType()`
1448 if (APSize == Size)
1449 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1450 }
Craig Topperf40110f2014-04-25 05:29:35 +00001451 return nullptr;
Eric Christopher7b7028f2010-02-09 21:24:27 +00001452 }
Michael Ilseman536cc322012-12-13 03:13:36 +00001453 case Intrinsic::bswap: {
1454 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001455 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001456
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001457 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001458 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001459 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001460
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001461 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001462 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1463 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1464 IIOperand->getType()->getPrimitiveSizeInBits();
1465 Value *CV = ConstantInt::get(X->getType(), C);
1466 Value *V = Builder->CreateLShr(X, CV);
1467 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001468 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001469 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001470 }
1471
James Molloy2d09c002015-11-12 12:39:41 +00001472 case Intrinsic::bitreverse: {
1473 Value *IIOperand = II->getArgOperand(0);
1474 Value *X = nullptr;
1475
1476 // bitreverse(bitreverse(x)) -> x
1477 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001478 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001479 break;
1480 }
1481
Sanjay Patelb695c552016-02-01 17:00:10 +00001482 case Intrinsic::masked_load:
1483 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001484 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001485 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001486 case Intrinsic::masked_store:
1487 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001488 case Intrinsic::masked_gather:
1489 return simplifyMaskedGather(*II, *this);
1490 case Intrinsic::masked_scatter:
1491 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001492
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001493 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001494 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001495 // powi(x, 0) -> 1.0
1496 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001497 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001498 // powi(x, 1) -> x
1499 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001500 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001501 // powi(x, -1) -> 1/x
1502 if (Power->isAllOnesValue())
1503 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001504 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001505 }
1506 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001507
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001508 case Intrinsic::cttz:
1509 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001510 if (auto *I = foldCttzCtlz(*II, *this))
1511 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001512 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001513
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001514 case Intrinsic::uadd_with_overflow:
1515 case Intrinsic::sadd_with_overflow:
1516 case Intrinsic::umul_with_overflow:
1517 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001518 if (isa<Constant>(II->getArgOperand(0)) &&
1519 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001520 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001521 Value *LHS = II->getArgOperand(0);
1522 II->setArgOperand(0, II->getArgOperand(1));
1523 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001524 return II;
1525 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001526 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001527
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001528 case Intrinsic::usub_with_overflow:
1529 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001530 OverflowCheckFlavor OCF =
1531 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1532 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001533
Sanjoy Dasb0984472015-04-08 04:27:22 +00001534 Value *OperationResult = nullptr;
1535 Constant *OverflowResult = nullptr;
1536 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1537 *II, OperationResult, OverflowResult))
1538 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00001539
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001540 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00001541 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001542
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001543 case Intrinsic::minnum:
1544 case Intrinsic::maxnum: {
1545 Value *Arg0 = II->getArgOperand(0);
1546 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00001547 // Canonicalize constants to the RHS.
1548 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001549 II->setArgOperand(0, Arg1);
1550 II->setArgOperand(1, Arg0);
1551 return II;
1552 }
Sanjay Patel0069f562016-01-31 16:35:23 +00001553 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00001554 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00001555 break;
1556 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001557 case Intrinsic::ppc_altivec_lvx:
1558 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00001559 // Turn PPC lvx -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001560 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1561 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00001562 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001563 PointerType::getUnqual(II->getType()));
1564 return new LoadInst(Ptr);
1565 }
1566 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001567 case Intrinsic::ppc_vsx_lxvw4x:
1568 case Intrinsic::ppc_vsx_lxvd2x: {
1569 // Turn PPC VSX loads into normal loads.
1570 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1571 PointerType::getUnqual(II->getType()));
1572 return new LoadInst(Ptr, Twine(""), false, 1);
1573 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001574 case Intrinsic::ppc_altivec_stvx:
1575 case Intrinsic::ppc_altivec_stvxl:
1576 // Turn stvx -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001577 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1578 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00001579 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00001580 PointerType::getUnqual(II->getArgOperand(0)->getType());
1581 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1582 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001583 }
1584 break;
Bill Schmidt72954782014-11-12 04:19:40 +00001585 case Intrinsic::ppc_vsx_stxvw4x:
1586 case Intrinsic::ppc_vsx_stxvd2x: {
1587 // Turn PPC VSX stores into normal stores.
1588 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1589 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1590 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1591 }
Hal Finkel221f4672015-02-26 18:56:03 +00001592 case Intrinsic::ppc_qpx_qvlfs:
1593 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001594 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1595 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001596 Type *VTy = VectorType::get(Builder->getFloatTy(),
1597 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00001598 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00001599 PointerType::getUnqual(VTy));
1600 Value *Load = Builder->CreateLoad(Ptr);
1601 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00001602 }
1603 break;
1604 case Intrinsic::ppc_qpx_qvlfd:
1605 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001606 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
1607 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001608 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1609 PointerType::getUnqual(II->getType()));
1610 return new LoadInst(Ptr);
1611 }
1612 break;
1613 case Intrinsic::ppc_qpx_qvstfs:
1614 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001615 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1616 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00001617 Type *VTy = VectorType::get(Builder->getFloatTy(),
1618 II->getArgOperand(0)->getType()->getVectorNumElements());
1619 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1620 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00001621 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00001622 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00001623 }
1624 break;
1625 case Intrinsic::ppc_qpx_qvstfd:
1626 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Justin Bogner99798402016-08-05 01:06:44 +00001627 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
1628 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00001629 Type *OpPtrTy =
1630 PointerType::getUnqual(II->getArgOperand(0)->getType());
1631 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1632 return new StoreInst(II->getArgOperand(0), Ptr);
1633 }
1634 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001635
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001636 case Intrinsic::x86_vcvtph2ps_128:
1637 case Intrinsic::x86_vcvtph2ps_256: {
1638 auto Arg = II->getArgOperand(0);
1639 auto ArgType = cast<VectorType>(Arg->getType());
1640 auto RetType = cast<VectorType>(II->getType());
1641 unsigned ArgWidth = ArgType->getNumElements();
1642 unsigned RetWidth = RetType->getNumElements();
1643 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1644 assert(ArgType->isIntOrIntVectorTy() &&
1645 ArgType->getScalarSizeInBits() == 16 &&
1646 "CVTPH2PS input type should be 16-bit integer vector");
1647 assert(RetType->getScalarType()->isFloatTy() &&
1648 "CVTPH2PS output type should be 32-bit float vector");
1649
1650 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001651 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00001652 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001653
Simon Pilgrim48ffca02015-09-12 14:00:17 +00001654 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001655 auto VectorHalfAsShorts = Arg;
1656 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00001657 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001658 for (unsigned i = 0; i != RetWidth; ++i)
1659 SubVecMask.push_back((int)i);
1660 VectorHalfAsShorts = Builder->CreateShuffleVector(
1661 Arg, UndefValue::get(ArgType), SubVecMask);
1662 }
1663
1664 auto VectorHalfType =
1665 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1666 auto VectorHalfs =
1667 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1668 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00001669 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001670 }
1671
1672 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001673 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00001674 II->setArgOperand(0, V);
1675 return II;
1676 }
1677 break;
1678 }
1679
Chandler Carruthcf414cf2011-01-10 07:19:37 +00001680 case Intrinsic::x86_sse_cvtss2si:
1681 case Intrinsic::x86_sse_cvtss2si64:
1682 case Intrinsic::x86_sse_cvttss2si:
1683 case Intrinsic::x86_sse_cvttss2si64:
1684 case Intrinsic::x86_sse2_cvtsd2si:
1685 case Intrinsic::x86_sse2_cvtsd2si64:
1686 case Intrinsic::x86_sse2_cvttsd2si:
1687 case Intrinsic::x86_sse2_cvttsd2si64: {
1688 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001689 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001690 Value *Arg = II->getArgOperand(0);
1691 unsigned VWidth = Arg->getType()->getVectorNumElements();
1692 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00001693 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001694 return II;
1695 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00001696 break;
1697 }
1698
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00001699 case Intrinsic::x86_mmx_pmovmskb:
1700 case Intrinsic::x86_sse_movmsk_ps:
1701 case Intrinsic::x86_sse2_movmsk_pd:
1702 case Intrinsic::x86_sse2_pmovmskb_128:
1703 case Intrinsic::x86_avx_movmsk_pd_256:
1704 case Intrinsic::x86_avx_movmsk_ps_256:
1705 case Intrinsic::x86_avx2_pmovmskb: {
1706 if (Value *V = simplifyX86movmsk(*II, *Builder))
1707 return replaceInstUsesWith(*II, V);
1708 break;
1709 }
1710
Simon Pilgrim471efd22016-02-20 23:17:35 +00001711 case Intrinsic::x86_sse_comieq_ss:
1712 case Intrinsic::x86_sse_comige_ss:
1713 case Intrinsic::x86_sse_comigt_ss:
1714 case Intrinsic::x86_sse_comile_ss:
1715 case Intrinsic::x86_sse_comilt_ss:
1716 case Intrinsic::x86_sse_comineq_ss:
1717 case Intrinsic::x86_sse_ucomieq_ss:
1718 case Intrinsic::x86_sse_ucomige_ss:
1719 case Intrinsic::x86_sse_ucomigt_ss:
1720 case Intrinsic::x86_sse_ucomile_ss:
1721 case Intrinsic::x86_sse_ucomilt_ss:
1722 case Intrinsic::x86_sse_ucomineq_ss:
1723 case Intrinsic::x86_sse2_comieq_sd:
1724 case Intrinsic::x86_sse2_comige_sd:
1725 case Intrinsic::x86_sse2_comigt_sd:
1726 case Intrinsic::x86_sse2_comile_sd:
1727 case Intrinsic::x86_sse2_comilt_sd:
1728 case Intrinsic::x86_sse2_comineq_sd:
1729 case Intrinsic::x86_sse2_ucomieq_sd:
1730 case Intrinsic::x86_sse2_ucomige_sd:
1731 case Intrinsic::x86_sse2_ucomigt_sd:
1732 case Intrinsic::x86_sse2_ucomile_sd:
1733 case Intrinsic::x86_sse2_ucomilt_sd:
1734 case Intrinsic::x86_sse2_ucomineq_sd: {
1735 // These intrinsics only demand the 0th element of their input vectors. If
1736 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001737 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001738 Value *Arg0 = II->getArgOperand(0);
1739 Value *Arg1 = II->getArgOperand(1);
1740 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1741 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1742 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001743 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001744 }
1745 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1746 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001747 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001748 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001749 if (MadeChange)
1750 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00001751 break;
1752 }
1753
Simon Pilgrim424da162016-04-24 18:12:42 +00001754 case Intrinsic::x86_sse_add_ss:
1755 case Intrinsic::x86_sse_sub_ss:
1756 case Intrinsic::x86_sse_mul_ss:
1757 case Intrinsic::x86_sse_div_ss:
1758 case Intrinsic::x86_sse_min_ss:
1759 case Intrinsic::x86_sse_max_ss:
1760 case Intrinsic::x86_sse_cmp_ss:
1761 case Intrinsic::x86_sse2_add_sd:
1762 case Intrinsic::x86_sse2_sub_sd:
1763 case Intrinsic::x86_sse2_mul_sd:
1764 case Intrinsic::x86_sse2_div_sd:
1765 case Intrinsic::x86_sse2_min_sd:
1766 case Intrinsic::x86_sse2_max_sd:
1767 case Intrinsic::x86_sse2_cmp_sd: {
1768 // These intrinsics only demand the lowest element of the second input
1769 // vector.
1770 Value *Arg1 = II->getArgOperand(1);
1771 unsigned VWidth = Arg1->getType()->getVectorNumElements();
1772 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1773 II->setArgOperand(1, V);
1774 return II;
1775 }
1776 break;
1777 }
1778
1779 case Intrinsic::x86_sse41_round_ss:
1780 case Intrinsic::x86_sse41_round_sd: {
1781 // These intrinsics demand the upper elements of the first input vector and
1782 // the lowest element of the second input vector.
1783 bool MadeChange = false;
1784 Value *Arg0 = II->getArgOperand(0);
1785 Value *Arg1 = II->getArgOperand(1);
1786 unsigned VWidth = Arg0->getType()->getVectorNumElements();
1787 if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1788 II->setArgOperand(0, V);
1789 MadeChange = true;
1790 }
1791 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1792 II->setArgOperand(1, V);
1793 MadeChange = true;
1794 }
1795 if (MadeChange)
1796 return II;
1797 break;
1798 }
1799
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001800 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001801 // Constant fold lshr( <A x Bi>, Ci ).
1802 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001803 case Intrinsic::x86_sse2_psrai_d:
1804 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00001805 case Intrinsic::x86_avx2_psrai_d:
1806 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001807 case Intrinsic::x86_avx512_psrai_q_128:
1808 case Intrinsic::x86_avx512_psrai_q_256:
1809 case Intrinsic::x86_avx512_psrai_d_512:
1810 case Intrinsic::x86_avx512_psrai_q_512:
1811 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001812 case Intrinsic::x86_sse2_psrli_d:
1813 case Intrinsic::x86_sse2_psrli_q:
1814 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001815 case Intrinsic::x86_avx2_psrli_d:
1816 case Intrinsic::x86_avx2_psrli_q:
1817 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001818 case Intrinsic::x86_avx512_psrli_d_512:
1819 case Intrinsic::x86_avx512_psrli_q_512:
1820 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00001821 case Intrinsic::x86_sse2_pslli_d:
1822 case Intrinsic::x86_sse2_pslli_q:
1823 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00001824 case Intrinsic::x86_avx2_pslli_d:
1825 case Intrinsic::x86_avx2_pslli_q:
1826 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001827 case Intrinsic::x86_avx512_pslli_d_512:
1828 case Intrinsic::x86_avx512_pslli_q_512:
1829 case Intrinsic::x86_avx512_pslli_w_512:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001830 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001831 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00001832 break;
1833
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001834 case Intrinsic::x86_sse2_psra_d:
1835 case Intrinsic::x86_sse2_psra_w:
1836 case Intrinsic::x86_avx2_psra_d:
1837 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001838 case Intrinsic::x86_avx512_psra_q_128:
1839 case Intrinsic::x86_avx512_psra_q_256:
1840 case Intrinsic::x86_avx512_psra_d_512:
1841 case Intrinsic::x86_avx512_psra_q_512:
1842 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001843 case Intrinsic::x86_sse2_psrl_d:
1844 case Intrinsic::x86_sse2_psrl_q:
1845 case Intrinsic::x86_sse2_psrl_w:
1846 case Intrinsic::x86_avx2_psrl_d:
1847 case Intrinsic::x86_avx2_psrl_q:
1848 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00001849 case Intrinsic::x86_avx512_psrl_d_512:
1850 case Intrinsic::x86_avx512_psrl_q_512:
1851 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001852 case Intrinsic::x86_sse2_psll_d:
1853 case Intrinsic::x86_sse2_psll_q:
1854 case Intrinsic::x86_sse2_psll_w:
1855 case Intrinsic::x86_avx2_psll_d:
1856 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00001857 case Intrinsic::x86_avx2_psll_w:
1858 case Intrinsic::x86_avx512_psll_d_512:
1859 case Intrinsic::x86_avx512_psll_q_512:
1860 case Intrinsic::x86_avx512_psll_w_512: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001861 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001862 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001863
1864 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1865 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00001866 Value *Arg1 = II->getArgOperand(1);
1867 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001868 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00001869 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001870
Simon Pilgrim996725e2015-09-19 11:41:53 +00001871 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00001872 II->setArgOperand(1, V);
1873 return II;
1874 }
1875 break;
1876 }
1877
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001878 case Intrinsic::x86_avx2_psllv_d:
1879 case Intrinsic::x86_avx2_psllv_d_256:
1880 case Intrinsic::x86_avx2_psllv_q:
1881 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00001882 case Intrinsic::x86_avx512_psllv_d_512:
1883 case Intrinsic::x86_avx512_psllv_q_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001884 case Intrinsic::x86_avx2_psrav_d:
1885 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00001886 case Intrinsic::x86_avx512_psrav_q_128:
1887 case Intrinsic::x86_avx512_psrav_q_256:
1888 case Intrinsic::x86_avx512_psrav_d_512:
1889 case Intrinsic::x86_avx512_psrav_q_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001890 case Intrinsic::x86_avx2_psrlv_d:
1891 case Intrinsic::x86_avx2_psrlv_d_256:
1892 case Intrinsic::x86_avx2_psrlv_q:
1893 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00001894 case Intrinsic::x86_avx512_psrlv_d_512:
1895 case Intrinsic::x86_avx512_psrlv_q_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00001896 if (Value *V = simplifyX86varShift(*II, *Builder))
1897 return replaceInstUsesWith(*II, V);
1898 break;
1899
Sanjay Patelc86867c2015-04-16 17:52:13 +00001900 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001901 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001902 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00001903 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001904
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001905 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001906 Value *Op0 = II->getArgOperand(0);
1907 Value *Op1 = II->getArgOperand(1);
1908 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1909 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001910 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1911 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1912 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001913
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001914 // See if we're dealing with constant values.
1915 Constant *C1 = dyn_cast<Constant>(Op1);
1916 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00001917 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001918 : nullptr;
1919 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00001920 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001921 : nullptr;
1922
1923 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001924 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001925 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001926
1927 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1928 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001929 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001930 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1931 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001932 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001933 }
1934 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1935 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001936 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001937 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00001938 if (MadeChange)
1939 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001940 break;
1941 }
1942
1943 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001944 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1945 // bits of the lower 64-bits. The upper 64-bits are undefined.
1946 Value *Op0 = II->getArgOperand(0);
1947 unsigned VWidth = Op0->getType()->getVectorNumElements();
1948 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1949 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001950
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001951 // See if we're dealing with constant values.
1952 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1953 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1954
1955 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001956 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001957 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001958
1959 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1960 // operand.
1961 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001962 II->setArgOperand(0, V);
1963 return II;
1964 }
1965 break;
1966 }
1967
1968 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001969 Value *Op0 = II->getArgOperand(0);
1970 Value *Op1 = II->getArgOperand(1);
1971 unsigned VWidth = Op0->getType()->getVectorNumElements();
1972 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1973 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1974 Op1->getType()->getVectorNumElements() == 2 &&
1975 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001976
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001977 // See if we're dealing with constant values.
1978 Constant *C1 = dyn_cast<Constant>(Op1);
1979 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00001980 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001981 : nullptr;
1982
1983 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1984 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00001985 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001986 APInt Len = V11.zextOrTrunc(6);
1987 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001988 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001989 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00001990 }
1991
1992 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1993 // operand.
1994 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001995 II->setArgOperand(0, V);
1996 return II;
1997 }
1998 break;
1999 }
2000
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002001 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002002 // INSERTQI: Extract lowest Length bits from lower half of second source and
2003 // insert over first source starting at Index bit. The upper 64-bits are
2004 // undefined.
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 == 2 && "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 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2015 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2016
2017 // Attempt to simplify to a constant or shuffle vector.
2018 if (CILength && CIIndex) {
2019 APInt Len = CILength->getValue().zextOrTrunc(6);
2020 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002021 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002022 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002023 }
2024
2025 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2026 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002027 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002028 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2029 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002030 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002031 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002032 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2033 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002034 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002035 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002036 if (MadeChange)
2037 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002038 break;
2039 }
2040
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002041 case Intrinsic::x86_sse41_pblendvb:
2042 case Intrinsic::x86_sse41_blendvps:
2043 case Intrinsic::x86_sse41_blendvpd:
2044 case Intrinsic::x86_avx_blendv_ps_256:
2045 case Intrinsic::x86_avx_blendv_pd_256:
2046 case Intrinsic::x86_avx2_pblendvb: {
2047 // Convert blendv* to vector selects if the mask is constant.
2048 // This optimization is convoluted because the intrinsic is defined as
2049 // getting a vector of floats or doubles for the ps and pd versions.
2050 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002051
2052 Value *Op0 = II->getArgOperand(0);
2053 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002054 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002055
2056 // fold (blend A, A, Mask) -> A
2057 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002058 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002059
2060 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002061 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002062 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002063
2064 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002065 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2066 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002067 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002068 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002069 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002070 }
2071
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002072 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002073 case Intrinsic::x86_avx2_pshuf_b:
2074 if (Value *V = simplifyX86pshufb(*II, *Builder))
2075 return replaceInstUsesWith(*II, V);
2076 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002077
Rafael Espindolabad3f772014-04-21 22:06:04 +00002078 case Intrinsic::x86_avx_vpermilvar_ps:
2079 case Intrinsic::x86_avx_vpermilvar_ps_256:
2080 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002081 case Intrinsic::x86_avx_vpermilvar_pd_256:
2082 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2083 return replaceInstUsesWith(*II, V);
2084 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002085
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002086 case Intrinsic::x86_avx2_permd:
2087 case Intrinsic::x86_avx2_permps:
2088 if (Value *V = simplifyX86vpermv(*II, *Builder))
2089 return replaceInstUsesWith(*II, V);
2090 break;
2091
Sanjay Patelccf5f242015-03-20 21:47:56 +00002092 case Intrinsic::x86_avx_vperm2f128_pd_256:
2093 case Intrinsic::x86_avx_vperm2f128_ps_256:
2094 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002095 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002096 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002097 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002098 break;
2099
Sanjay Patel98a71502016-02-29 23:16:48 +00002100 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002101 case Intrinsic::x86_avx_maskload_pd:
2102 case Intrinsic::x86_avx_maskload_ps_256:
2103 case Intrinsic::x86_avx_maskload_pd_256:
2104 case Intrinsic::x86_avx2_maskload_d:
2105 case Intrinsic::x86_avx2_maskload_q:
2106 case Intrinsic::x86_avx2_maskload_d_256:
2107 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002108 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2109 return I;
2110 break;
2111
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002112 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002113 case Intrinsic::x86_avx_maskstore_ps:
2114 case Intrinsic::x86_avx_maskstore_pd:
2115 case Intrinsic::x86_avx_maskstore_ps_256:
2116 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002117 case Intrinsic::x86_avx2_maskstore_d:
2118 case Intrinsic::x86_avx2_maskstore_q:
2119 case Intrinsic::x86_avx2_maskstore_d_256:
2120 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002121 if (simplifyX86MaskedStore(*II, *this))
2122 return nullptr;
2123 break;
2124
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002125 case Intrinsic::x86_xop_vpcomb:
2126 case Intrinsic::x86_xop_vpcomd:
2127 case Intrinsic::x86_xop_vpcomq:
2128 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002129 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002130 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002131 break;
2132
2133 case Intrinsic::x86_xop_vpcomub:
2134 case Intrinsic::x86_xop_vpcomud:
2135 case Intrinsic::x86_xop_vpcomuq:
2136 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002137 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002138 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002139 break;
2140
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002141 case Intrinsic::ppc_altivec_vperm:
2142 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002143 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2144 // a vectorshuffle for little endian, we must undo the transformation
2145 // performed on vec_perm in altivec.h. That is, we must complement
2146 // the permutation mask with respect to 31 and reverse the order of
2147 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002148 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2149 assert(Mask->getType()->getVectorNumElements() == 16 &&
2150 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002151
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002152 // Check that all of the elements are integer constants or undefs.
2153 bool AllEltsOk = true;
2154 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002155 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002156 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002157 AllEltsOk = false;
2158 break;
2159 }
2160 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002161
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002162 if (AllEltsOk) {
2163 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002164 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2165 Mask->getType());
2166 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2167 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002168 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002169
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002170 // Only extract each element once.
2171 Value *ExtractedElts[32];
2172 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002173
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002174 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002175 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002176 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002177 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002178 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002179 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002180 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002181 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002182
Craig Topperf40110f2014-04-25 05:29:35 +00002183 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002184 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2185 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002186 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002187 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002188 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002189 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002190
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002191 // Insert this value into the result vector.
2192 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002193 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002194 }
2195 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2196 }
2197 }
2198 break;
2199
Bob Wilsona4e231c2010-10-22 21:41:48 +00002200 case Intrinsic::arm_neon_vld1:
2201 case Intrinsic::arm_neon_vld2:
2202 case Intrinsic::arm_neon_vld3:
2203 case Intrinsic::arm_neon_vld4:
2204 case Intrinsic::arm_neon_vld2lane:
2205 case Intrinsic::arm_neon_vld3lane:
2206 case Intrinsic::arm_neon_vld4lane:
2207 case Intrinsic::arm_neon_vst1:
2208 case Intrinsic::arm_neon_vst2:
2209 case Intrinsic::arm_neon_vst3:
2210 case Intrinsic::arm_neon_vst4:
2211 case Intrinsic::arm_neon_vst2lane:
2212 case Intrinsic::arm_neon_vst3lane:
2213 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00002214 unsigned MemAlign =
2215 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00002216 unsigned AlignArg = II->getNumArgOperands() - 1;
2217 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2218 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2219 II->setArgOperand(AlignArg,
2220 ConstantInt::get(Type::getInt32Ty(II->getContext()),
2221 MemAlign, false));
2222 return II;
2223 }
2224 break;
2225 }
2226
Lang Hames3a90fab2012-05-01 00:20:38 +00002227 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00002228 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00002229 case Intrinsic::aarch64_neon_smull:
2230 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00002231 Value *Arg0 = II->getArgOperand(0);
2232 Value *Arg1 = II->getArgOperand(1);
2233
2234 // Handle mul by zero first:
2235 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002236 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00002237 }
2238
2239 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00002240 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00002241 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00002242 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00002243 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2244 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2245 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2246 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2247
Sanjay Patel4b198802016-02-01 22:23:39 +00002248 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00002249 }
2250
Alp Tokercb402912014-01-24 17:20:08 +00002251 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00002252 std::swap(Arg0, Arg1);
2253 }
2254
2255 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00002256 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00002257 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00002258 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2259 if (Splat->isOne())
2260 return CastInst::CreateIntegerCast(Arg0, II->getType(),
2261 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00002262
2263 break;
2264 }
2265
Matt Arsenaultbef34e22016-01-22 21:30:34 +00002266 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002267 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2268 const APFloat &ArgVal = C->getValueAPF();
2269 APFloat Val(ArgVal.getSemantics(), 1.0);
2270 APFloat::opStatus Status = Val.divide(ArgVal,
2271 APFloat::rmNearestTiesToEven);
2272 // Only do this if it was exact and therefore not dependent on the
2273 // rounding mode.
2274 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00002275 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00002276 }
2277
2278 break;
2279 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002280 case Intrinsic::amdgcn_frexp_mant:
2281 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002282 Value *Src = II->getArgOperand(0);
2283 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2284 int Exp;
2285 APFloat Significand = frexp(C->getValueAPF(), Exp,
2286 APFloat::rmNearestTiesToEven);
2287
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00002288 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2289 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2290 Significand));
2291 }
2292
2293 // Match instruction special case behavior.
2294 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2295 Exp = 0;
2296
2297 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2298 }
2299
2300 if (isa<UndefValue>(Src))
2301 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00002302
2303 break;
2304 }
Matt Arsenault46a03822016-09-03 07:06:58 +00002305 case Intrinsic::amdgcn_class: {
2306 enum {
2307 S_NAN = 1 << 0, // Signaling NaN
2308 Q_NAN = 1 << 1, // Quiet NaN
2309 N_INFINITY = 1 << 2, // Negative infinity
2310 N_NORMAL = 1 << 3, // Negative normal
2311 N_SUBNORMAL = 1 << 4, // Negative subnormal
2312 N_ZERO = 1 << 5, // Negative zero
2313 P_ZERO = 1 << 6, // Positive zero
2314 P_SUBNORMAL = 1 << 7, // Positive subnormal
2315 P_NORMAL = 1 << 8, // Positive normal
2316 P_INFINITY = 1 << 9 // Positive infinity
2317 };
2318
2319 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
2320 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
2321
2322 Value *Src0 = II->getArgOperand(0);
2323 Value *Src1 = II->getArgOperand(1);
2324 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
2325 if (!CMask) {
2326 if (isa<UndefValue>(Src0))
2327 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2328
2329 if (isa<UndefValue>(Src1))
2330 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2331 break;
2332 }
2333
2334 uint32_t Mask = CMask->getZExtValue();
2335
2336 // If all tests are made, it doesn't matter what the value is.
2337 if ((Mask & FullMask) == FullMask)
2338 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
2339
2340 if ((Mask & FullMask) == 0)
2341 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2342
2343 if (Mask == (S_NAN | Q_NAN)) {
2344 // Equivalent of isnan. Replace with standard fcmp.
2345 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
2346 FCmp->takeName(II);
2347 return replaceInstUsesWith(*II, FCmp);
2348 }
2349
2350 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
2351 if (!CVal) {
2352 if (isa<UndefValue>(Src0))
2353 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2354
2355 // Clamp mask to used bits
2356 if ((Mask & FullMask) != Mask) {
2357 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
2358 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
2359 );
2360
2361 NewCall->takeName(II);
2362 return replaceInstUsesWith(*II, NewCall);
2363 }
2364
2365 break;
2366 }
2367
2368 const APFloat &Val = CVal->getValueAPF();
2369
2370 bool Result =
2371 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
2372 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
2373 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
2374 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
2375 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
2376 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
2377 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
2378 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
2379 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
2380 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
2381
2382 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
2383 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002384 case Intrinsic::stackrestore: {
2385 // If the save is right next to the restore, remove the restore. This can
2386 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00002387 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002388 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002389 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00002390 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002391 }
2392 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002393
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002394 // Scan down this block to see if there is another stack restore in the
2395 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002396 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002397 TerminatorInst *TI = II->getParent()->getTerminator();
2398 bool CannotRemove = false;
2399 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00002400 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002401 CannotRemove = true;
2402 break;
2403 }
2404 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2405 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2406 // If there is a stackrestore below this one, remove this one.
2407 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00002408 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00002409
2410 // Bail if we cross over an intrinsic with side effects, such as
2411 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2412 if (II->mayHaveSideEffects()) {
2413 CannotRemove = true;
2414 break;
2415 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002416 } else {
2417 // If we found a non-intrinsic call, we can't remove the stack
2418 // restore.
2419 CannotRemove = true;
2420 break;
2421 }
2422 }
2423 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002424
Bill Wendlingf891bf82011-07-31 06:30:59 +00002425 // If the stack restore is in a return, resume, or unwind block and if there
2426 // are no allocas or calls between the restore and the return, nuke the
2427 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00002428 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00002429 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002430 break;
2431 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00002432 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00002433 // Asan needs to poison memory to detect invalid access which is possible
2434 // even for empty lifetime range.
2435 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2436 break;
2437
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00002438 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2439 Intrinsic::lifetime_end, *this))
2440 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00002441 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00002442 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00002443 Value *IIOperand = II->getArgOperand(0);
2444 // Remove an assume if it is immediately followed by an identical assume.
2445 if (match(II->getNextNode(),
2446 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2447 return eraseInstFromFunction(CI);
2448
Hal Finkelf5867a72014-07-25 21:45:17 +00002449 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00002450 // Note: New assumption intrinsics created here are registered by
2451 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00002452 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00002453 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2454 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2455 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002456 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002457 }
2458 // assume(!(a || b)) -> assume(!a); assume(!b);
2459 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00002460 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2461 II->getName());
2462 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2463 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00002464 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00002465 }
Hal Finkel04a15612014-10-04 21:27:06 +00002466
Philip Reames66c6de62014-11-11 23:33:19 +00002467 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2468 // (if assume is valid at the load)
2469 if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2470 Value *LHS = ICmp->getOperand(0);
2471 Value *RHS = ICmp->getOperand(1);
2472 if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2473 isa<LoadInst>(LHS) &&
2474 isa<Constant>(RHS) &&
2475 RHS->getType()->isPointerTy() &&
2476 cast<Constant>(RHS)->isNullValue()) {
2477 LoadInst* LI = cast<LoadInst>(LHS);
Justin Bogner99798402016-08-05 01:06:44 +00002478 if (isValidAssumeForContext(II, LI, &DT)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +00002479 MDNode *MD = MDNode::get(II->getContext(), None);
Philip Reames66c6de62014-11-11 23:33:19 +00002480 LI->setMetadata(LLVMContext::MD_nonnull, MD);
Sanjay Patel4b198802016-02-01 22:23:39 +00002481 return eraseInstFromFunction(*II);
Philip Reames66c6de62014-11-11 23:33:19 +00002482 }
2483 }
Chandler Carruth24969102015-02-10 08:07:32 +00002484 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00002485 // TODO: apply range metadata for range check patterns?
2486 }
Hal Finkel04a15612014-10-04 21:27:06 +00002487 // If there is a dominating assume with the same condition as this one,
2488 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00002489 APInt KnownZero(1, 0), KnownOne(1, 0);
2490 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2491 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00002492 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00002493
Hal Finkelf5867a72014-07-25 21:45:17 +00002494 break;
2495 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002496 case Intrinsic::experimental_gc_relocate: {
2497 // Translate facts known about a pointer before relocating into
2498 // facts about the relocate value, while being careful to
2499 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00002500 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00002501
2502 // Remove the relocation if unused, note that this check is required
2503 // to prevent the cases below from looping forever.
2504 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00002505 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00002506
2507 // Undef is undef, even after relocation.
2508 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
2509 // most practical collectors, but there was discussion in the review thread
2510 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00002511 if (isa<UndefValue>(DerivedPtr))
2512 // Use undef of gc_relocate's type to replace it.
2513 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00002514
Philip Reamesea4d8e82016-02-09 21:09:22 +00002515 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2516 // The relocation of null will be null for most any collector.
2517 // TODO: provide a hook for this in GCStrategy. There might be some
2518 // weird collector this property does not hold for.
2519 if (isa<ConstantPointerNull>(DerivedPtr))
2520 // Use null-pointer of gc_relocate's type to replace it.
2521 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002522
Philip Reamesea4d8e82016-02-09 21:09:22 +00002523 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00002524 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00002525 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002526 }
Philip Reames9db26ff2014-12-29 23:27:30 +00002527
2528 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2529 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00002530
Philip Reames9db26ff2014-12-29 23:27:30 +00002531 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00002532 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00002533 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002534 }
2535
2536 return visitCallSite(II);
2537}
2538
2539// InvokeInst simplification
2540//
2541Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2542 return visitCallSite(&II);
2543}
2544
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002545/// If this cast does not affect the value passed through the varargs area, we
2546/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002547static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002548 const DataLayout &DL,
2549 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002550 const int ix) {
2551 if (!CI->isLosslessCast())
2552 return false;
2553
Philip Reames1a1bdb22014-12-02 18:50:36 +00002554 // If this is a GC intrinsic, avoid munging types. We need types for
2555 // statepoint reconstruction in SelectionDAG.
2556 // TODO: This is probably something which should be expanded to all
2557 // intrinsics since the entire point of intrinsics is that
2558 // they are understandable by the optimizer.
2559 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2560 return false;
2561
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002562 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002563 // can't change to a type with a different size. If the size were
2564 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002565 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002566 return true;
2567
Jim Grosbach7815f562012-02-03 00:07:04 +00002568 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002569 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00002570 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002571 if (!SrcTy->isSized() || !DstTy->isSized())
2572 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002573 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002574 return false;
2575 return true;
2576}
2577
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002578Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00002579 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002580
Chandler Carruthba4c5172015-01-21 11:23:40 +00002581 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00002582 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002583 };
Justin Bogner99798402016-08-05 01:06:44 +00002584 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00002585 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00002586 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00002587 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00002588 }
Meador Ingedf796f82012-10-13 16:45:24 +00002589
Craig Topperf40110f2014-04-25 05:29:35 +00002590 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00002591}
2592
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002593static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002594 // Strip off at most one level of pointer casts, looking for an alloca. This
2595 // is good enough in practice and simpler than handling any number of casts.
2596 Value *Underlying = TrampMem->stripPointerCasts();
2597 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00002598 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00002599 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002600 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00002601 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002602
Craig Topperf40110f2014-04-25 05:29:35 +00002603 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00002604 for (User *U : TrampMem->users()) {
2605 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00002606 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00002607 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002608 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2609 if (InitTrampoline)
2610 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00002611 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002612 InitTrampoline = II;
2613 continue;
2614 }
2615 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2616 // Allow any number of calls to adjust.trampoline.
2617 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00002618 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002619 }
2620
2621 // No call to init.trampoline found.
2622 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002623 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002624
2625 // Check that the alloca is being used in the expected way.
2626 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00002627 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002628
2629 return InitTrampoline;
2630}
2631
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002632static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00002633 Value *TrampMem) {
2634 // Visit all the previous instructions in the basic block, and try to find a
2635 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00002636 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2637 E = AdjustTramp->getParent()->begin();
2638 I != E;) {
2639 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00002640 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2641 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2642 II->getOperand(0) == TrampMem)
2643 return II;
2644 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00002645 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002646 }
Craig Topperf40110f2014-04-25 05:29:35 +00002647 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002648}
2649
2650// Given a call to llvm.adjust.trampoline, find and return the corresponding
2651// call to llvm.init.trampoline if the call to the trampoline can be optimized
2652// to a direct call to a function. Otherwise return NULL.
2653//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002654static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00002655 Callee = Callee->stripPointerCasts();
2656 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2657 if (!AdjustTramp ||
2658 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00002659 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002660
2661 Value *TrampMem = AdjustTramp->getOperand(0);
2662
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002663 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002664 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002665 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00002666 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00002667 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00002668}
2669
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002670/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002671Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00002672 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00002673 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00002674
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002675 bool Changed = false;
2676
Philip Reamesc25df112015-06-16 20:24:25 +00002677 // Mark any parameters that are known to be non-null with the nonnull
2678 // attribute. This is helpful for inlining calls to functions with null
2679 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00002680 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00002681 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00002682
Philip Reamesc25df112015-06-16 20:24:25 +00002683 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00002684 if (V->getType()->isPointerTy() &&
2685 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00002686 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00002687 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00002688 ArgNo++;
2689 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00002690
Philip Reamesc25df112015-06-16 20:24:25 +00002691 assert(ArgNo == CS.arg_size() && "sanity check");
2692
Akira Hatanaka237916b2015-12-02 06:58:49 +00002693 if (!Indices.empty()) {
2694 AttributeSet AS = CS.getAttributes();
2695 LLVMContext &Ctx = CS.getInstruction()->getContext();
2696 AS = AS.addAttribute(Ctx, Indices,
2697 Attribute::get(Ctx, Attribute::NonNull));
2698 CS.setAttributes(AS);
2699 Changed = true;
2700 }
2701
Chris Lattner73989652010-12-20 08:25:06 +00002702 // If the callee is a pointer to a function, attempt to move any casts to the
2703 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002704 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00002705 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00002706 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002707
Justin Lebar9d943972016-03-14 20:18:54 +00002708 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2709 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00002710 if (CS.isConvergent() && !CalleeF->isConvergent() &&
2711 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00002712 DEBUG(dbgs() << "Removing convergent attr from instr "
2713 << CS.getInstruction() << "\n");
2714 CS.setNotConvergent();
2715 return CS.getInstruction();
2716 }
2717
Chris Lattner846a52e2010-02-01 18:11:34 +00002718 // If the call and callee calling conventions don't match, this call must
2719 // be unreachable, as the call is undefined.
2720 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2721 // Only do this for calls to a function with a body. A prototype may
2722 // not actually end up matching the implementation's calling conv for a
2723 // variety of reasons (e.g. it may be written in assembly).
2724 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002725 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002726 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00002727 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002728 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00002729 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002730 // This allows ValueHandlers and custom metadata to adjust itself.
2731 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002732 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00002733 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00002734 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00002735
Chris Lattner2cecedf2010-02-01 18:04:58 +00002736 // We cannot remove an invoke, because it would change the CFG, just
2737 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00002738 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00002739 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00002740 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002741 }
Justin Lebar9d943972016-03-14 20:18:54 +00002742 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002743
2744 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002745 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002746 // This allows ValueHandlers and custom metadata to adjust itself.
2747 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00002748 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00002749 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002750
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002751 if (isa<InvokeInst>(CS.getInstruction())) {
2752 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00002753 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002754 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00002755
2756 // This instruction is not reachable, just remove it. We insert a store to
2757 // undef so that we know that this code is not reachable, despite the fact
2758 // that we can't modify the CFG here.
2759 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2760 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2761 CS.getInstruction());
2762
Sanjay Patel4b198802016-02-01 22:23:39 +00002763 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002764 }
2765
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002766 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00002767 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002768
Chris Lattner229907c2011-07-18 04:54:35 +00002769 PointerType *PTy = cast<PointerType>(Callee->getType());
2770 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002771 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00002772 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002773 // See if we can optimize any arguments passed through the varargs area of
2774 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002775 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002776 E = CS.arg_end(); I != E; ++I, ++ix) {
2777 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002778 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002779 *I = CI->getOperand(0);
2780 Changed = true;
2781 }
2782 }
2783 }
2784
2785 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2786 // Inline asm calls cannot throw - mark them 'nounwind'.
2787 CS.setDoesNotThrow();
2788 Changed = true;
2789 }
2790
Micah Villmowcdfe20b2012-10-08 16:38:25 +00002791 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00002792 // this. None of these calls are seen as possibly dead so go ahead and
2793 // delete the instruction now.
2794 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002795 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00002796 // If we changed something return the result, etc. Otherwise let
2797 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00002798 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00002799 }
2800
Craig Topperf40110f2014-04-25 05:29:35 +00002801 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002802}
2803
Sanjay Patelcd4377c2016-01-20 22:24:38 +00002804/// If the callee is a constexpr cast of a function, attempt to move the cast to
2805/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002806bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00002807 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00002808 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002809 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002810
2811 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00002812 if (Callee->hasFnAttribute("thunk"))
2813 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00002814
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002815 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00002816 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002817
2818 // Okay, this is a cast from a function to a different type. Unless doing so
2819 // would cause a type conversion of one of our arguments, change this call to
2820 // be a direct call with arguments casted to the appropriate types.
2821 //
Chris Lattner229907c2011-07-18 04:54:35 +00002822 FunctionType *FT = Callee->getFunctionType();
2823 Type *OldRetTy = Caller->getType();
2824 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002825
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002826 // Check to see if we are changing the return type...
2827 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00002828
2829 if (NewRetTy->isStructTy())
2830 return false; // TODO: Handle multiple return values.
2831
David Majnemer9b6b8222015-01-06 08:41:31 +00002832 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002833 if (Callee->isDeclaration())
2834 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002835
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002836 if (!Caller->use_empty() &&
2837 // void -> non-void is handled specially
2838 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00002839 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00002840 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002841
2842 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00002843 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00002844 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002845 return false; // Attribute not compatible with transformed value.
2846 }
2847
2848 // If the callsite is an invoke instruction, and the return value is used by
2849 // a PHI node in a successor, we cannot change the return type of the call
2850 // because there is no place to put the cast instruction (without breaking
2851 // the critical edge). Bail out in this case.
2852 if (!Caller->use_empty())
2853 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00002854 for (User *U : II->users())
2855 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002856 if (PN->getParent() == II->getNormalDest() ||
2857 PN->getParent() == II->getUnwindDest())
2858 return false;
2859 }
2860
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00002861 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002862 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2863
David Majnemer9b6b8222015-01-06 08:41:31 +00002864 // Prevent us turning:
2865 // declare void @takes_i32_inalloca(i32* inalloca)
2866 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2867 //
2868 // into:
2869 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00002870 //
2871 // Similarly, avoid folding away bitcasts of byval calls.
2872 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2873 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00002874 return false;
2875
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002876 CallSite::arg_iterator AI = CS.arg_begin();
2877 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002878 Type *ParamTy = FT->getParamType(i);
2879 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002880
David Majnemer9b6b8222015-01-06 08:41:31 +00002881 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002882 return false; // Cannot transform this parameter value.
2883
Bill Wendling49bc76c2013-01-23 06:14:59 +00002884 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00002885 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002886 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00002887
Reid Kleckner26af2ca2014-01-28 02:38:36 +00002888 if (CS.isInAllocaArgument(i))
2889 return false; // Cannot transform to and from inalloca.
2890
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002891 // If the parameter is passed as a byval argument, then we have to have a
2892 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002893 if (ParamTy != ActTy &&
2894 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2895 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00002896 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002897 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002898 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00002899
Matt Arsenaultfa252722013-09-27 22:18:51 +00002900 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002901 if (DL.getTypeAllocSize(CurElTy) !=
2902 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00002903 return false;
2904 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002905 }
2906
Chris Lattneradf38b32011-02-24 05:10:56 +00002907 if (Callee->isDeclaration()) {
2908 // Do not delete arguments unless we have a function body.
2909 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2910 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002911
Chris Lattneradf38b32011-02-24 05:10:56 +00002912 // If the callee is just a declaration, don't change the varargsness of the
2913 // call. We don't want to introduce a varargs call where one doesn't
2914 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00002915 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00002916 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2917 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002918
2919 // If both the callee and the cast type are varargs, we still have to make
2920 // sure the number of fixed parameters are the same or we have the same
2921 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00002922 if (FT->isVarArg() &&
2923 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2924 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00002925 cast<FunctionType>(APTy->getElementType())->getNumParams())
2926 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00002927 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002928
Jim Grosbach0ab54182012-02-03 00:00:50 +00002929 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2930 !CallerPAL.isEmpty())
2931 // In this case we have more arguments than the new function type, but we
2932 // won't be dropping them. Check that these extra arguments have attributes
2933 // that are compatible with being a vararg call argument.
2934 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00002935 unsigned Index = CallerPAL.getSlotIndex(i - 1);
2936 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00002937 break;
Bill Wendling57625a42013-01-25 23:09:36 +00002938
Bill Wendlingd97b75d2012-12-19 08:57:40 +00002939 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00002940 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2941 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00002942 return false;
2943 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002944
Jim Grosbach7815f562012-02-03 00:07:04 +00002945
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002946 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00002947 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002948 std::vector<Value*> Args;
2949 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00002950 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002951 attrVec.reserve(NumCommonArgs);
2952
2953 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00002954 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002955
2956 // If the return value is not being used, the type may not be compatible
2957 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00002958 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002959
2960 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00002961 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002962 attrVec.push_back(AttributeSet::get(Caller->getContext(),
2963 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002964
2965 AI = CS.arg_begin();
2966 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002967 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00002968
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002969 if ((*AI)->getType() == ParamTy) {
2970 Args.push_back(*AI);
2971 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00002972 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002973 }
2974
2975 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00002976 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00002977 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00002978 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2979 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002980 }
2981
2982 // If the function takes more arguments than the call was taking, add them
2983 // now.
2984 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2985 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2986
2987 // If we are removing arguments to the function, emit an obnoxious warning.
2988 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00002989 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
2990 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002991 // Add all of the arguments in their promoted form to the arg list.
2992 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00002993 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002994 if (PTy != (*AI)->getType()) {
2995 // Must promote to pass through va_arg area!
2996 Instruction::CastOps opcode =
2997 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002998 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002999 } else {
3000 Args.push_back(*AI);
3001 }
3002
3003 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003004 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003005 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003006 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
3007 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003008 }
3009 }
3010 }
3011
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003012 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00003013 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003014 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003015
3016 if (NewRetTy->isVoidTy())
3017 Caller->setName(""); // Void type should not have a name.
3018
Bill Wendlinge94d8432012-12-07 23:16:57 +00003019 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003020 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003021
Sanjoy Das76293462015-11-25 00:42:19 +00003022 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00003023 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00003024
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003025 Instruction *NC;
3026 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00003027 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
3028 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003029 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003030 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
3031 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
3032 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003033 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00003034 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003035 NC->takeName(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003036 if (CI->isTailCall())
3037 cast<CallInst>(NC)->setTailCall();
3038 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
3039 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
3040 }
3041
3042 // Insert a cast of the return type as necessary.
3043 Value *NV = NC;
3044 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3045 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00003046 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00003047 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003048
3049 // If this is an invoke instruction, we should insert it after the first
3050 // non-phi, instruction in the normal successor block.
3051 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00003052 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003053 InsertNewInstBefore(NC, *I);
3054 } else {
Chris Lattner73989652010-12-20 08:25:06 +00003055 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003056 InsertNewInstBefore(NC, *Caller);
3057 }
3058 Worklist.AddUsersToWorkList(*Caller);
3059 } else {
3060 NV = UndefValue::get(Caller->getType());
3061 }
3062 }
3063
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003064 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003065 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00003066 else if (Caller->hasValueHandle()) {
3067 if (OldRetTy == NV->getType())
3068 ValueHandleBase::ValueIsRAUWd(Caller, NV);
3069 else
3070 // We cannot call ValueIsRAUWd with a different type, and the
3071 // actual tracked value will disappear.
3072 ValueHandleBase::ValueIsDeleted(Caller);
3073 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003074
Sanjay Patel4b198802016-02-01 22:23:39 +00003075 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003076 return true;
3077}
3078
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003079/// Turn a call to a function created by init_trampoline / adjust_trampoline
3080/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00003081Instruction *
3082InstCombiner::transformCallThroughTrampoline(CallSite CS,
3083 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003084 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00003085 PointerType *PTy = cast<PointerType>(Callee->getType());
3086 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00003087 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003088
3089 // If the call already has the 'nest' attribute somewhere then give up -
3090 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00003091 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00003092 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003093
Duncan Sandsa0984362011-09-06 13:37:06 +00003094 assert(Tramp &&
3095 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003096
Gabor Greif3e44ea12010-07-22 10:37:47 +00003097 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003098 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003099
Bill Wendlinge94d8432012-12-07 23:16:57 +00003100 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003101 if (!NestAttrs.isEmpty()) {
3102 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00003103 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00003104 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003105
3106 // Look for a parameter marked with the 'nest' attribute.
3107 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3108 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00003109 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003110 // Record the parameter type and any other attributes.
3111 NestTy = *I;
3112 NestAttr = NestAttrs.getParamAttributes(NestIdx);
3113 break;
3114 }
3115
3116 if (NestTy) {
3117 Instruction *Caller = CS.getInstruction();
3118 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003119 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003120
Bill Wendling3575c8c2013-01-27 02:08:22 +00003121 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003122 NewAttrs.reserve(Attrs.getNumSlots() + 1);
3123
3124 // Insert the nest argument into the call argument list, which may
3125 // mean appending it. Likewise for attributes.
3126
3127 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003128 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003129 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3130 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003131
3132 {
3133 unsigned Idx = 1;
3134 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3135 do {
3136 if (Idx == NestIdx) {
3137 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00003138 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003139 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00003140 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003141 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003142 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3143 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003144 }
3145
3146 if (I == E)
3147 break;
3148
3149 // Add the original argument and attributes.
3150 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00003151 AttributeSet Attr = Attrs.getParamAttributes(Idx);
3152 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00003153 AttrBuilder B(Attr, Idx);
3154 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3155 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00003156 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003157
Richard Trieu7a083812016-02-18 22:09:30 +00003158 ++Idx;
3159 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003160 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003161 }
3162
3163 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00003164 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003165 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3166 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003167
3168 // The trampoline may have been bitcast to a bogus type (FTy).
3169 // Handle this by synthesizing a new function type, equal to FTy
3170 // with the chain parameter inserted.
3171
Jay Foadb804a2b2011-07-12 14:06:48 +00003172 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003173 NewTypes.reserve(FTy->getNumParams()+1);
3174
3175 // Insert the chain's type into the list of parameter types, which may
3176 // mean appending it.
3177 {
3178 unsigned Idx = 1;
3179 FunctionType::param_iterator I = FTy->param_begin(),
3180 E = FTy->param_end();
3181
3182 do {
3183 if (Idx == NestIdx)
3184 // Add the chain's type.
3185 NewTypes.push_back(NestTy);
3186
3187 if (I == E)
3188 break;
3189
3190 // Add the original type.
3191 NewTypes.push_back(*I);
3192
Richard Trieu7a083812016-02-18 22:09:30 +00003193 ++Idx;
3194 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003195 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003196 }
3197
3198 // Replace the trampoline call with a direct call. Let the generic
3199 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00003200 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003201 FTy->isVarArg());
3202 Constant *NewCallee =
3203 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00003204 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003205 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00003206 const AttributeSet &NewPAL =
3207 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003208
David Majnemer231a68c2016-04-29 08:07:20 +00003209 SmallVector<OperandBundleDef, 1> OpBundles;
3210 CS.getOperandBundlesAsDefs(OpBundles);
3211
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003212 Instruction *NewCaller;
3213 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3214 NewCaller = InvokeInst::Create(NewCallee,
3215 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00003216 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003217 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3218 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3219 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00003220 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003221 if (cast<CallInst>(Caller)->isTailCall())
3222 cast<CallInst>(NewCaller)->setTailCall();
3223 cast<CallInst>(NewCaller)->
3224 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
3225 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3226 }
Eli Friedman49346012011-05-18 19:57:14 +00003227
3228 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003229 }
3230 }
3231
3232 // Replace the trampoline call with a direct call. Since there is no 'nest'
3233 // parameter, there is no need to adjust the argument list. Let the generic
3234 // code sort out any function type mismatches.
3235 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00003236 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003237 ConstantExpr::getBitCast(NestF, PTy);
3238 CS.setCalledFunction(NewCallee);
3239 return CS.getInstruction();
3240}