blob: 644dfd50adc2ea085c20d95bd4a193004ab3bc59 [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"
Craig Topperb45eabc2017-04-26 16:39:58 +000047#include "llvm/Support/KnownBits.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000048#include "llvm/Support/MathExtras.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000049#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000050#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000051#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <cstring>
55#include <vector>
56
Chris Lattner7a9e47a2010-01-05 07:32:13 +000057using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000058using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000059
Chandler Carruth964daaa2014-04-22 02:55:47 +000060#define DEBUG_TYPE "instcombine"
61
Meador Ingee3f2b262012-11-30 04:05:06 +000062STATISTIC(NumSimplified, "Number of library calls simplified");
63
Igor Laevskya9b68722017-02-08 15:21:48 +000064static cl::opt<unsigned> UnfoldElementAtomicMemcpyMaxElements(
Igor Laevsky900ffa32017-02-08 14:32:04 +000065 "unfold-element-atomic-memcpy-max-elements",
66 cl::init(16),
67 cl::desc("Maximum number of elements in atomic memcpy the optimizer is "
68 "allowed to unfold"));
69
Sanjay Patelcd4377c2016-01-20 22:24:38 +000070/// Return the specified type promoted as it would be to pass though a va_arg
71/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000072static Type *getPromotedType(Type *Ty) {
73 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000074 if (ITy->getBitWidth() < 32)
75 return Type::getInt32Ty(Ty->getContext());
76 }
77 return Ty;
78}
79
Sanjay Patel368ac5d2016-02-21 17:29:33 +000080/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +000081/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +000082static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
83 SmallVector<Constant *, 32> BoolVec;
84 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
85 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
86 Constant *Elt = V->getElementAsConstant(I);
87 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
88 "Unexpected constant data vector element type");
89 bool Sign = V->getElementType()->isIntegerTy()
90 ? cast<ConstantInt>(Elt)->isNegative()
91 : cast<ConstantFP>(Elt)->isNegative();
92 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
93 }
94 return ConstantVector::get(BoolVec);
95}
96
Igor Laevsky900ffa32017-02-08 14:32:04 +000097Instruction *
98InstCombiner::SimplifyElementAtomicMemCpy(ElementAtomicMemCpyInst *AMI) {
99 // Try to unfold this intrinsic into sequence of explicit atomic loads and
100 // stores.
101 // First check that number of elements is compile time constant.
102 auto *NumElementsCI = dyn_cast<ConstantInt>(AMI->getNumElements());
103 if (!NumElementsCI)
104 return nullptr;
105
106 // Check that there are not too many elements.
107 uint64_t NumElements = NumElementsCI->getZExtValue();
108 if (NumElements >= UnfoldElementAtomicMemcpyMaxElements)
109 return nullptr;
110
111 // Don't unfold into illegal integers
112 uint64_t ElementSizeInBytes = AMI->getElementSizeInBytes() * 8;
113 if (!getDataLayout().isLegalInteger(ElementSizeInBytes))
114 return nullptr;
115
116 // Cast source and destination to the correct type. Intrinsic input arguments
117 // are usually represented as i8*.
118 // Often operands will be explicitly casted to i8* and we can just strip
119 // those casts instead of inserting new ones. However it's easier to rely on
120 // other InstCombine rules which will cover trivial cases anyway.
121 Value *Src = AMI->getRawSource();
122 Value *Dst = AMI->getRawDest();
123 Type *ElementPointerType = Type::getIntNPtrTy(
124 AMI->getContext(), ElementSizeInBytes, Src->getType()->getPointerAddressSpace());
125
126 Value *SrcCasted = Builder->CreatePointerCast(Src, ElementPointerType,
127 "memcpy_unfold.src_casted");
128 Value *DstCasted = Builder->CreatePointerCast(Dst, ElementPointerType,
129 "memcpy_unfold.dst_casted");
130
131 for (uint64_t i = 0; i < NumElements; ++i) {
132 // Get current element addresses
133 ConstantInt *ElementIdxCI =
134 ConstantInt::get(AMI->getContext(), APInt(64, i));
135 Value *SrcElementAddr =
136 Builder->CreateGEP(SrcCasted, ElementIdxCI, "memcpy_unfold.src_addr");
137 Value *DstElementAddr =
138 Builder->CreateGEP(DstCasted, ElementIdxCI, "memcpy_unfold.dst_addr");
139
140 // Load from the source. Transfer alignment information and mark load as
141 // unordered atomic.
142 LoadInst *Load = Builder->CreateLoad(SrcElementAddr, "memcpy_unfold.val");
143 Load->setOrdering(AtomicOrdering::Unordered);
144 // We know alignment of the first element. It is also guaranteed by the
145 // verifier that element size is less or equal than first element alignment
146 // and both of this values are powers of two.
147 // This means that all subsequent accesses are at least element size
148 // aligned.
149 // TODO: We can infer better alignment but there is no evidence that this
150 // will matter.
151 Load->setAlignment(i == 0 ? AMI->getSrcAlignment()
152 : AMI->getElementSizeInBytes());
153 Load->setDebugLoc(AMI->getDebugLoc());
154
155 // Store loaded value via unordered atomic store.
156 StoreInst *Store = Builder->CreateStore(Load, DstElementAddr);
157 Store->setOrdering(AtomicOrdering::Unordered);
158 Store->setAlignment(i == 0 ? AMI->getDstAlignment()
159 : AMI->getElementSizeInBytes());
160 Store->setDebugLoc(AMI->getDebugLoc());
161 }
162
163 // Set the number of elements of the copy to 0, it will be deleted on the
164 // next iteration.
165 AMI->setNumElements(Constant::getNullValue(NumElementsCI->getType()));
166 return AMI;
167}
168
Pete Cooper67cf9a72015-11-19 05:56:52 +0000169Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000170 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
171 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000172 unsigned MinAlign = std::min(DstAlign, SrcAlign);
173 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000174
Pete Cooper67cf9a72015-11-19 05:56:52 +0000175 if (CopyAlign < MinAlign) {
176 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000177 return MI;
178 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000179
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000180 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
181 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000182 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000183 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000184
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000185 // Source and destination pointer types are always "i8*" for intrinsic. See
186 // if the size is something we can handle with a single primitive load/store.
187 // A single load+store correctly handles overlapping memory in the memmove
188 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000189 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000190 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000191
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000192 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000193 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000194
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000195 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000196 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000197 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000198 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000199 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000200
Chris Lattner229907c2011-07-18 04:54:35 +0000201 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000202 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
203 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000204
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000205 // If the memcpy has metadata describing the members, see if we can get the
206 // TBAA tag describing our copy.
Craig Topperf40110f2014-04-25 05:29:35 +0000207 MDNode *CopyMD = nullptr;
Mikael Holmen760dc9a2017-03-01 06:45:20 +0000208 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
209 if (M->getNumOperands() == 3 && M->getOperand(0) &&
210 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
211 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
212 M->getOperand(1) &&
213 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
214 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
215 Size &&
216 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
217 CopyMD = cast<MDNode>(M->getOperand(2));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000218 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000219
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000220 // If the memcpy/memmove provides better alignment info than we can
221 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000222 SrcAlign = std::max(SrcAlign, CopyAlign);
223 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000224
Gabor Greif5f3e6562010-06-25 07:57:14 +0000225 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
226 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000227 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
228 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000229 if (CopyMD)
230 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000231 MDNode *LoopMemParallelMD =
232 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
233 if (LoopMemParallelMD)
234 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000235
Eli Friedman49346012011-05-18 19:57:14 +0000236 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
237 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000238 if (CopyMD)
239 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000240 if (LoopMemParallelMD)
241 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000242
243 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000244 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000245 return MI;
246}
247
248Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000249 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000250 if (MI->getAlignment() < Alignment) {
251 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
252 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000253 return MI;
254 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000255
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000256 // Extract the length and alignment and fill if they are constant.
257 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
258 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000259 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000260 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000261 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000262 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000263 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000264
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000265 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
266 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000267 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000268
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000269 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000270 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
271 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
272 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000273
274 // Alignment 0 is identity for alignment 1 for memset, but not store.
275 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000276
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000277 // Extract the fill value and store.
278 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000279 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
280 MI->isVolatile());
281 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000282
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000283 // Set the size of the copy to 0, it will be deleted on the next iteration.
284 MI->setLength(Constant::getNullValue(LenC->getType()));
285 return MI;
286 }
287
Simon Pilgrim18617d12015-08-05 08:18:00 +0000288 return nullptr;
289}
290
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000291static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000292 InstCombiner::BuilderTy &Builder) {
293 bool LogicalShift = false;
294 bool ShiftLeft = false;
295
296 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000297 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000298 case Intrinsic::x86_sse2_psra_d:
299 case Intrinsic::x86_sse2_psra_w:
300 case Intrinsic::x86_sse2_psrai_d:
301 case Intrinsic::x86_sse2_psrai_w:
302 case Intrinsic::x86_avx2_psra_d:
303 case Intrinsic::x86_avx2_psra_w:
304 case Intrinsic::x86_avx2_psrai_d:
305 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000306 case Intrinsic::x86_avx512_psra_q_128:
307 case Intrinsic::x86_avx512_psrai_q_128:
308 case Intrinsic::x86_avx512_psra_q_256:
309 case Intrinsic::x86_avx512_psrai_q_256:
310 case Intrinsic::x86_avx512_psra_d_512:
311 case Intrinsic::x86_avx512_psra_q_512:
312 case Intrinsic::x86_avx512_psra_w_512:
313 case Intrinsic::x86_avx512_psrai_d_512:
314 case Intrinsic::x86_avx512_psrai_q_512:
315 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000316 LogicalShift = false; ShiftLeft = false;
317 break;
318 case Intrinsic::x86_sse2_psrl_d:
319 case Intrinsic::x86_sse2_psrl_q:
320 case Intrinsic::x86_sse2_psrl_w:
321 case Intrinsic::x86_sse2_psrli_d:
322 case Intrinsic::x86_sse2_psrli_q:
323 case Intrinsic::x86_sse2_psrli_w:
324 case Intrinsic::x86_avx2_psrl_d:
325 case Intrinsic::x86_avx2_psrl_q:
326 case Intrinsic::x86_avx2_psrl_w:
327 case Intrinsic::x86_avx2_psrli_d:
328 case Intrinsic::x86_avx2_psrli_q:
329 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000330 case Intrinsic::x86_avx512_psrl_d_512:
331 case Intrinsic::x86_avx512_psrl_q_512:
332 case Intrinsic::x86_avx512_psrl_w_512:
333 case Intrinsic::x86_avx512_psrli_d_512:
334 case Intrinsic::x86_avx512_psrli_q_512:
335 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000336 LogicalShift = true; ShiftLeft = false;
337 break;
338 case Intrinsic::x86_sse2_psll_d:
339 case Intrinsic::x86_sse2_psll_q:
340 case Intrinsic::x86_sse2_psll_w:
341 case Intrinsic::x86_sse2_pslli_d:
342 case Intrinsic::x86_sse2_pslli_q:
343 case Intrinsic::x86_sse2_pslli_w:
344 case Intrinsic::x86_avx2_psll_d:
345 case Intrinsic::x86_avx2_psll_q:
346 case Intrinsic::x86_avx2_psll_w:
347 case Intrinsic::x86_avx2_pslli_d:
348 case Intrinsic::x86_avx2_pslli_q:
349 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000350 case Intrinsic::x86_avx512_psll_d_512:
351 case Intrinsic::x86_avx512_psll_q_512:
352 case Intrinsic::x86_avx512_psll_w_512:
353 case Intrinsic::x86_avx512_pslli_d_512:
354 case Intrinsic::x86_avx512_pslli_q_512:
355 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000356 LogicalShift = true; ShiftLeft = true;
357 break;
358 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000359 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
360
Simon Pilgrim3815c162015-08-07 18:22:50 +0000361 // Simplify if count is constant.
362 auto Arg1 = II.getArgOperand(1);
363 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
364 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
365 auto CInt = dyn_cast<ConstantInt>(Arg1);
366 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000367 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000368
369 APInt Count(64, 0);
370 if (CDV) {
371 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
372 // operand to compute the shift amount.
373 auto VT = cast<VectorType>(CDV->getType());
374 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
375 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
376 unsigned NumSubElts = 64 / BitWidth;
377
378 // Concatenate the sub-elements to create the 64-bit value.
379 for (unsigned i = 0; i != NumSubElts; ++i) {
380 unsigned SubEltIdx = (NumSubElts - 1) - i;
381 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
Craig Topper24e71012017-04-28 03:36:24 +0000382 Count <<= BitWidth;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000383 Count |= SubElt->getValue().zextOrTrunc(64);
384 }
385 }
386 else if (CInt)
387 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000388
389 auto Vec = II.getArgOperand(0);
390 auto VT = cast<VectorType>(Vec->getType());
391 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000392 unsigned VWidth = VT->getNumElements();
393 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
394
395 // If shift-by-zero then just return the original value.
396 if (Count == 0)
397 return Vec;
398
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000399 // Handle cases when Shift >= BitWidth.
400 if (Count.uge(BitWidth)) {
401 // If LogicalShift - just return zero.
402 if (LogicalShift)
403 return ConstantAggregateZero::get(VT);
404
405 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
406 Count = APInt(64, BitWidth - 1);
407 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000408
Simon Pilgrim18617d12015-08-05 08:18:00 +0000409 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000410 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
411 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000412
413 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000414 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000415
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000416 if (LogicalShift)
417 return Builder.CreateLShr(Vec, ShiftVec);
418
419 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000420}
421
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000422// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
423// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
424// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
425static Value *simplifyX86varShift(const IntrinsicInst &II,
426 InstCombiner::BuilderTy &Builder) {
427 bool LogicalShift = false;
428 bool ShiftLeft = false;
429
430 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000431 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000432 case Intrinsic::x86_avx2_psrav_d:
433 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000434 case Intrinsic::x86_avx512_psrav_q_128:
435 case Intrinsic::x86_avx512_psrav_q_256:
436 case Intrinsic::x86_avx512_psrav_d_512:
437 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000438 case Intrinsic::x86_avx512_psrav_w_128:
439 case Intrinsic::x86_avx512_psrav_w_256:
440 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000441 LogicalShift = false;
442 ShiftLeft = false;
443 break;
444 case Intrinsic::x86_avx2_psrlv_d:
445 case Intrinsic::x86_avx2_psrlv_d_256:
446 case Intrinsic::x86_avx2_psrlv_q:
447 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000448 case Intrinsic::x86_avx512_psrlv_d_512:
449 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000450 case Intrinsic::x86_avx512_psrlv_w_128:
451 case Intrinsic::x86_avx512_psrlv_w_256:
452 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000453 LogicalShift = true;
454 ShiftLeft = false;
455 break;
456 case Intrinsic::x86_avx2_psllv_d:
457 case Intrinsic::x86_avx2_psllv_d_256:
458 case Intrinsic::x86_avx2_psllv_q:
459 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000460 case Intrinsic::x86_avx512_psllv_d_512:
461 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000462 case Intrinsic::x86_avx512_psllv_w_128:
463 case Intrinsic::x86_avx512_psllv_w_256:
464 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000465 LogicalShift = true;
466 ShiftLeft = true;
467 break;
468 }
469 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
470
471 // Simplify if all shift amounts are constant/undef.
472 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
473 if (!CShift)
474 return nullptr;
475
476 auto Vec = II.getArgOperand(0);
477 auto VT = cast<VectorType>(II.getType());
478 auto SVT = VT->getVectorElementType();
479 int NumElts = VT->getNumElements();
480 int BitWidth = SVT->getIntegerBitWidth();
481
482 // Collect each element's shift amount.
483 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
484 bool AnyOutOfRange = false;
485 SmallVector<int, 8> ShiftAmts;
486 for (int I = 0; I < NumElts; ++I) {
487 auto *CElt = CShift->getAggregateElement(I);
488 if (CElt && isa<UndefValue>(CElt)) {
489 ShiftAmts.push_back(-1);
490 continue;
491 }
492
493 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
494 if (!COp)
495 return nullptr;
496
497 // Handle out of range shifts.
498 // If LogicalShift - set to BitWidth (special case).
499 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
500 APInt ShiftVal = COp->getValue();
501 if (ShiftVal.uge(BitWidth)) {
502 AnyOutOfRange = LogicalShift;
503 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
504 continue;
505 }
506
507 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
508 }
509
510 // If all elements out of range or UNDEF, return vector of zeros/undefs.
511 // ArithmeticShift should only hit this if they are all UNDEF.
512 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000513 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000514 SmallVector<Constant *, 8> ConstantVec;
515 for (int Idx : ShiftAmts) {
516 if (Idx < 0) {
517 ConstantVec.push_back(UndefValue::get(SVT));
518 } else {
519 assert(LogicalShift && "Logical shift expected");
520 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
521 }
522 }
523 return ConstantVector::get(ConstantVec);
524 }
525
526 // We can't handle only some out of range values with generic logical shifts.
527 if (AnyOutOfRange)
528 return nullptr;
529
530 // Build the shift amount constant vector.
531 SmallVector<Constant *, 8> ShiftVecAmts;
532 for (int Idx : ShiftAmts) {
533 if (Idx < 0)
534 ShiftVecAmts.push_back(UndefValue::get(SVT));
535 else
536 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
537 }
538 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
539
540 if (ShiftLeft)
541 return Builder.CreateShl(Vec, ShiftVec);
542
543 if (LogicalShift)
544 return Builder.CreateLShr(Vec, ShiftVec);
545
546 return Builder.CreateAShr(Vec, ShiftVec);
547}
548
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000549static Value *simplifyX86muldq(const IntrinsicInst &II,
550 InstCombiner::BuilderTy &Builder) {
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000551 Value *Arg0 = II.getArgOperand(0);
552 Value *Arg1 = II.getArgOperand(1);
553 Type *ResTy = II.getType();
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000554 assert(Arg0->getType()->getScalarSizeInBits() == 32 &&
555 Arg1->getType()->getScalarSizeInBits() == 32 &&
556 ResTy->getScalarSizeInBits() == 64 && "Unexpected muldq/muludq types");
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000557
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000558 // muldq/muludq(undef, undef) -> zero (matches generic mul behavior)
Simon Pilgrim78f86302017-01-24 11:07:41 +0000559 if (isa<UndefValue>(Arg0) || isa<UndefValue>(Arg1))
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000560 return ConstantAggregateZero::get(ResTy);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000561
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000562 // Constant folding.
563 // PMULDQ = (mul(vXi64 sext(shuffle<0,2,..>(Arg0)),
564 // vXi64 sext(shuffle<0,2,..>(Arg1))))
565 // PMULUDQ = (mul(vXi64 zext(shuffle<0,2,..>(Arg0)),
566 // vXi64 zext(shuffle<0,2,..>(Arg1))))
567 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
568 return nullptr;
569
570 unsigned NumElts = ResTy->getVectorNumElements();
571 assert(Arg0->getType()->getVectorNumElements() == (2 * NumElts) &&
572 Arg1->getType()->getVectorNumElements() == (2 * NumElts) &&
573 "Unexpected muldq/muludq types");
574
575 unsigned IntrinsicID = II.getIntrinsicID();
576 bool IsSigned = (Intrinsic::x86_sse41_pmuldq == IntrinsicID ||
577 Intrinsic::x86_avx2_pmul_dq == IntrinsicID ||
578 Intrinsic::x86_avx512_pmul_dq_512 == IntrinsicID);
579
580 SmallVector<unsigned, 16> ShuffleMask;
581 for (unsigned i = 0; i != NumElts; ++i)
582 ShuffleMask.push_back(i * 2);
583
584 auto *LHS = Builder.CreateShuffleVector(Arg0, Arg0, ShuffleMask);
585 auto *RHS = Builder.CreateShuffleVector(Arg1, Arg1, ShuffleMask);
586
587 if (IsSigned) {
588 LHS = Builder.CreateSExt(LHS, ResTy);
589 RHS = Builder.CreateSExt(RHS, ResTy);
590 } else {
591 LHS = Builder.CreateZExt(LHS, ResTy);
592 RHS = Builder.CreateZExt(RHS, ResTy);
593 }
594
595 return Builder.CreateMul(LHS, RHS);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000596}
597
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000598static Value *simplifyX86pack(IntrinsicInst &II, InstCombiner &IC,
599 InstCombiner::BuilderTy &Builder, bool IsSigned) {
600 Value *Arg0 = II.getArgOperand(0);
601 Value *Arg1 = II.getArgOperand(1);
602 Type *ResTy = II.getType();
603
604 // Fast all undef handling.
605 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
606 return UndefValue::get(ResTy);
607
608 Type *ArgTy = Arg0->getType();
609 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
610 unsigned NumDstElts = ResTy->getVectorNumElements();
611 unsigned NumSrcElts = ArgTy->getVectorNumElements();
612 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
613
614 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
615 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
616 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
617 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
618 "Unexpected packing types");
619
620 // Constant folding.
621 auto *Cst0 = dyn_cast<Constant>(Arg0);
622 auto *Cst1 = dyn_cast<Constant>(Arg1);
623 if (!Cst0 || !Cst1)
624 return nullptr;
625
626 SmallVector<Constant *, 32> Vals;
627 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
628 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
629 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
630 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
631 auto *COp = Cst->getAggregateElement(SrcIdx);
632 if (COp && isa<UndefValue>(COp)) {
633 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
634 continue;
635 }
636
637 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
638 if (!CInt)
639 return nullptr;
640
641 APInt Val = CInt->getValue();
642 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
643 "Unexpected constant bitwidth");
644
645 if (IsSigned) {
646 // PACKSS: Truncate signed value with signed saturation.
647 // Source values less than dst minint are saturated to minint.
648 // Source values greater than dst maxint are saturated to maxint.
649 if (Val.isSignedIntN(DstScalarSizeInBits))
650 Val = Val.trunc(DstScalarSizeInBits);
651 else if (Val.isNegative())
652 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
653 else
654 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
655 } else {
656 // PACKUS: Truncate signed value with unsigned saturation.
657 // Source values less than zero are saturated to zero.
658 // Source values greater than dst maxuint are saturated to maxuint.
659 if (Val.isIntN(DstScalarSizeInBits))
660 Val = Val.trunc(DstScalarSizeInBits);
661 else if (Val.isNegative())
662 Val = APInt::getNullValue(DstScalarSizeInBits);
663 else
664 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
665 }
666
667 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
668 }
669 }
670
671 return ConstantVector::get(Vals);
672}
673
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000674static Value *simplifyX86movmsk(const IntrinsicInst &II,
675 InstCombiner::BuilderTy &Builder) {
676 Value *Arg = II.getArgOperand(0);
677 Type *ResTy = II.getType();
678 Type *ArgTy = Arg->getType();
679
680 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
681 if (isa<UndefValue>(Arg))
682 return Constant::getNullValue(ResTy);
683
684 // We can't easily peek through x86_mmx types.
685 if (!ArgTy->isVectorTy())
686 return nullptr;
687
688 auto *C = dyn_cast<Constant>(Arg);
689 if (!C)
690 return nullptr;
691
692 // Extract signbits of the vector input and pack into integer result.
693 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
694 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
695 auto *COp = C->getAggregateElement(I);
696 if (!COp)
697 return nullptr;
698 if (isa<UndefValue>(COp))
699 continue;
700
701 auto *CInt = dyn_cast<ConstantInt>(COp);
702 auto *CFp = dyn_cast<ConstantFP>(COp);
703 if (!CInt && !CFp)
704 return nullptr;
705
706 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
707 Result.setBit(I);
708 }
709
710 return Constant::getIntegerValue(ResTy, Result);
711}
712
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000713static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000714 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000715 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
716 if (!CInt)
717 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000718
Sanjay Patel03c03f52016-01-28 00:03:16 +0000719 VectorType *VecTy = cast<VectorType>(II.getType());
720 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000721
Sanjay Patel03c03f52016-01-28 00:03:16 +0000722 // The immediate permute control byte looks like this:
723 // [3:0] - zero mask for each 32-bit lane
724 // [5:4] - select one 32-bit destination lane
725 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000726
Sanjay Patel03c03f52016-01-28 00:03:16 +0000727 uint8_t Imm = CInt->getZExtValue();
728 uint8_t ZMask = Imm & 0xf;
729 uint8_t DestLane = (Imm >> 4) & 0x3;
730 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000731
Sanjay Patel03c03f52016-01-28 00:03:16 +0000732 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000733
Sanjay Patel03c03f52016-01-28 00:03:16 +0000734 // If all zero mask bits are set, this was just a weird way to
735 // generate a zero vector.
736 if (ZMask == 0xf)
737 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000738
Sanjay Patel03c03f52016-01-28 00:03:16 +0000739 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000740 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000741
Sanjay Patel03c03f52016-01-28 00:03:16 +0000742 // We may replace the second operand with the zero vector.
743 Value *V1 = II.getArgOperand(1);
744
745 if (ZMask) {
746 // If the zero mask is being used with a single input or the zero mask
747 // overrides the destination lane, this is a shuffle with the zero vector.
748 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
749 (ZMask & (1 << DestLane))) {
750 V1 = ZeroVector;
751 // We may still move 32-bits of the first source vector from one lane
752 // to another.
753 ShuffleMask[DestLane] = SourceLane;
754 // The zero mask may override the previous insert operation.
755 for (unsigned i = 0; i < 4; ++i)
756 if ((ZMask >> i) & 0x1)
757 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000758 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000759 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
760 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000761 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000762 } else {
763 // Replace the selected destination lane with the selected source lane.
764 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000765 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000766
767 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000768}
769
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000770/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
771/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000772static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000773 ConstantInt *CILength, ConstantInt *CIIndex,
774 InstCombiner::BuilderTy &Builder) {
775 auto LowConstantHighUndef = [&](uint64_t Val) {
776 Type *IntTy64 = Type::getInt64Ty(II.getContext());
777 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
778 UndefValue::get(IntTy64)};
779 return ConstantVector::get(Args);
780 };
781
782 // See if we're dealing with constant values.
783 Constant *C0 = dyn_cast<Constant>(Op0);
784 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000785 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000786 : nullptr;
787
788 // Attempt to constant fold.
789 if (CILength && CIIndex) {
790 // From AMD documentation: "The bit index and field length are each six
791 // bits in length other bits of the field are ignored."
792 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
793 APInt APLength = CILength->getValue().zextOrTrunc(6);
794
795 unsigned Index = APIndex.getZExtValue();
796
797 // From AMD documentation: "a value of zero in the field length is
798 // defined as length of 64".
799 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
800
801 // From AMD documentation: "If the sum of the bit index + length field
802 // is greater than 64, the results are undefined".
803 unsigned End = Index + Length;
804
805 // Note that both field index and field length are 8-bit quantities.
806 // Since variables 'Index' and 'Length' are unsigned values
807 // obtained from zero-extending field index and field length
808 // respectively, their sum should never wrap around.
809 if (End > 64)
810 return UndefValue::get(II.getType());
811
812 // If we are inserting whole bytes, we can convert this to a shuffle.
813 // Lowering can recognize EXTRQI shuffle masks.
814 if ((Length % 8) == 0 && (Index % 8) == 0) {
815 // Convert bit indices to byte indices.
816 Length /= 8;
817 Index /= 8;
818
819 Type *IntTy8 = Type::getInt8Ty(II.getContext());
820 Type *IntTy32 = Type::getInt32Ty(II.getContext());
821 VectorType *ShufTy = VectorType::get(IntTy8, 16);
822
823 SmallVector<Constant *, 16> ShuffleMask;
824 for (int i = 0; i != (int)Length; ++i)
825 ShuffleMask.push_back(
826 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
827 for (int i = Length; i != 8; ++i)
828 ShuffleMask.push_back(
829 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
830 for (int i = 8; i != 16; ++i)
831 ShuffleMask.push_back(UndefValue::get(IntTy32));
832
833 Value *SV = Builder.CreateShuffleVector(
834 Builder.CreateBitCast(Op0, ShufTy),
835 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
836 return Builder.CreateBitCast(SV, II.getType());
837 }
838
839 // Constant Fold - shift Index'th bit to lowest position and mask off
840 // Length bits.
841 if (CI0) {
842 APInt Elt = CI0->getValue();
Craig Topperfc947bc2017-04-18 17:14:21 +0000843 Elt.lshrInPlace(Index);
844 Elt = Elt.zextOrTrunc(Length);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000845 return LowConstantHighUndef(Elt.getZExtValue());
846 }
847
848 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
849 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
850 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000851 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000852 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
853 return Builder.CreateCall(F, Args);
854 }
855 }
856
857 // Constant Fold - extraction from zero is always {zero, undef}.
858 if (CI0 && CI0->equalsInt(0))
859 return LowConstantHighUndef(0);
860
861 return nullptr;
862}
863
864/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
865/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000866static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000867 APInt APLength, APInt APIndex,
868 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000869 // From AMD documentation: "The bit index and field length are each six bits
870 // in length other bits of the field are ignored."
871 APIndex = APIndex.zextOrTrunc(6);
872 APLength = APLength.zextOrTrunc(6);
873
874 // Attempt to constant fold.
875 unsigned Index = APIndex.getZExtValue();
876
877 // From AMD documentation: "a value of zero in the field length is
878 // defined as length of 64".
879 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
880
881 // From AMD documentation: "If the sum of the bit index + length field
882 // is greater than 64, the results are undefined".
883 unsigned End = Index + Length;
884
885 // Note that both field index and field length are 8-bit quantities.
886 // Since variables 'Index' and 'Length' are unsigned values
887 // obtained from zero-extending field index and field length
888 // respectively, their sum should never wrap around.
889 if (End > 64)
890 return UndefValue::get(II.getType());
891
892 // If we are inserting whole bytes, we can convert this to a shuffle.
893 // Lowering can recognize INSERTQI shuffle masks.
894 if ((Length % 8) == 0 && (Index % 8) == 0) {
895 // Convert bit indices to byte indices.
896 Length /= 8;
897 Index /= 8;
898
899 Type *IntTy8 = Type::getInt8Ty(II.getContext());
900 Type *IntTy32 = Type::getInt32Ty(II.getContext());
901 VectorType *ShufTy = VectorType::get(IntTy8, 16);
902
903 SmallVector<Constant *, 16> ShuffleMask;
904 for (int i = 0; i != (int)Index; ++i)
905 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
906 for (int i = 0; i != (int)Length; ++i)
907 ShuffleMask.push_back(
908 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
909 for (int i = Index + Length; i != 8; ++i)
910 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
911 for (int i = 8; i != 16; ++i)
912 ShuffleMask.push_back(UndefValue::get(IntTy32));
913
914 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
915 Builder.CreateBitCast(Op1, ShufTy),
916 ConstantVector::get(ShuffleMask));
917 return Builder.CreateBitCast(SV, II.getType());
918 }
919
920 // See if we're dealing with constant values.
921 Constant *C0 = dyn_cast<Constant>(Op0);
922 Constant *C1 = dyn_cast<Constant>(Op1);
923 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000924 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000925 : nullptr;
926 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000927 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000928 : nullptr;
929
930 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
931 if (CI00 && CI10) {
932 APInt V00 = CI00->getValue();
933 APInt V10 = CI10->getValue();
934 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
935 V00 = V00 & ~Mask;
936 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
937 APInt Val = V00 | V10;
938 Type *IntTy64 = Type::getInt64Ty(II.getContext());
939 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
940 UndefValue::get(IntTy64)};
941 return ConstantVector::get(Args);
942 }
943
944 // If we were an INSERTQ call, we'll save demanded elements if we convert to
945 // INSERTQI.
946 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
947 Type *IntTy8 = Type::getInt8Ty(II.getContext());
948 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
949 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
950
951 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000952 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000953 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
954 return Builder.CreateCall(F, Args);
955 }
956
957 return nullptr;
958}
959
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000960/// Attempt to convert pshufb* to shufflevector if the mask is constant.
961static Value *simplifyX86pshufb(const IntrinsicInst &II,
962 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000963 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
964 if (!V)
965 return nullptr;
966
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000967 auto *VecTy = cast<VectorType>(II.getType());
968 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
969 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +0000970 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000971 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000972
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000973 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +0000974 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000975
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000976 // Each byte in the shuffle control mask forms an index to permute the
977 // corresponding byte in the destination operand.
978 for (unsigned I = 0; I < NumElts; ++I) {
979 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000980 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000981 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +0000982
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000983 if (isa<UndefValue>(COp)) {
984 Indexes[I] = UndefValue::get(MaskEltTy);
985 continue;
986 }
987
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000988 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
989
990 // If the most significant bit (bit[7]) of each byte of the shuffle
991 // control mask is set, then zero is written in the result byte.
992 // The zero vector is in the right-hand side of the resulting
993 // shufflevector.
994
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +0000995 // The value of each index for the high 128-bit lane is the least
996 // significant 4 bits of the respective shuffle control byte.
997 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
998 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +0000999 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001000
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001001 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001002 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001003 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001004 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1005}
1006
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001007/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1008static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1009 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001010 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1011 if (!V)
1012 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001013
Craig Topper58917f32016-12-11 01:59:36 +00001014 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001015 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001016 unsigned NumElts = VecTy->getVectorNumElements();
1017 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1018 unsigned NumLaneElts = IsPD ? 2 : 4;
1019 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001020
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001021 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001022 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001023
1024 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001025 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001026 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001027 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001028 return nullptr;
1029
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001030 if (isa<UndefValue>(COp)) {
1031 Indexes[I] = UndefValue::get(MaskEltTy);
1032 continue;
1033 }
1034
1035 APInt Index = cast<ConstantInt>(COp)->getValue();
1036 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001037
1038 // The PD variants uses bit 1 to select per-lane element index, so
1039 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001040 if (IsPD)
Craig Topperfc947bc2017-04-18 17:14:21 +00001041 Index.lshrInPlace(1);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001042
1043 // The _256 variants are a bit trickier since the mask bits always index
1044 // into the corresponding 128 half. In order to convert to a generic
1045 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001046 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001047
1048 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001049 }
1050
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001051 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001052 auto V1 = II.getArgOperand(0);
1053 auto V2 = UndefValue::get(V1->getType());
1054 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1055}
1056
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001057/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1058static Value *simplifyX86vpermv(const IntrinsicInst &II,
1059 InstCombiner::BuilderTy &Builder) {
1060 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1061 if (!V)
1062 return nullptr;
1063
Simon Pilgrimca140b12016-05-01 20:43:02 +00001064 auto *VecTy = cast<VectorType>(II.getType());
1065 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001066 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001067 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1068 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001069
Simon Pilgrimca140b12016-05-01 20:43:02 +00001070 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001071 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001072
1073 for (unsigned I = 0; I < Size; ++I) {
1074 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001075 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001076 return nullptr;
1077
Simon Pilgrimca140b12016-05-01 20:43:02 +00001078 if (isa<UndefValue>(COp)) {
1079 Indexes[I] = UndefValue::get(MaskEltTy);
1080 continue;
1081 }
1082
Craig Toppere3280452016-12-25 23:58:57 +00001083 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1084 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001085 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001086 }
1087
Simon Pilgrimca140b12016-05-01 20:43:02 +00001088 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001089 auto V1 = II.getArgOperand(0);
1090 auto V2 = UndefValue::get(VecTy);
1091 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1092}
1093
Sanjay Patelccf5f242015-03-20 21:47:56 +00001094/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
1095/// source vectors, unless a zero bit is set. If a zero bit is set,
1096/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001097static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +00001098 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +00001099 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
1100 if (!CInt)
1101 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001102
Sanjay Patel03c03f52016-01-28 00:03:16 +00001103 VectorType *VecTy = cast<VectorType>(II.getType());
1104 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001105
Sanjay Patel03c03f52016-01-28 00:03:16 +00001106 // The immediate permute control byte looks like this:
1107 // [1:0] - select 128 bits from sources for low half of destination
1108 // [2] - ignore
1109 // [3] - zero low half of destination
1110 // [5:4] - select 128 bits from sources for high half of destination
1111 // [6] - ignore
1112 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001113
Sanjay Patel03c03f52016-01-28 00:03:16 +00001114 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001115
Sanjay Patel03c03f52016-01-28 00:03:16 +00001116 bool LowHalfZero = Imm & 0x08;
1117 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001118
Sanjay Patel03c03f52016-01-28 00:03:16 +00001119 // If both zero mask bits are set, this was just a weird way to
1120 // generate a zero vector.
1121 if (LowHalfZero && HighHalfZero)
1122 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001123
Sanjay Patel03c03f52016-01-28 00:03:16 +00001124 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
1125 unsigned NumElts = VecTy->getNumElements();
1126 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +00001127 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001128
Sanjay Patel03c03f52016-01-28 00:03:16 +00001129 // The high bit of the selection field chooses the 1st or 2nd operand.
1130 bool LowInputSelect = Imm & 0x02;
1131 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001132
Sanjay Patel03c03f52016-01-28 00:03:16 +00001133 // The low bit of the selection field chooses the low or high half
1134 // of the selected operand.
1135 bool LowHalfSelect = Imm & 0x01;
1136 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001137
Sanjay Patel03c03f52016-01-28 00:03:16 +00001138 // Determine which operand(s) are actually in use for this instruction.
1139 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
1140 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001141
Sanjay Patel03c03f52016-01-28 00:03:16 +00001142 // If needed, replace operands based on zero mask.
1143 V0 = LowHalfZero ? ZeroVector : V0;
1144 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001145
Sanjay Patel03c03f52016-01-28 00:03:16 +00001146 // Permute low half of result.
1147 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
1148 for (unsigned i = 0; i < HalfSize; ++i)
1149 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001150
Sanjay Patel03c03f52016-01-28 00:03:16 +00001151 // Permute high half of result.
1152 StartIndex = HighHalfSelect ? HalfSize : 0;
1153 StartIndex += NumElts;
1154 for (unsigned i = 0; i < HalfSize; ++i)
1155 ShuffleMask[i + HalfSize] = StartIndex + i;
1156
1157 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +00001158}
1159
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001160/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001161static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001162 InstCombiner::BuilderTy &Builder,
1163 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001164 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1165 uint64_t Imm = CInt->getZExtValue() & 0x7;
1166 VectorType *VecTy = cast<VectorType>(II.getType());
1167 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1168
1169 switch (Imm) {
1170 case 0x0:
1171 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1172 break;
1173 case 0x1:
1174 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1175 break;
1176 case 0x2:
1177 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1178 break;
1179 case 0x3:
1180 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1181 break;
1182 case 0x4:
1183 Pred = ICmpInst::ICMP_EQ; break;
1184 case 0x5:
1185 Pred = ICmpInst::ICMP_NE; break;
1186 case 0x6:
1187 return ConstantInt::getSigned(VecTy, 0); // FALSE
1188 case 0x7:
1189 return ConstantInt::getSigned(VecTy, -1); // TRUE
1190 }
1191
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001192 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1193 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001194 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1195 }
1196 return nullptr;
1197}
1198
Craig Toppere3280452016-12-25 23:58:57 +00001199// Emit a select instruction and appropriate bitcasts to help simplify
1200// masked intrinsics.
1201static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1202 InstCombiner::BuilderTy &Builder) {
Craig Topper99163632016-12-30 23:06:28 +00001203 unsigned VWidth = Op0->getType()->getVectorNumElements();
1204
1205 // If the mask is all ones we don't need the select. But we need to check
1206 // only the bit thats will be used in case VWidth is less than 8.
1207 if (auto *C = dyn_cast<ConstantInt>(Mask))
1208 if (C->getValue().zextOrTrunc(VWidth).isAllOnesValue())
1209 return Op0;
1210
Craig Toppere3280452016-12-25 23:58:57 +00001211 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1212 cast<IntegerType>(Mask->getType())->getBitWidth());
1213 Mask = Builder.CreateBitCast(Mask, MaskTy);
1214
1215 // If we have less than 8 elements, then the starting mask was an i8 and
1216 // we need to extract down to the right number of elements.
Craig Toppere3280452016-12-25 23:58:57 +00001217 if (VWidth < 8) {
1218 uint32_t Indices[4];
1219 for (unsigned i = 0; i != VWidth; ++i)
1220 Indices[i] = i;
1221 Mask = Builder.CreateShuffleVector(Mask, Mask,
1222 makeArrayRef(Indices, VWidth),
1223 "extract");
1224 }
1225
1226 return Builder.CreateSelect(Mask, Op0, Op1);
1227}
1228
Sanjay Patel0069f562016-01-31 16:35:23 +00001229static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1230 Value *Arg0 = II.getArgOperand(0);
1231 Value *Arg1 = II.getArgOperand(1);
1232
1233 // fmin(x, x) -> x
1234 if (Arg0 == Arg1)
1235 return Arg0;
1236
1237 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1238
1239 // fmin(x, nan) -> x
1240 if (C1 && C1->isNaN())
1241 return Arg0;
1242
1243 // This is the value because if undef were NaN, we would return the other
1244 // value and cannot return a NaN unless both operands are.
1245 //
1246 // fmin(undef, x) -> x
1247 if (isa<UndefValue>(Arg0))
1248 return Arg1;
1249
1250 // fmin(x, undef) -> x
1251 if (isa<UndefValue>(Arg1))
1252 return Arg0;
1253
1254 Value *X = nullptr;
1255 Value *Y = nullptr;
1256 if (II.getIntrinsicID() == Intrinsic::minnum) {
1257 // fmin(x, fmin(x, y)) -> fmin(x, y)
1258 // fmin(y, fmin(x, y)) -> fmin(x, y)
1259 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1260 if (Arg0 == X || Arg0 == Y)
1261 return Arg1;
1262 }
1263
1264 // fmin(fmin(x, y), x) -> fmin(x, y)
1265 // fmin(fmin(x, y), y) -> fmin(x, y)
1266 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1267 if (Arg1 == X || Arg1 == Y)
1268 return Arg0;
1269 }
1270
1271 // TODO: fmin(nnan x, inf) -> x
1272 // TODO: fmin(nnan ninf x, flt_max) -> x
1273 if (C1 && C1->isInfinity()) {
1274 // fmin(x, -inf) -> -inf
1275 if (C1->isNegative())
1276 return Arg1;
1277 }
1278 } else {
1279 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1280 // fmax(x, fmax(x, y)) -> fmax(x, y)
1281 // fmax(y, fmax(x, y)) -> fmax(x, y)
1282 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1283 if (Arg0 == X || Arg0 == Y)
1284 return Arg1;
1285 }
1286
1287 // fmax(fmax(x, y), x) -> fmax(x, y)
1288 // fmax(fmax(x, y), y) -> fmax(x, y)
1289 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1290 if (Arg1 == X || Arg1 == Y)
1291 return Arg0;
1292 }
1293
1294 // TODO: fmax(nnan x, -inf) -> x
1295 // TODO: fmax(nnan ninf x, -flt_max) -> x
1296 if (C1 && C1->isInfinity()) {
1297 // fmax(x, inf) -> inf
1298 if (!C1->isNegative())
1299 return Arg1;
1300 }
1301 }
1302 return nullptr;
1303}
1304
David Majnemer666aa942016-07-14 06:58:42 +00001305static bool maskIsAllOneOrUndef(Value *Mask) {
1306 auto *ConstMask = dyn_cast<Constant>(Mask);
1307 if (!ConstMask)
1308 return false;
1309 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1310 return true;
1311 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1312 ++I) {
1313 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1314 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1315 continue;
1316 return false;
1317 }
1318 return true;
1319}
1320
Sanjay Patelb695c552016-02-01 17:00:10 +00001321static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1322 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001323 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1324 // argument.
1325 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001326 Value *LoadPtr = II.getArgOperand(0);
1327 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1328 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1329 }
1330
1331 return nullptr;
1332}
1333
Sanjay Patel04f792b2016-02-01 19:39:52 +00001334static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1335 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1336 if (!ConstMask)
1337 return nullptr;
1338
1339 // If the mask is all zeros, this instruction does nothing.
1340 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001341 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001342
1343 // If the mask is all ones, this is a plain vector store of the 1st argument.
1344 if (ConstMask->isAllOnesValue()) {
1345 Value *StorePtr = II.getArgOperand(1);
1346 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1347 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1348 }
1349
1350 return nullptr;
1351}
1352
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001353static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1354 // If the mask is all zeros, return the "passthru" argument of the gather.
1355 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1356 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001357 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001358
1359 return nullptr;
1360}
1361
1362static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1363 // If the mask is all zeros, a scatter does nothing.
1364 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1365 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001366 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001367
1368 return nullptr;
1369}
1370
Amaury Sechet763c59d2016-08-18 20:43:50 +00001371static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1372 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1373 II.getIntrinsicID() == Intrinsic::ctlz) &&
1374 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001375 Value *Op0 = II.getArgOperand(0);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001376
Craig Topper8205a1a2017-05-24 16:53:07 +00001377 KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001378
1379 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1380 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
Craig Topper8df66c62017-05-12 17:20:30 +00001381 unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1382 : Known.countMaxLeadingZeros();
1383 unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1384 : Known.countMinLeadingZeros();
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001385
1386 // If all bits above (ctlz) or below (cttz) the first known one are known
1387 // zero, this value is constant.
1388 // FIXME: This should be in InstSimplify because we're replacing an
1389 // instruction with a constant.
Craig Topper9474e9b2017-04-27 04:51:25 +00001390 if (PossibleZeros == DefiniteZeros) {
Craig Topper0799ff92017-06-03 18:50:32 +00001391 auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
Amaury Sechet763c59d2016-08-18 20:43:50 +00001392 return IC.replaceInstUsesWith(II, C);
1393 }
1394
1395 // If the input to cttz/ctlz is known to be non-zero,
1396 // then change the 'ZeroIsUndef' parameter to 'true'
1397 // because we know the zero behavior can't affect the result.
Craig Topperd45185f2017-05-26 18:23:57 +00001398 if (Known.One != 0 ||
1399 isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1400 &IC.getDominatorTree())) {
Amaury Sechet763c59d2016-08-18 20:43:50 +00001401 if (!match(II.getArgOperand(1), m_One())) {
1402 II.setOperand(1, IC.Builder->getTrue());
1403 return &II;
1404 }
1405 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001406
1407 return nullptr;
1408}
1409
Sanjay Patel1ace9932016-02-26 21:04:14 +00001410// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1411// XMM register mask efficiently, we could transform all x86 masked intrinsics
1412// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001413static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1414 Value *Ptr = II.getOperand(0);
1415 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001416 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001417
1418 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001419 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001420 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001421 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001422
1423 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1424 if (!ConstMask)
1425 return nullptr;
1426
1427 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1428 // to allow target-independent optimizations.
1429
1430 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1431 // the LLVM intrinsic definition for the pointer argument.
1432 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1433 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1434 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1435
1436 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1437 // on each element's most significant bit (the sign bit).
1438 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1439
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001440 // The pass-through vector for an x86 masked load is a zero vector.
1441 CallInst *NewMaskedLoad =
1442 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001443 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1444}
1445
1446// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1447// XMM register mask efficiently, we could transform all x86 masked intrinsics
1448// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001449static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1450 Value *Ptr = II.getOperand(0);
1451 Value *Mask = II.getOperand(1);
1452 Value *Vec = II.getOperand(2);
1453
1454 // Special case a zero mask since that's not a ConstantDataVector:
1455 // this masked store instruction does nothing.
1456 if (isa<ConstantAggregateZero>(Mask)) {
1457 IC.eraseInstFromFunction(II);
1458 return true;
1459 }
1460
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001461 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1462 // anything else at this level.
1463 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1464 return false;
1465
Sanjay Patel1ace9932016-02-26 21:04:14 +00001466 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1467 if (!ConstMask)
1468 return false;
1469
1470 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1471 // to allow target-independent optimizations.
1472
1473 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1474 // the LLVM intrinsic definition for the pointer argument.
1475 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1476 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001477 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1478
1479 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1480 // on each element's most significant bit (the sign bit).
1481 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1482
1483 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1484
1485 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1486 IC.eraseInstFromFunction(II);
1487 return true;
1488}
1489
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00001490// Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1491//
1492// A single NaN input is folded to minnum, so we rely on that folding for
1493// handling NaNs.
1494static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1495 const APFloat &Src2) {
1496 APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1497
1498 APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1499 assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1500 if (Cmp0 == APFloat::cmpEqual)
1501 return maxnum(Src1, Src2);
1502
1503 APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1504 assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1505 if (Cmp1 == APFloat::cmpEqual)
1506 return maxnum(Src0, Src2);
1507
1508 return maxnum(Src0, Src1);
1509}
1510
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001511// Returns true iff the 2 intrinsics have the same operands, limiting the
1512// comparison to the first NumOperands.
1513static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1514 unsigned NumOperands) {
1515 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1516 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1517 for (unsigned i = 0; i < NumOperands; i++)
1518 if (I.getArgOperand(i) != E.getArgOperand(i))
1519 return false;
1520 return true;
1521}
1522
1523// Remove trivially empty start/end intrinsic ranges, i.e. a start
1524// immediately followed by an end (ignoring debuginfo or other
1525// start/end intrinsics in between). As this handles only the most trivial
1526// cases, tracking the nesting level is not needed:
1527//
1528// call @llvm.foo.start(i1 0) ; &I
1529// call @llvm.foo.start(i1 0)
1530// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1531// call @llvm.foo.end(i1 0)
1532static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1533 unsigned EndID, InstCombiner &IC) {
1534 assert(I.getIntrinsicID() == StartID &&
1535 "Start intrinsic does not have expected ID");
1536 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1537 for (++BI; BI != BE; ++BI) {
1538 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1539 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1540 continue;
1541 if (E->getIntrinsicID() == EndID &&
1542 haveSameOperands(I, *E, E->getNumArgOperands())) {
1543 IC.eraseInstFromFunction(*E);
1544 IC.eraseInstFromFunction(I);
1545 return true;
1546 }
1547 }
1548 break;
1549 }
1550
1551 return false;
1552}
1553
Justin Lebar698c31b2017-01-27 00:58:58 +00001554// Convert NVVM intrinsics to target-generic LLVM code where possible.
1555static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1556 // Each NVVM intrinsic we can simplify can be replaced with one of:
1557 //
1558 // * an LLVM intrinsic,
1559 // * an LLVM cast operation,
1560 // * an LLVM binary operation, or
1561 // * ad-hoc LLVM IR for the particular operation.
1562
1563 // Some transformations are only valid when the module's
1564 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1565 // transformations are valid regardless of the module's ftz setting.
1566 enum FtzRequirementTy {
1567 FTZ_Any, // Any ftz setting is ok.
1568 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1569 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1570 };
1571 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1572 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1573 // simplify.
1574 enum SpecialCase {
1575 SPC_Reciprocal,
1576 };
1577
1578 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1579 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1580 struct SimplifyAction {
1581 // Invariant: At most one of these Optionals has a value.
1582 Optional<Intrinsic::ID> IID;
1583 Optional<Instruction::CastOps> CastOp;
1584 Optional<Instruction::BinaryOps> BinaryOp;
1585 Optional<SpecialCase> Special;
1586
1587 FtzRequirementTy FtzRequirement = FTZ_Any;
1588
1589 SimplifyAction() = default;
1590
1591 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1592 : IID(IID), FtzRequirement(FtzReq) {}
1593
1594 // Cast operations don't have anything to do with FTZ, so we skip that
1595 // argument.
1596 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1597
1598 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1599 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1600
1601 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1602 : Special(Special), FtzRequirement(FtzReq) {}
1603 };
1604
1605 // Try to generate a SimplifyAction describing how to replace our
1606 // IntrinsicInstr with target-generic LLVM IR.
1607 const SimplifyAction Action = [II]() -> SimplifyAction {
1608 switch (II->getIntrinsicID()) {
1609
1610 // NVVM intrinsics that map directly to LLVM intrinsics.
1611 case Intrinsic::nvvm_ceil_d:
1612 return {Intrinsic::ceil, FTZ_Any};
1613 case Intrinsic::nvvm_ceil_f:
1614 return {Intrinsic::ceil, FTZ_MustBeOff};
1615 case Intrinsic::nvvm_ceil_ftz_f:
1616 return {Intrinsic::ceil, FTZ_MustBeOn};
1617 case Intrinsic::nvvm_fabs_d:
1618 return {Intrinsic::fabs, FTZ_Any};
1619 case Intrinsic::nvvm_fabs_f:
1620 return {Intrinsic::fabs, FTZ_MustBeOff};
1621 case Intrinsic::nvvm_fabs_ftz_f:
1622 return {Intrinsic::fabs, FTZ_MustBeOn};
1623 case Intrinsic::nvvm_floor_d:
1624 return {Intrinsic::floor, FTZ_Any};
1625 case Intrinsic::nvvm_floor_f:
1626 return {Intrinsic::floor, FTZ_MustBeOff};
1627 case Intrinsic::nvvm_floor_ftz_f:
1628 return {Intrinsic::floor, FTZ_MustBeOn};
1629 case Intrinsic::nvvm_fma_rn_d:
1630 return {Intrinsic::fma, FTZ_Any};
1631 case Intrinsic::nvvm_fma_rn_f:
1632 return {Intrinsic::fma, FTZ_MustBeOff};
1633 case Intrinsic::nvvm_fma_rn_ftz_f:
1634 return {Intrinsic::fma, FTZ_MustBeOn};
1635 case Intrinsic::nvvm_fmax_d:
1636 return {Intrinsic::maxnum, FTZ_Any};
1637 case Intrinsic::nvvm_fmax_f:
1638 return {Intrinsic::maxnum, FTZ_MustBeOff};
1639 case Intrinsic::nvvm_fmax_ftz_f:
1640 return {Intrinsic::maxnum, FTZ_MustBeOn};
1641 case Intrinsic::nvvm_fmin_d:
1642 return {Intrinsic::minnum, FTZ_Any};
1643 case Intrinsic::nvvm_fmin_f:
1644 return {Intrinsic::minnum, FTZ_MustBeOff};
1645 case Intrinsic::nvvm_fmin_ftz_f:
1646 return {Intrinsic::minnum, FTZ_MustBeOn};
1647 case Intrinsic::nvvm_round_d:
1648 return {Intrinsic::round, FTZ_Any};
1649 case Intrinsic::nvvm_round_f:
1650 return {Intrinsic::round, FTZ_MustBeOff};
1651 case Intrinsic::nvvm_round_ftz_f:
1652 return {Intrinsic::round, FTZ_MustBeOn};
1653 case Intrinsic::nvvm_sqrt_rn_d:
1654 return {Intrinsic::sqrt, FTZ_Any};
1655 case Intrinsic::nvvm_sqrt_f:
1656 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1657 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1658 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1659 // the versions with explicit ftz-ness.
1660 return {Intrinsic::sqrt, FTZ_Any};
1661 case Intrinsic::nvvm_sqrt_rn_f:
1662 return {Intrinsic::sqrt, FTZ_MustBeOff};
1663 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1664 return {Intrinsic::sqrt, FTZ_MustBeOn};
1665 case Intrinsic::nvvm_trunc_d:
1666 return {Intrinsic::trunc, FTZ_Any};
1667 case Intrinsic::nvvm_trunc_f:
1668 return {Intrinsic::trunc, FTZ_MustBeOff};
1669 case Intrinsic::nvvm_trunc_ftz_f:
1670 return {Intrinsic::trunc, FTZ_MustBeOn};
1671
1672 // NVVM intrinsics that map to LLVM cast operations.
1673 //
1674 // Note that llvm's target-generic conversion operators correspond to the rz
1675 // (round to zero) versions of the nvvm conversion intrinsics, even though
1676 // most everything else here uses the rn (round to nearest even) nvvm ops.
1677 case Intrinsic::nvvm_d2i_rz:
1678 case Intrinsic::nvvm_f2i_rz:
1679 case Intrinsic::nvvm_d2ll_rz:
1680 case Intrinsic::nvvm_f2ll_rz:
1681 return {Instruction::FPToSI};
1682 case Intrinsic::nvvm_d2ui_rz:
1683 case Intrinsic::nvvm_f2ui_rz:
1684 case Intrinsic::nvvm_d2ull_rz:
1685 case Intrinsic::nvvm_f2ull_rz:
1686 return {Instruction::FPToUI};
1687 case Intrinsic::nvvm_i2d_rz:
1688 case Intrinsic::nvvm_i2f_rz:
1689 case Intrinsic::nvvm_ll2d_rz:
1690 case Intrinsic::nvvm_ll2f_rz:
1691 return {Instruction::SIToFP};
1692 case Intrinsic::nvvm_ui2d_rz:
1693 case Intrinsic::nvvm_ui2f_rz:
1694 case Intrinsic::nvvm_ull2d_rz:
1695 case Intrinsic::nvvm_ull2f_rz:
1696 return {Instruction::UIToFP};
1697
1698 // NVVM intrinsics that map to LLVM binary ops.
1699 case Intrinsic::nvvm_add_rn_d:
1700 return {Instruction::FAdd, FTZ_Any};
1701 case Intrinsic::nvvm_add_rn_f:
1702 return {Instruction::FAdd, FTZ_MustBeOff};
1703 case Intrinsic::nvvm_add_rn_ftz_f:
1704 return {Instruction::FAdd, FTZ_MustBeOn};
1705 case Intrinsic::nvvm_mul_rn_d:
1706 return {Instruction::FMul, FTZ_Any};
1707 case Intrinsic::nvvm_mul_rn_f:
1708 return {Instruction::FMul, FTZ_MustBeOff};
1709 case Intrinsic::nvvm_mul_rn_ftz_f:
1710 return {Instruction::FMul, FTZ_MustBeOn};
1711 case Intrinsic::nvvm_div_rn_d:
1712 return {Instruction::FDiv, FTZ_Any};
1713 case Intrinsic::nvvm_div_rn_f:
1714 return {Instruction::FDiv, FTZ_MustBeOff};
1715 case Intrinsic::nvvm_div_rn_ftz_f:
1716 return {Instruction::FDiv, FTZ_MustBeOn};
1717
1718 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1719 // need special handling.
1720 //
1721 // We seem to be mising intrinsics for rcp.approx.{ftz.}f32, which is just
1722 // as well.
1723 case Intrinsic::nvvm_rcp_rn_d:
1724 return {SPC_Reciprocal, FTZ_Any};
1725 case Intrinsic::nvvm_rcp_rn_f:
1726 return {SPC_Reciprocal, FTZ_MustBeOff};
1727 case Intrinsic::nvvm_rcp_rn_ftz_f:
1728 return {SPC_Reciprocal, FTZ_MustBeOn};
1729
1730 // We do not currently simplify intrinsics that give an approximate answer.
1731 // These include:
1732 //
1733 // - nvvm_cos_approx_{f,ftz_f}
1734 // - nvvm_ex2_approx_{d,f,ftz_f}
1735 // - nvvm_lg2_approx_{d,f,ftz_f}
1736 // - nvvm_sin_approx_{f,ftz_f}
1737 // - nvvm_sqrt_approx_{f,ftz_f}
1738 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1739 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1740 // - nvvm_rcp_approx_ftz_d
1741 //
1742 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1743 // means that fastmath is enabled in the intrinsic. Unfortunately only
1744 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1745 // information gets lost and we can't select on it.
1746 //
1747 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1748 // lower them to "fast fdiv".
1749
1750 default:
1751 return {};
1752 }
1753 }();
1754
1755 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1756 // can bail out now. (Notice that in the case that IID is not an NVVM
1757 // intrinsic, we don't have to look up any module metadata, as
1758 // FtzRequirementTy will be FTZ_Any.)
1759 if (Action.FtzRequirement != FTZ_Any) {
1760 bool FtzEnabled =
1761 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1762 "true";
1763
1764 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1765 return nullptr;
1766 }
1767
1768 // Simplify to target-generic intrinsic.
1769 if (Action.IID) {
1770 SmallVector<Value *, 4> Args(II->arg_operands());
1771 // All the target-generic intrinsics currently of interest to us have one
1772 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001773 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001774 return CallInst::Create(
1775 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1776 }
1777
1778 // Simplify to target-generic binary op.
1779 if (Action.BinaryOp)
1780 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1781 II->getArgOperand(1), II->getName());
1782
1783 // Simplify to target-generic cast op.
1784 if (Action.CastOp)
1785 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1786 II->getName());
1787
1788 // All that's left are the special cases.
1789 if (!Action.Special)
1790 return nullptr;
1791
1792 switch (*Action.Special) {
1793 case SPC_Reciprocal:
1794 // Simplify reciprocal.
1795 return BinaryOperator::Create(
1796 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1797 II->getArgOperand(0), II->getName());
1798 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001799 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001800}
1801
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001802Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1803 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1804 return nullptr;
1805}
1806
1807Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1808 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1809 return nullptr;
1810}
1811
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001812/// CallInst simplification. This mostly only handles folding of intrinsic
1813/// instructions. For normal calls, it allows visitCallSite to do the heavy
1814/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001815Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001816 auto Args = CI.arg_operands();
Daniel Berlin2c75c632017-04-26 20:56:07 +00001817 if (Value *V =
1818 SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), SQ))
Sanjay Patel4b198802016-02-01 22:23:39 +00001819 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001820
Justin Bogner99798402016-08-05 01:06:44 +00001821 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001822 return visitFree(CI);
1823
1824 // If the caller function is nounwind, mark the call as nounwind, even if the
1825 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001826 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001827 CI.setDoesNotThrow();
1828 return &CI;
1829 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001830
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001831 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1832 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001833
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001834 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1835 // visitCallSite.
1836 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1837 bool Changed = false;
1838
1839 // memmove/cpy/set of zero bytes is a noop.
1840 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001841 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001842 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001843
1844 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1845 if (CI->getZExtValue() == 1) {
1846 // Replace the instruction with just byte operations. We would
1847 // transform other cases to loads/stores, but we don't know if
1848 // alignment is sufficient.
1849 }
1850 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001851
Chris Lattnerc663a672010-10-01 05:51:02 +00001852 // No other transformations apply to volatile transfers.
1853 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001854 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001855
1856 // If we have a memmove and the source operation is a constant global,
1857 // then the source and dest pointers can't alias, so we can change this
1858 // into a call to memcpy.
1859 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1860 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1861 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001862 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001863 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001864 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1865 CI.getArgOperand(1)->getType(),
1866 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001867 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001868 Changed = true;
1869 }
1870 }
1871
1872 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1873 // memmove(x,x,size) -> noop.
1874 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001875 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001876 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001877
Eric Christopher7258dcd2010-04-16 23:37:20 +00001878 // If we can determine a pointer alignment that is bigger than currently
1879 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001880 if (isa<MemTransferInst>(MI)) {
1881 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001882 return I;
1883 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1884 if (Instruction *I = SimplifyMemSet(MSI))
1885 return I;
1886 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001887
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001888 if (Changed) return II;
1889 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001890
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001891 if (auto *AMI = dyn_cast<ElementAtomicMemCpyInst>(II)) {
1892 if (Constant *C = dyn_cast<Constant>(AMI->getNumElements()))
1893 if (C->isNullValue())
1894 return eraseInstFromFunction(*AMI);
Igor Laevsky900ffa32017-02-08 14:32:04 +00001895
1896 if (Instruction *I = SimplifyElementAtomicMemCpy(AMI))
1897 return I;
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001898 }
1899
Justin Lebar698c31b2017-01-27 00:58:58 +00001900 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1901 return I;
1902
Sanjay Patel1c600c62016-01-20 16:41:43 +00001903 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1904 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001905 APInt UndefElts(Width, 0);
1906 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1907 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1908 };
1909
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001910 switch (II->getIntrinsicID()) {
1911 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001912 case Intrinsic::objectsize:
1913 if (ConstantInt *N =
1914 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1915 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001916 return nullptr;
George Burgess IV3f089142016-12-20 23:46:36 +00001917
Michael Ilseman536cc322012-12-13 03:13:36 +00001918 case Intrinsic::bswap: {
1919 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001920 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001921
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001922 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001923 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001924 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001925
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001926 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001927 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1928 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1929 IIOperand->getType()->getPrimitiveSizeInBits();
1930 Value *CV = ConstantInt::get(X->getType(), C);
1931 Value *V = Builder->CreateLShr(X, CV);
1932 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001933 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001934 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001935 }
1936
James Molloy2d09c002015-11-12 12:39:41 +00001937 case Intrinsic::bitreverse: {
1938 Value *IIOperand = II->getArgOperand(0);
1939 Value *X = nullptr;
1940
1941 // bitreverse(bitreverse(x)) -> x
1942 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001943 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001944 break;
1945 }
1946
Sanjay Patelb695c552016-02-01 17:00:10 +00001947 case Intrinsic::masked_load:
1948 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001949 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001950 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001951 case Intrinsic::masked_store:
1952 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001953 case Intrinsic::masked_gather:
1954 return simplifyMaskedGather(*II, *this);
1955 case Intrinsic::masked_scatter:
1956 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001957
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001958 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001959 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001960 // powi(x, 0) -> 1.0
1961 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001962 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001963 // powi(x, 1) -> x
1964 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001965 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001966 // powi(x, -1) -> 1/x
1967 if (Power->isAllOnesValue())
1968 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001969 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001970 }
1971 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001972
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001973 case Intrinsic::cttz:
1974 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00001975 if (auto *I = foldCttzCtlz(*II, *this))
1976 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001977 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00001978
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001979 case Intrinsic::uadd_with_overflow:
1980 case Intrinsic::sadd_with_overflow:
1981 case Intrinsic::umul_with_overflow:
1982 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00001983 if (isa<Constant>(II->getArgOperand(0)) &&
1984 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001985 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00001986 Value *LHS = II->getArgOperand(0);
1987 II->setArgOperand(0, II->getArgOperand(1));
1988 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001989 return II;
1990 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00001991 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001992
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00001993 case Intrinsic::usub_with_overflow:
1994 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00001995 OverflowCheckFlavor OCF =
1996 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1997 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00001998
Sanjoy Dasb0984472015-04-08 04:27:22 +00001999 Value *OperationResult = nullptr;
2000 Constant *OverflowResult = nullptr;
2001 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
2002 *II, OperationResult, OverflowResult))
2003 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00002004
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002005 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002006 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002007
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002008 case Intrinsic::minnum:
2009 case Intrinsic::maxnum: {
2010 Value *Arg0 = II->getArgOperand(0);
2011 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00002012 // Canonicalize constants to the RHS.
2013 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002014 II->setArgOperand(0, Arg1);
2015 II->setArgOperand(1, Arg0);
2016 return II;
2017 }
Sanjay Patel0069f562016-01-31 16:35:23 +00002018 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00002019 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002020 break;
2021 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002022 case Intrinsic::fmuladd: {
Matt Arsenault92057602017-02-16 18:46:24 +00002023 // Canonicalize fast fmuladd to the separate fmul + fadd.
2024 if (II->hasUnsafeAlgebra()) {
2025 BuilderTy::FastMathFlagGuard Guard(*Builder);
2026 Builder->setFastMathFlags(II->getFastMathFlags());
2027 Value *Mul = Builder->CreateFMul(II->getArgOperand(0),
2028 II->getArgOperand(1));
2029 Value *Add = Builder->CreateFAdd(Mul, II->getArgOperand(2));
2030 Add->takeName(II);
2031 return replaceInstUsesWith(*II, Add);
2032 }
2033
2034 LLVM_FALLTHROUGH;
2035 }
2036 case Intrinsic::fma: {
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002037 Value *Src0 = II->getArgOperand(0);
2038 Value *Src1 = II->getArgOperand(1);
2039
Matt Arsenaultb264c942017-01-03 04:32:35 +00002040 // Canonicalize constants into the RHS.
2041 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2042 II->setArgOperand(0, Src1);
2043 II->setArgOperand(1, Src0);
2044 std::swap(Src0, Src1);
2045 }
2046
2047 Value *LHS = nullptr;
2048 Value *RHS = nullptr;
2049
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002050 // fma fneg(x), fneg(y), z -> fma x, y, z
2051 if (match(Src0, m_FNeg(m_Value(LHS))) &&
2052 match(Src1, m_FNeg(m_Value(RHS)))) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002053 II->setArgOperand(0, LHS);
2054 II->setArgOperand(1, RHS);
2055 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002056 }
2057
2058 // fma fabs(x), fabs(x), z -> fma x, x, z
2059 if (match(Src0, m_Intrinsic<Intrinsic::fabs>(m_Value(LHS))) &&
2060 match(Src1, m_Intrinsic<Intrinsic::fabs>(m_Value(RHS))) && LHS == RHS) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002061 II->setArgOperand(0, LHS);
2062 II->setArgOperand(1, RHS);
2063 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002064 }
2065
Matt Arsenaultb264c942017-01-03 04:32:35 +00002066 // fma x, 1, z -> fadd x, z
2067 if (match(Src1, m_FPOne())) {
2068 Instruction *RI = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2069 RI->copyFastMathFlags(II);
2070 return RI;
2071 }
2072
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002073 break;
2074 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002075 case Intrinsic::fabs: {
2076 Value *Cond;
2077 Constant *LHS, *RHS;
2078 if (match(II->getArgOperand(0),
2079 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
2080 CallInst *Call0 = Builder->CreateCall(II->getCalledFunction(), {LHS});
2081 CallInst *Call1 = Builder->CreateCall(II->getCalledFunction(), {RHS});
2082 return SelectInst::Create(Cond, Call0, Call1);
2083 }
2084
Matt Arsenault954a6242017-01-23 23:55:08 +00002085 LLVM_FALLTHROUGH;
2086 }
2087 case Intrinsic::ceil:
2088 case Intrinsic::floor:
2089 case Intrinsic::round:
2090 case Intrinsic::nearbyint:
Joerg Sonnenberger28bed102017-03-31 19:58:07 +00002091 case Intrinsic::rint:
Matt Arsenault954a6242017-01-23 23:55:08 +00002092 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002093 Value *ExtSrc;
2094 if (match(II->getArgOperand(0), m_FPExt(m_Value(ExtSrc))) &&
2095 II->getArgOperand(0)->hasOneUse()) {
2096 // fabs (fpext x) -> fpext (fabs x)
Matt Arsenault954a6242017-01-23 23:55:08 +00002097 Value *F = Intrinsic::getDeclaration(II->getModule(), II->getIntrinsicID(),
Matt Arsenault72333442017-01-17 00:10:40 +00002098 { ExtSrc->getType() });
2099 CallInst *NewFabs = Builder->CreateCall(F, ExtSrc);
2100 NewFabs->copyFastMathFlags(II);
2101 NewFabs->takeName(II);
2102 return new FPExtInst(NewFabs, II->getType());
2103 }
2104
Matt Arsenault56ff4832017-01-03 22:40:34 +00002105 break;
2106 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002107 case Intrinsic::cos:
2108 case Intrinsic::amdgcn_cos: {
2109 Value *SrcSrc;
2110 Value *Src = II->getArgOperand(0);
2111 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
2112 match(Src, m_Intrinsic<Intrinsic::fabs>(m_Value(SrcSrc)))) {
2113 // cos(-x) -> cos(x)
2114 // cos(fabs(x)) -> cos(x)
2115 II->setArgOperand(0, SrcSrc);
2116 return II;
2117 }
2118
2119 break;
2120 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002121 case Intrinsic::ppc_altivec_lvx:
2122 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002123 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002124 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002125 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002126 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002127 PointerType::getUnqual(II->getType()));
2128 return new LoadInst(Ptr);
2129 }
2130 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002131 case Intrinsic::ppc_vsx_lxvw4x:
2132 case Intrinsic::ppc_vsx_lxvd2x: {
2133 // Turn PPC VSX loads into normal loads.
2134 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2135 PointerType::getUnqual(II->getType()));
2136 return new LoadInst(Ptr, Twine(""), false, 1);
2137 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002138 case Intrinsic::ppc_altivec_stvx:
2139 case Intrinsic::ppc_altivec_stvxl:
2140 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002141 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002142 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002143 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002144 PointerType::getUnqual(II->getArgOperand(0)->getType());
2145 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2146 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002147 }
2148 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002149 case Intrinsic::ppc_vsx_stxvw4x:
2150 case Intrinsic::ppc_vsx_stxvd2x: {
2151 // Turn PPC VSX stores into normal stores.
2152 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
2153 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2154 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2155 }
Hal Finkel221f4672015-02-26 18:56:03 +00002156 case Intrinsic::ppc_qpx_qvlfs:
2157 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002158 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002159 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00002160 Type *VTy = VectorType::get(Builder->getFloatTy(),
2161 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00002162 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002163 PointerType::getUnqual(VTy));
2164 Value *Load = Builder->CreateLoad(Ptr);
2165 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002166 }
2167 break;
2168 case Intrinsic::ppc_qpx_qvlfd:
2169 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002170 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002171 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002172 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2173 PointerType::getUnqual(II->getType()));
2174 return new LoadInst(Ptr);
2175 }
2176 break;
2177 case Intrinsic::ppc_qpx_qvstfs:
2178 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002179 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002180 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00002181 Type *VTy = VectorType::get(Builder->getFloatTy(),
2182 II->getArgOperand(0)->getType()->getVectorNumElements());
2183 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
2184 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002185 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002186 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002187 }
2188 break;
2189 case Intrinsic::ppc_qpx_qvstfd:
2190 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002191 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002192 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002193 Type *OpPtrTy =
2194 PointerType::getUnqual(II->getArgOperand(0)->getType());
2195 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2196 return new StoreInst(II->getArgOperand(0), Ptr);
2197 }
2198 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002199
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002200 case Intrinsic::x86_vcvtph2ps_128:
2201 case Intrinsic::x86_vcvtph2ps_256: {
2202 auto Arg = II->getArgOperand(0);
2203 auto ArgType = cast<VectorType>(Arg->getType());
2204 auto RetType = cast<VectorType>(II->getType());
2205 unsigned ArgWidth = ArgType->getNumElements();
2206 unsigned RetWidth = RetType->getNumElements();
2207 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2208 assert(ArgType->isIntOrIntVectorTy() &&
2209 ArgType->getScalarSizeInBits() == 16 &&
2210 "CVTPH2PS input type should be 16-bit integer vector");
2211 assert(RetType->getScalarType()->isFloatTy() &&
2212 "CVTPH2PS output type should be 32-bit float vector");
2213
2214 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002215 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002216 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002217
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002218 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002219 auto VectorHalfAsShorts = Arg;
2220 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002221 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002222 for (unsigned i = 0; i != RetWidth; ++i)
2223 SubVecMask.push_back((int)i);
2224 VectorHalfAsShorts = Builder->CreateShuffleVector(
2225 Arg, UndefValue::get(ArgType), SubVecMask);
2226 }
2227
2228 auto VectorHalfType =
2229 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2230 auto VectorHalfs =
2231 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2232 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002233 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002234 }
2235
2236 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002237 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002238 II->setArgOperand(0, V);
2239 return II;
2240 }
2241 break;
2242 }
2243
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002244 case Intrinsic::x86_sse_cvtss2si:
2245 case Intrinsic::x86_sse_cvtss2si64:
2246 case Intrinsic::x86_sse_cvttss2si:
2247 case Intrinsic::x86_sse_cvttss2si64:
2248 case Intrinsic::x86_sse2_cvtsd2si:
2249 case Intrinsic::x86_sse2_cvtsd2si64:
2250 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002251 case Intrinsic::x86_sse2_cvttsd2si64:
2252 case Intrinsic::x86_avx512_vcvtss2si32:
2253 case Intrinsic::x86_avx512_vcvtss2si64:
2254 case Intrinsic::x86_avx512_vcvtss2usi32:
2255 case Intrinsic::x86_avx512_vcvtss2usi64:
2256 case Intrinsic::x86_avx512_vcvtsd2si32:
2257 case Intrinsic::x86_avx512_vcvtsd2si64:
2258 case Intrinsic::x86_avx512_vcvtsd2usi32:
2259 case Intrinsic::x86_avx512_vcvtsd2usi64:
2260 case Intrinsic::x86_avx512_cvttss2si:
2261 case Intrinsic::x86_avx512_cvttss2si64:
2262 case Intrinsic::x86_avx512_cvttss2usi:
2263 case Intrinsic::x86_avx512_cvttss2usi64:
2264 case Intrinsic::x86_avx512_cvttsd2si:
2265 case Intrinsic::x86_avx512_cvttsd2si64:
2266 case Intrinsic::x86_avx512_cvttsd2usi:
2267 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002268 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002269 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002270 Value *Arg = II->getArgOperand(0);
2271 unsigned VWidth = Arg->getType()->getVectorNumElements();
2272 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002273 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002274 return II;
2275 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002276 break;
2277 }
2278
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002279 case Intrinsic::x86_mmx_pmovmskb:
2280 case Intrinsic::x86_sse_movmsk_ps:
2281 case Intrinsic::x86_sse2_movmsk_pd:
2282 case Intrinsic::x86_sse2_pmovmskb_128:
2283 case Intrinsic::x86_avx_movmsk_pd_256:
2284 case Intrinsic::x86_avx_movmsk_ps_256:
2285 case Intrinsic::x86_avx2_pmovmskb: {
2286 if (Value *V = simplifyX86movmsk(*II, *Builder))
2287 return replaceInstUsesWith(*II, V);
2288 break;
2289 }
2290
Simon Pilgrim471efd22016-02-20 23:17:35 +00002291 case Intrinsic::x86_sse_comieq_ss:
2292 case Intrinsic::x86_sse_comige_ss:
2293 case Intrinsic::x86_sse_comigt_ss:
2294 case Intrinsic::x86_sse_comile_ss:
2295 case Intrinsic::x86_sse_comilt_ss:
2296 case Intrinsic::x86_sse_comineq_ss:
2297 case Intrinsic::x86_sse_ucomieq_ss:
2298 case Intrinsic::x86_sse_ucomige_ss:
2299 case Intrinsic::x86_sse_ucomigt_ss:
2300 case Intrinsic::x86_sse_ucomile_ss:
2301 case Intrinsic::x86_sse_ucomilt_ss:
2302 case Intrinsic::x86_sse_ucomineq_ss:
2303 case Intrinsic::x86_sse2_comieq_sd:
2304 case Intrinsic::x86_sse2_comige_sd:
2305 case Intrinsic::x86_sse2_comigt_sd:
2306 case Intrinsic::x86_sse2_comile_sd:
2307 case Intrinsic::x86_sse2_comilt_sd:
2308 case Intrinsic::x86_sse2_comineq_sd:
2309 case Intrinsic::x86_sse2_ucomieq_sd:
2310 case Intrinsic::x86_sse2_ucomige_sd:
2311 case Intrinsic::x86_sse2_ucomigt_sd:
2312 case Intrinsic::x86_sse2_ucomile_sd:
2313 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002314 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002315 case Intrinsic::x86_avx512_vcomi_ss:
2316 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002317 case Intrinsic::x86_avx512_mask_cmp_ss:
2318 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002319 // These intrinsics only demand the 0th element of their input vectors. If
2320 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002321 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002322 Value *Arg0 = II->getArgOperand(0);
2323 Value *Arg1 = II->getArgOperand(1);
2324 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2325 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2326 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002327 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002328 }
2329 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2330 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002331 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002332 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002333 if (MadeChange)
2334 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002335 break;
2336 }
Michael Zuckerman16b20d22017-04-16 13:26:08 +00002337 case Intrinsic::x86_avx512_mask_cmp_pd_128:
2338 case Intrinsic::x86_avx512_mask_cmp_pd_256:
2339 case Intrinsic::x86_avx512_mask_cmp_pd_512:
2340 case Intrinsic::x86_avx512_mask_cmp_ps_128:
2341 case Intrinsic::x86_avx512_mask_cmp_ps_256:
2342 case Intrinsic::x86_avx512_mask_cmp_ps_512: {
2343 // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2344 Value *Arg0 = II->getArgOperand(0);
2345 Value *Arg1 = II->getArgOperand(1);
2346 bool Arg0IsZero = match(Arg0, m_Zero());
2347 if (Arg0IsZero)
2348 std::swap(Arg0, Arg1);
2349 Value *A, *B;
2350 // This fold requires only the NINF(not +/- inf) since inf minus
2351 // inf is nan.
2352 // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2353 // equal for both compares.
2354 // NNAN is not needed because nans compare the same for both compares.
2355 // The compare intrinsic uses the above assumptions and therefore
2356 // doesn't require additional flags.
2357 if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
2358 match(Arg1, m_Zero()) &&
2359 cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2360 if (Arg0IsZero)
2361 std::swap(A, B);
2362 II->setArgOperand(0, A);
2363 II->setArgOperand(1, B);
2364 return II;
2365 }
2366 break;
2367 }
Simon Pilgrim471efd22016-02-20 23:17:35 +00002368
Craig Topper020b2282016-12-27 00:23:16 +00002369 case Intrinsic::x86_avx512_mask_add_ps_512:
2370 case Intrinsic::x86_avx512_mask_div_ps_512:
2371 case Intrinsic::x86_avx512_mask_mul_ps_512:
2372 case Intrinsic::x86_avx512_mask_sub_ps_512:
2373 case Intrinsic::x86_avx512_mask_add_pd_512:
2374 case Intrinsic::x86_avx512_mask_div_pd_512:
2375 case Intrinsic::x86_avx512_mask_mul_pd_512:
2376 case Intrinsic::x86_avx512_mask_sub_pd_512:
2377 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2378 // IR operations.
2379 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2380 if (R->getValue() == 4) {
2381 Value *Arg0 = II->getArgOperand(0);
2382 Value *Arg1 = II->getArgOperand(1);
2383
2384 Value *V;
2385 switch (II->getIntrinsicID()) {
2386 default: llvm_unreachable("Case stmts out of sync!");
2387 case Intrinsic::x86_avx512_mask_add_ps_512:
2388 case Intrinsic::x86_avx512_mask_add_pd_512:
2389 V = Builder->CreateFAdd(Arg0, Arg1);
2390 break;
2391 case Intrinsic::x86_avx512_mask_sub_ps_512:
2392 case Intrinsic::x86_avx512_mask_sub_pd_512:
2393 V = Builder->CreateFSub(Arg0, Arg1);
2394 break;
2395 case Intrinsic::x86_avx512_mask_mul_ps_512:
2396 case Intrinsic::x86_avx512_mask_mul_pd_512:
2397 V = Builder->CreateFMul(Arg0, Arg1);
2398 break;
2399 case Intrinsic::x86_avx512_mask_div_ps_512:
2400 case Intrinsic::x86_avx512_mask_div_pd_512:
2401 V = Builder->CreateFDiv(Arg0, Arg1);
2402 break;
2403 }
2404
2405 // Create a select for the masking.
2406 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2407 *Builder);
2408 return replaceInstUsesWith(*II, V);
2409 }
2410 }
2411 break;
2412
Craig Topper790d0fa2016-12-11 07:42:01 +00002413 case Intrinsic::x86_avx512_mask_add_ss_round:
2414 case Intrinsic::x86_avx512_mask_div_ss_round:
2415 case Intrinsic::x86_avx512_mask_mul_ss_round:
2416 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002417 case Intrinsic::x86_avx512_mask_add_sd_round:
2418 case Intrinsic::x86_avx512_mask_div_sd_round:
2419 case Intrinsic::x86_avx512_mask_mul_sd_round:
2420 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002421 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2422 // IR operations.
2423 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2424 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002425 // Extract the element as scalars.
2426 Value *Arg0 = II->getArgOperand(0);
2427 Value *Arg1 = II->getArgOperand(1);
2428 Value *LHS = Builder->CreateExtractElement(Arg0, (uint64_t)0);
2429 Value *RHS = Builder->CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002430
Craig Topper7f8540b2016-12-27 01:56:30 +00002431 Value *V;
2432 switch (II->getIntrinsicID()) {
2433 default: llvm_unreachable("Case stmts out of sync!");
2434 case Intrinsic::x86_avx512_mask_add_ss_round:
2435 case Intrinsic::x86_avx512_mask_add_sd_round:
2436 V = Builder->CreateFAdd(LHS, RHS);
2437 break;
2438 case Intrinsic::x86_avx512_mask_sub_ss_round:
2439 case Intrinsic::x86_avx512_mask_sub_sd_round:
2440 V = Builder->CreateFSub(LHS, RHS);
2441 break;
2442 case Intrinsic::x86_avx512_mask_mul_ss_round:
2443 case Intrinsic::x86_avx512_mask_mul_sd_round:
2444 V = Builder->CreateFMul(LHS, RHS);
2445 break;
2446 case Intrinsic::x86_avx512_mask_div_ss_round:
2447 case Intrinsic::x86_avx512_mask_div_sd_round:
2448 V = Builder->CreateFDiv(LHS, RHS);
2449 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002450 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002451
2452 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002453 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002454 auto *C = dyn_cast<ConstantInt>(Mask);
2455 // We don't need a select if we know the mask bit is a 1.
2456 if (!C || !C->getValue()[0]) {
2457 // Cast the mask to an i1 vector and then extract the lowest element.
2458 auto *MaskTy = VectorType::get(Builder->getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002459 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topper99163632016-12-30 23:06:28 +00002460 Mask = Builder->CreateBitCast(Mask, MaskTy);
2461 Mask = Builder->CreateExtractElement(Mask, (uint64_t)0);
2462 // Extract the lowest element from the passthru operand.
2463 Value *Passthru = Builder->CreateExtractElement(II->getArgOperand(2),
2464 (uint64_t)0);
2465 V = Builder->CreateSelect(Mask, V, Passthru);
2466 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002467
2468 // Insert the result back into the original argument 0.
2469 V = Builder->CreateInsertElement(Arg0, V, (uint64_t)0);
2470
2471 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002472 }
2473 }
2474 LLVM_FALLTHROUGH;
2475
2476 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2477 case Intrinsic::x86_avx512_mask_max_ss_round:
2478 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002479 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002480 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Topperab5f3552016-12-15 03:49:45 +00002481 case Intrinsic::x86_avx512_mask_vfmadd_ss:
2482 case Intrinsic::x86_avx512_mask_vfmadd_sd:
2483 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
2484 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
2485 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
2486 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
2487 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
2488 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
2489 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
2490 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
Craig Topperdfd268d2016-12-14 05:43:05 +00002491 case Intrinsic::x86_fma_vfmadd_ss:
2492 case Intrinsic::x86_fma_vfmsub_ss:
2493 case Intrinsic::x86_fma_vfnmadd_ss:
2494 case Intrinsic::x86_fma_vfnmsub_ss:
2495 case Intrinsic::x86_fma_vfmadd_sd:
2496 case Intrinsic::x86_fma_vfmsub_sd:
2497 case Intrinsic::x86_fma_vfnmadd_sd:
2498 case Intrinsic::x86_fma_vfnmsub_sd:
Craig Toppera0372de2016-12-14 03:17:27 +00002499 case Intrinsic::x86_sse_cmp_ss:
2500 case Intrinsic::x86_sse_min_ss:
2501 case Intrinsic::x86_sse_max_ss:
2502 case Intrinsic::x86_sse2_cmp_sd:
2503 case Intrinsic::x86_sse2_min_sd:
2504 case Intrinsic::x86_sse2_max_sd:
Craig Toppereb6a20e2016-12-14 03:17:30 +00002505 case Intrinsic::x86_sse41_round_ss:
2506 case Intrinsic::x86_sse41_round_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002507 case Intrinsic::x86_xop_vfrcz_ss:
2508 case Intrinsic::x86_xop_vfrcz_sd: {
2509 unsigned VWidth = II->getType()->getVectorNumElements();
2510 APInt UndefElts(VWidth, 0);
2511 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2512 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2513 if (V != II)
2514 return replaceInstUsesWith(*II, V);
2515 return II;
2516 }
2517 break;
2518 }
2519
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002520 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002521 // Constant fold lshr( <A x Bi>, Ci ).
2522 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002523 case Intrinsic::x86_sse2_psrai_d:
2524 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002525 case Intrinsic::x86_avx2_psrai_d:
2526 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002527 case Intrinsic::x86_avx512_psrai_q_128:
2528 case Intrinsic::x86_avx512_psrai_q_256:
2529 case Intrinsic::x86_avx512_psrai_d_512:
2530 case Intrinsic::x86_avx512_psrai_q_512:
2531 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002532 case Intrinsic::x86_sse2_psrli_d:
2533 case Intrinsic::x86_sse2_psrli_q:
2534 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002535 case Intrinsic::x86_avx2_psrli_d:
2536 case Intrinsic::x86_avx2_psrli_q:
2537 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002538 case Intrinsic::x86_avx512_psrli_d_512:
2539 case Intrinsic::x86_avx512_psrli_q_512:
2540 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002541 case Intrinsic::x86_sse2_pslli_d:
2542 case Intrinsic::x86_sse2_pslli_q:
2543 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002544 case Intrinsic::x86_avx2_pslli_d:
2545 case Intrinsic::x86_avx2_pslli_q:
2546 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002547 case Intrinsic::x86_avx512_pslli_d_512:
2548 case Intrinsic::x86_avx512_pslli_q_512:
2549 case Intrinsic::x86_avx512_pslli_w_512:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002550 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002551 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002552 break;
2553
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002554 case Intrinsic::x86_sse2_psra_d:
2555 case Intrinsic::x86_sse2_psra_w:
2556 case Intrinsic::x86_avx2_psra_d:
2557 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002558 case Intrinsic::x86_avx512_psra_q_128:
2559 case Intrinsic::x86_avx512_psra_q_256:
2560 case Intrinsic::x86_avx512_psra_d_512:
2561 case Intrinsic::x86_avx512_psra_q_512:
2562 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002563 case Intrinsic::x86_sse2_psrl_d:
2564 case Intrinsic::x86_sse2_psrl_q:
2565 case Intrinsic::x86_sse2_psrl_w:
2566 case Intrinsic::x86_avx2_psrl_d:
2567 case Intrinsic::x86_avx2_psrl_q:
2568 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002569 case Intrinsic::x86_avx512_psrl_d_512:
2570 case Intrinsic::x86_avx512_psrl_q_512:
2571 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002572 case Intrinsic::x86_sse2_psll_d:
2573 case Intrinsic::x86_sse2_psll_q:
2574 case Intrinsic::x86_sse2_psll_w:
2575 case Intrinsic::x86_avx2_psll_d:
2576 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002577 case Intrinsic::x86_avx2_psll_w:
2578 case Intrinsic::x86_avx512_psll_d_512:
2579 case Intrinsic::x86_avx512_psll_q_512:
2580 case Intrinsic::x86_avx512_psll_w_512: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002581 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002582 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002583
2584 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2585 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002586 Value *Arg1 = II->getArgOperand(1);
2587 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002588 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002589 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002590
Simon Pilgrim996725e2015-09-19 11:41:53 +00002591 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002592 II->setArgOperand(1, V);
2593 return II;
2594 }
2595 break;
2596 }
2597
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002598 case Intrinsic::x86_avx2_psllv_d:
2599 case Intrinsic::x86_avx2_psllv_d_256:
2600 case Intrinsic::x86_avx2_psllv_q:
2601 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002602 case Intrinsic::x86_avx512_psllv_d_512:
2603 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002604 case Intrinsic::x86_avx512_psllv_w_128:
2605 case Intrinsic::x86_avx512_psllv_w_256:
2606 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002607 case Intrinsic::x86_avx2_psrav_d:
2608 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002609 case Intrinsic::x86_avx512_psrav_q_128:
2610 case Intrinsic::x86_avx512_psrav_q_256:
2611 case Intrinsic::x86_avx512_psrav_d_512:
2612 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002613 case Intrinsic::x86_avx512_psrav_w_128:
2614 case Intrinsic::x86_avx512_psrav_w_256:
2615 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002616 case Intrinsic::x86_avx2_psrlv_d:
2617 case Intrinsic::x86_avx2_psrlv_d_256:
2618 case Intrinsic::x86_avx2_psrlv_q:
2619 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002620 case Intrinsic::x86_avx512_psrlv_d_512:
2621 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002622 case Intrinsic::x86_avx512_psrlv_w_128:
2623 case Intrinsic::x86_avx512_psrlv_w_256:
2624 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002625 if (Value *V = simplifyX86varShift(*II, *Builder))
2626 return replaceInstUsesWith(*II, V);
2627 break;
2628
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002629 case Intrinsic::x86_sse2_pmulu_dq:
2630 case Intrinsic::x86_sse41_pmuldq:
2631 case Intrinsic::x86_avx2_pmul_dq:
Craig Topper72f2d4e2016-12-27 05:30:09 +00002632 case Intrinsic::x86_avx2_pmulu_dq:
2633 case Intrinsic::x86_avx512_pmul_dq_512:
2634 case Intrinsic::x86_avx512_pmulu_dq_512: {
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +00002635 if (Value *V = simplifyX86muldq(*II, *Builder))
Simon Pilgrima50a93f2017-01-20 18:20:30 +00002636 return replaceInstUsesWith(*II, V);
2637
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002638 unsigned VWidth = II->getType()->getVectorNumElements();
2639 APInt UndefElts(VWidth, 0);
2640 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
2641 if (Value *V = SimplifyDemandedVectorElts(II, DemandedElts, UndefElts)) {
2642 if (V != II)
2643 return replaceInstUsesWith(*II, V);
2644 return II;
2645 }
2646 break;
2647 }
2648
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002649 case Intrinsic::x86_sse2_packssdw_128:
2650 case Intrinsic::x86_sse2_packsswb_128:
2651 case Intrinsic::x86_avx2_packssdw:
2652 case Intrinsic::x86_avx2_packsswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002653 case Intrinsic::x86_avx512_packssdw_512:
2654 case Intrinsic::x86_avx512_packsswb_512:
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002655 if (Value *V = simplifyX86pack(*II, *this, *Builder, true))
2656 return replaceInstUsesWith(*II, V);
2657 break;
2658
2659 case Intrinsic::x86_sse2_packuswb_128:
2660 case Intrinsic::x86_sse41_packusdw:
2661 case Intrinsic::x86_avx2_packusdw:
2662 case Intrinsic::x86_avx2_packuswb:
Craig Topper3731f4d2017-02-16 07:35:23 +00002663 case Intrinsic::x86_avx512_packusdw_512:
2664 case Intrinsic::x86_avx512_packuswb_512:
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002665 if (Value *V = simplifyX86pack(*II, *this, *Builder, false))
2666 return replaceInstUsesWith(*II, V);
2667 break;
2668
Craig Topperb6122122017-01-26 05:17:13 +00002669 case Intrinsic::x86_pclmulqdq: {
2670 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2671 unsigned Imm = C->getZExtValue();
2672
2673 bool MadeChange = false;
2674 Value *Arg0 = II->getArgOperand(0);
2675 Value *Arg1 = II->getArgOperand(1);
2676 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2677 APInt DemandedElts(VWidth, 0);
2678
2679 APInt UndefElts1(VWidth, 0);
2680 DemandedElts = (Imm & 0x01) ? 2 : 1;
2681 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts,
2682 UndefElts1)) {
2683 II->setArgOperand(0, V);
2684 MadeChange = true;
2685 }
2686
2687 APInt UndefElts2(VWidth, 0);
2688 DemandedElts = (Imm & 0x10) ? 2 : 1;
2689 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts,
2690 UndefElts2)) {
2691 II->setArgOperand(1, V);
2692 MadeChange = true;
2693 }
2694
2695 // If both input elements are undef, the result is undef.
2696 if (UndefElts1[(Imm & 0x01) ? 1 : 0] ||
2697 UndefElts2[(Imm & 0x10) ? 1 : 0])
2698 return replaceInstUsesWith(*II,
2699 ConstantAggregateZero::get(II->getType()));
2700
2701 if (MadeChange)
2702 return II;
2703 }
2704 break;
2705 }
2706
Sanjay Patelc86867c2015-04-16 17:52:13 +00002707 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002708 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002709 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002710 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002711
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002712 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002713 Value *Op0 = II->getArgOperand(0);
2714 Value *Op1 = II->getArgOperand(1);
2715 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2716 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002717 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2718 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2719 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002720
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002721 // See if we're dealing with constant values.
2722 Constant *C1 = dyn_cast<Constant>(Op1);
2723 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002724 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002725 : nullptr;
2726 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002727 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002728 : nullptr;
2729
2730 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002731 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002732 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002733
2734 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2735 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002736 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002737 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2738 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002739 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002740 }
2741 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2742 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002743 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002744 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002745 if (MadeChange)
2746 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002747 break;
2748 }
2749
2750 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002751 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2752 // bits of the lower 64-bits. The upper 64-bits are undefined.
2753 Value *Op0 = II->getArgOperand(0);
2754 unsigned VWidth = Op0->getType()->getVectorNumElements();
2755 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2756 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002757
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002758 // See if we're dealing with constant values.
2759 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2760 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2761
2762 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002763 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002764 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002765
2766 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2767 // operand.
2768 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002769 II->setArgOperand(0, V);
2770 return II;
2771 }
2772 break;
2773 }
2774
2775 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002776 Value *Op0 = II->getArgOperand(0);
2777 Value *Op1 = II->getArgOperand(1);
2778 unsigned VWidth = Op0->getType()->getVectorNumElements();
2779 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2780 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2781 Op1->getType()->getVectorNumElements() == 2 &&
2782 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002783
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002784 // See if we're dealing with constant values.
2785 Constant *C1 = dyn_cast<Constant>(Op1);
2786 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002787 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002788 : nullptr;
2789
2790 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2791 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002792 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002793 APInt Len = V11.zextOrTrunc(6);
2794 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002795 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002796 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002797 }
2798
2799 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2800 // operand.
2801 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002802 II->setArgOperand(0, V);
2803 return II;
2804 }
2805 break;
2806 }
2807
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002808 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002809 // INSERTQI: Extract lowest Length bits from lower half of second source and
2810 // insert over first source starting at Index bit. The upper 64-bits are
2811 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002812 Value *Op0 = II->getArgOperand(0);
2813 Value *Op1 = II->getArgOperand(1);
2814 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2815 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002816 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2817 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2818 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002819
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002820 // See if we're dealing with constant values.
2821 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2822 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2823
2824 // Attempt to simplify to a constant or shuffle vector.
2825 if (CILength && CIIndex) {
2826 APInt Len = CILength->getValue().zextOrTrunc(6);
2827 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002828 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002829 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002830 }
2831
2832 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2833 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002834 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002835 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2836 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002837 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002838 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002839 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2840 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002841 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002842 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002843 if (MadeChange)
2844 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002845 break;
2846 }
2847
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002848 case Intrinsic::x86_sse41_pblendvb:
2849 case Intrinsic::x86_sse41_blendvps:
2850 case Intrinsic::x86_sse41_blendvpd:
2851 case Intrinsic::x86_avx_blendv_ps_256:
2852 case Intrinsic::x86_avx_blendv_pd_256:
2853 case Intrinsic::x86_avx2_pblendvb: {
2854 // Convert blendv* to vector selects if the mask is constant.
2855 // This optimization is convoluted because the intrinsic is defined as
2856 // getting a vector of floats or doubles for the ps and pd versions.
2857 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002858
2859 Value *Op0 = II->getArgOperand(0);
2860 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002861 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002862
2863 // fold (blend A, A, Mask) -> A
2864 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002865 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002866
2867 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002868 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002869 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002870
2871 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002872 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2873 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002874 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002875 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002876 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002877 }
2878
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002879 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002880 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002881 case Intrinsic::x86_avx512_pshuf_b_512:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002882 if (Value *V = simplifyX86pshufb(*II, *Builder))
2883 return replaceInstUsesWith(*II, V);
2884 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002885
Rafael Espindolabad3f772014-04-21 22:06:04 +00002886 case Intrinsic::x86_avx_vpermilvar_ps:
2887 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002888 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002889 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002890 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002891 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002892 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2893 return replaceInstUsesWith(*II, V);
2894 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002895
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002896 case Intrinsic::x86_avx2_permd:
2897 case Intrinsic::x86_avx2_permps:
2898 if (Value *V = simplifyX86vpermv(*II, *Builder))
2899 return replaceInstUsesWith(*II, V);
2900 break;
2901
Craig Toppere3280452016-12-25 23:58:57 +00002902 case Intrinsic::x86_avx512_mask_permvar_df_256:
2903 case Intrinsic::x86_avx512_mask_permvar_df_512:
2904 case Intrinsic::x86_avx512_mask_permvar_di_256:
2905 case Intrinsic::x86_avx512_mask_permvar_di_512:
2906 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2907 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2908 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2909 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2910 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2911 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2912 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2913 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2914 case Intrinsic::x86_avx512_mask_permvar_si_256:
2915 case Intrinsic::x86_avx512_mask_permvar_si_512:
2916 if (Value *V = simplifyX86vpermv(*II, *Builder)) {
2917 // We simplified the permuting, now create a select for the masking.
2918 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2919 *Builder);
2920 return replaceInstUsesWith(*II, V);
2921 }
2922 break;
2923
Sanjay Patelccf5f242015-03-20 21:47:56 +00002924 case Intrinsic::x86_avx_vperm2f128_pd_256:
2925 case Intrinsic::x86_avx_vperm2f128_ps_256:
2926 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002927 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002928 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002929 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002930 break;
2931
Sanjay Patel98a71502016-02-29 23:16:48 +00002932 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002933 case Intrinsic::x86_avx_maskload_pd:
2934 case Intrinsic::x86_avx_maskload_ps_256:
2935 case Intrinsic::x86_avx_maskload_pd_256:
2936 case Intrinsic::x86_avx2_maskload_d:
2937 case Intrinsic::x86_avx2_maskload_q:
2938 case Intrinsic::x86_avx2_maskload_d_256:
2939 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002940 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2941 return I;
2942 break;
2943
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002944 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002945 case Intrinsic::x86_avx_maskstore_ps:
2946 case Intrinsic::x86_avx_maskstore_pd:
2947 case Intrinsic::x86_avx_maskstore_ps_256:
2948 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002949 case Intrinsic::x86_avx2_maskstore_d:
2950 case Intrinsic::x86_avx2_maskstore_q:
2951 case Intrinsic::x86_avx2_maskstore_d_256:
2952 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002953 if (simplifyX86MaskedStore(*II, *this))
2954 return nullptr;
2955 break;
2956
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002957 case Intrinsic::x86_xop_vpcomb:
2958 case Intrinsic::x86_xop_vpcomd:
2959 case Intrinsic::x86_xop_vpcomq:
2960 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002961 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002962 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002963 break;
2964
2965 case Intrinsic::x86_xop_vpcomub:
2966 case Intrinsic::x86_xop_vpcomud:
2967 case Intrinsic::x86_xop_vpcomuq:
2968 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002969 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002970 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002971 break;
2972
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002973 case Intrinsic::ppc_altivec_vperm:
2974 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002975 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2976 // a vectorshuffle for little endian, we must undo the transformation
2977 // performed on vec_perm in altivec.h. That is, we must complement
2978 // the permutation mask with respect to 31 and reverse the order of
2979 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002980 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2981 assert(Mask->getType()->getVectorNumElements() == 16 &&
2982 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002983
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002984 // Check that all of the elements are integer constants or undefs.
2985 bool AllEltsOk = true;
2986 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002987 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002988 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002989 AllEltsOk = false;
2990 break;
2991 }
2992 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002993
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002994 if (AllEltsOk) {
2995 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002996 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2997 Mask->getType());
2998 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2999 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003000 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00003001
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003002 // Only extract each element once.
3003 Value *ExtractedElts[32];
3004 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00003005
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003006 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00003007 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003008 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00003009 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00003010 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003011 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003012 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00003013 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00003014
Craig Topperf40110f2014-04-25 05:29:35 +00003015 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003016 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3017 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00003018 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00003019 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003020 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003021 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003022
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003023 // Insert this value into the result vector.
3024 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003025 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003026 }
3027 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3028 }
3029 }
3030 break;
3031
Bob Wilsona4e231c2010-10-22 21:41:48 +00003032 case Intrinsic::arm_neon_vld1:
3033 case Intrinsic::arm_neon_vld2:
3034 case Intrinsic::arm_neon_vld3:
3035 case Intrinsic::arm_neon_vld4:
3036 case Intrinsic::arm_neon_vld2lane:
3037 case Intrinsic::arm_neon_vld3lane:
3038 case Intrinsic::arm_neon_vld4lane:
3039 case Intrinsic::arm_neon_vst1:
3040 case Intrinsic::arm_neon_vst2:
3041 case Intrinsic::arm_neon_vst3:
3042 case Intrinsic::arm_neon_vst4:
3043 case Intrinsic::arm_neon_vst2lane:
3044 case Intrinsic::arm_neon_vst3lane:
3045 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003046 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003047 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003048 unsigned AlignArg = II->getNumArgOperands() - 1;
3049 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3050 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3051 II->setArgOperand(AlignArg,
3052 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3053 MemAlign, false));
3054 return II;
3055 }
3056 break;
3057 }
3058
Lang Hames3a90fab2012-05-01 00:20:38 +00003059 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003060 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003061 case Intrinsic::aarch64_neon_smull:
3062 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003063 Value *Arg0 = II->getArgOperand(0);
3064 Value *Arg1 = II->getArgOperand(1);
3065
3066 // Handle mul by zero first:
3067 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003068 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003069 }
3070
3071 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003072 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003073 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003074 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003075 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3076 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3077 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3078 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3079
Sanjay Patel4b198802016-02-01 22:23:39 +00003080 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003081 }
3082
Alp Tokercb402912014-01-24 17:20:08 +00003083 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003084 std::swap(Arg0, Arg1);
3085 }
3086
3087 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003088 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003089 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003090 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3091 if (Splat->isOne())
3092 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3093 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003094
3095 break;
3096 }
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003097 case Intrinsic::amdgcn_rcp: {
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003098 Value *Src = II->getArgOperand(0);
3099
3100 // TODO: Move to ConstantFolding/InstSimplify?
3101 if (isa<UndefValue>(Src))
3102 return replaceInstUsesWith(CI, Src);
3103
3104 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003105 const APFloat &ArgVal = C->getValueAPF();
3106 APFloat Val(ArgVal.getSemantics(), 1.0);
3107 APFloat::opStatus Status = Val.divide(ArgVal,
3108 APFloat::rmNearestTiesToEven);
3109 // Only do this if it was exact and therefore not dependent on the
3110 // rounding mode.
3111 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003112 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003113 }
3114
3115 break;
3116 }
Matt Arsenault4c7795d2017-03-24 19:04:57 +00003117 case Intrinsic::amdgcn_rsq: {
3118 Value *Src = II->getArgOperand(0);
3119
3120 // TODO: Move to ConstantFolding/InstSimplify?
3121 if (isa<UndefValue>(Src))
3122 return replaceInstUsesWith(CI, Src);
3123 break;
3124 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003125 case Intrinsic::amdgcn_frexp_mant:
3126 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003127 Value *Src = II->getArgOperand(0);
3128 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3129 int Exp;
3130 APFloat Significand = frexp(C->getValueAPF(), Exp,
3131 APFloat::rmNearestTiesToEven);
3132
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003133 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3134 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3135 Significand));
3136 }
3137
3138 // Match instruction special case behavior.
3139 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3140 Exp = 0;
3141
3142 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3143 }
3144
3145 if (isa<UndefValue>(Src))
3146 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003147
3148 break;
3149 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003150 case Intrinsic::amdgcn_class: {
3151 enum {
3152 S_NAN = 1 << 0, // Signaling NaN
3153 Q_NAN = 1 << 1, // Quiet NaN
3154 N_INFINITY = 1 << 2, // Negative infinity
3155 N_NORMAL = 1 << 3, // Negative normal
3156 N_SUBNORMAL = 1 << 4, // Negative subnormal
3157 N_ZERO = 1 << 5, // Negative zero
3158 P_ZERO = 1 << 6, // Positive zero
3159 P_SUBNORMAL = 1 << 7, // Positive subnormal
3160 P_NORMAL = 1 << 8, // Positive normal
3161 P_INFINITY = 1 << 9 // Positive infinity
3162 };
3163
3164 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3165 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3166
3167 Value *Src0 = II->getArgOperand(0);
3168 Value *Src1 = II->getArgOperand(1);
3169 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3170 if (!CMask) {
3171 if (isa<UndefValue>(Src0))
3172 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3173
3174 if (isa<UndefValue>(Src1))
3175 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3176 break;
3177 }
3178
3179 uint32_t Mask = CMask->getZExtValue();
3180
3181 // If all tests are made, it doesn't matter what the value is.
3182 if ((Mask & FullMask) == FullMask)
3183 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3184
3185 if ((Mask & FullMask) == 0)
3186 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3187
3188 if (Mask == (S_NAN | Q_NAN)) {
3189 // Equivalent of isnan. Replace with standard fcmp.
3190 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
3191 FCmp->takeName(II);
3192 return replaceInstUsesWith(*II, FCmp);
3193 }
3194
3195 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3196 if (!CVal) {
3197 if (isa<UndefValue>(Src0))
3198 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3199
3200 // Clamp mask to used bits
3201 if ((Mask & FullMask) != Mask) {
3202 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
3203 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3204 );
3205
3206 NewCall->takeName(II);
3207 return replaceInstUsesWith(*II, NewCall);
3208 }
3209
3210 break;
3211 }
3212
3213 const APFloat &Val = CVal->getValueAPF();
3214
3215 bool Result =
3216 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3217 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3218 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3219 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3220 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3221 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3222 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3223 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3224 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3225 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3226
3227 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3228 }
Matt Arsenault1f17c662017-02-22 00:27:34 +00003229 case Intrinsic::amdgcn_cvt_pkrtz: {
3230 Value *Src0 = II->getArgOperand(0);
3231 Value *Src1 = II->getArgOperand(1);
3232 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3233 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3234 const fltSemantics &HalfSem
3235 = II->getType()->getScalarType()->getFltSemantics();
3236 bool LosesInfo;
3237 APFloat Val0 = C0->getValueAPF();
3238 APFloat Val1 = C1->getValueAPF();
3239 Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3240 Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3241
3242 Constant *Folded = ConstantVector::get({
3243 ConstantFP::get(II->getContext(), Val0),
3244 ConstantFP::get(II->getContext(), Val1) });
3245 return replaceInstUsesWith(*II, Folded);
3246 }
3247 }
3248
3249 if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3250 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3251
3252 break;
3253 }
Matt Arsenaultf5262252017-02-22 23:04:58 +00003254 case Intrinsic::amdgcn_ubfe:
3255 case Intrinsic::amdgcn_sbfe: {
3256 // Decompose simple cases into standard shifts.
3257 Value *Src = II->getArgOperand(0);
3258 if (isa<UndefValue>(Src))
3259 return replaceInstUsesWith(*II, Src);
3260
3261 unsigned Width;
3262 Type *Ty = II->getType();
3263 unsigned IntSize = Ty->getIntegerBitWidth();
3264
3265 ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3266 if (CWidth) {
3267 Width = CWidth->getZExtValue();
3268 if ((Width & (IntSize - 1)) == 0)
3269 return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3270
3271 if (Width >= IntSize) {
3272 // Hardware ignores high bits, so remove those.
3273 II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3274 Width & (IntSize - 1)));
3275 return II;
3276 }
3277 }
3278
3279 unsigned Offset;
3280 ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3281 if (COffset) {
3282 Offset = COffset->getZExtValue();
3283 if (Offset >= IntSize) {
3284 II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3285 Offset & (IntSize - 1)));
3286 return II;
3287 }
3288 }
3289
3290 bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3291
3292 // TODO: Also emit sub if only width is constant.
3293 if (!CWidth && COffset && Offset == 0) {
3294 Constant *KSize = ConstantInt::get(COffset->getType(), IntSize);
3295 Value *ShiftVal = Builder->CreateSub(KSize, II->getArgOperand(2));
3296 ShiftVal = Builder->CreateZExt(ShiftVal, II->getType());
3297
3298 Value *Shl = Builder->CreateShl(Src, ShiftVal);
3299 Value *RightShift = Signed ?
3300 Builder->CreateAShr(Shl, ShiftVal) :
3301 Builder->CreateLShr(Shl, ShiftVal);
3302 RightShift->takeName(II);
3303 return replaceInstUsesWith(*II, RightShift);
3304 }
3305
3306 if (!CWidth || !COffset)
3307 break;
3308
3309 // TODO: This allows folding to undef when the hardware has specific
3310 // behavior?
3311 if (Offset + Width < IntSize) {
3312 Value *Shl = Builder->CreateShl(Src, IntSize - Offset - Width);
3313 Value *RightShift = Signed ?
3314 Builder->CreateAShr(Shl, IntSize - Width) :
3315 Builder->CreateLShr(Shl, IntSize - Width);
3316 RightShift->takeName(II);
3317 return replaceInstUsesWith(*II, RightShift);
3318 }
3319
3320 Value *RightShift = Signed ?
3321 Builder->CreateAShr(Src, Offset) :
3322 Builder->CreateLShr(Src, Offset);
3323
3324 RightShift->takeName(II);
3325 return replaceInstUsesWith(*II, RightShift);
3326 }
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003327 case Intrinsic::amdgcn_exp:
3328 case Intrinsic::amdgcn_exp_compr: {
3329 ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3330 if (!En) // Illegal.
3331 break;
3332
3333 unsigned EnBits = En->getZExtValue();
3334 if (EnBits == 0xf)
3335 break; // All inputs enabled.
3336
3337 bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3338 bool Changed = false;
3339 for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3340 if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3341 (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3342 Value *Src = II->getArgOperand(I + 2);
3343 if (!isa<UndefValue>(Src)) {
3344 II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3345 Changed = true;
3346 }
3347 }
3348 }
3349
3350 if (Changed)
3351 return II;
3352
3353 break;
Matt Arsenaultcdb468c2017-02-27 23:08:49 +00003354
3355 }
3356 case Intrinsic::amdgcn_fmed3: {
3357 // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3358 // for the shader.
3359
3360 Value *Src0 = II->getArgOperand(0);
3361 Value *Src1 = II->getArgOperand(1);
3362 Value *Src2 = II->getArgOperand(2);
3363
3364 bool Swap = false;
3365 // Canonicalize constants to RHS operands.
3366 //
3367 // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3368 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3369 std::swap(Src0, Src1);
3370 Swap = true;
3371 }
3372
3373 if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3374 std::swap(Src1, Src2);
3375 Swap = true;
3376 }
3377
3378 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3379 std::swap(Src0, Src1);
3380 Swap = true;
3381 }
3382
3383 if (Swap) {
3384 II->setArgOperand(0, Src0);
3385 II->setArgOperand(1, Src1);
3386 II->setArgOperand(2, Src2);
3387 return II;
3388 }
3389
3390 if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3391 CallInst *NewCall = Builder->CreateMinNum(Src0, Src1);
3392 NewCall->copyFastMathFlags(II);
3393 NewCall->takeName(II);
3394 return replaceInstUsesWith(*II, NewCall);
3395 }
3396
3397 if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3398 if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3399 if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3400 APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3401 C2->getValueAPF());
3402 return replaceInstUsesWith(*II,
3403 ConstantFP::get(Builder->getContext(), Result));
3404 }
3405 }
3406 }
3407
3408 break;
Matt Arsenaultd4bca1e2017-02-23 00:44:03 +00003409 }
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003410 case Intrinsic::amdgcn_icmp:
3411 case Intrinsic::amdgcn_fcmp: {
3412 const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2));
3413 if (!CC)
3414 break;
3415
3416 // Guard against invalid arguments.
3417 int64_t CCVal = CC->getZExtValue();
3418 bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3419 if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3420 CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3421 (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3422 CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3423 break;
3424
3425 Value *Src0 = II->getArgOperand(0);
3426 Value *Src1 = II->getArgOperand(1);
3427
3428 if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3429 if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3430 Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
Nicolai Haehnle9c661852017-04-24 17:08:43 +00003431 if (CCmp->isNullValue()) {
3432 return replaceInstUsesWith(
3433 *II, ConstantExpr::getSExt(CCmp, II->getType()));
3434 }
3435
3436 // The result of V_ICMP/V_FCMP assembly instructions (which this
3437 // intrinsic exposes) is one bit per thread, masked with the EXEC
3438 // register (which contains the bitmask of live threads). So a
3439 // comparison that always returns true is the same as a read of the
3440 // EXEC register.
3441 Value *NewF = Intrinsic::getDeclaration(
3442 II->getModule(), Intrinsic::read_register, II->getType());
3443 Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3444 MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3445 Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
3446 CallInst *NewCall = Builder->CreateCall(NewF, Args);
3447 NewCall->addAttribute(AttributeList::FunctionIndex,
3448 Attribute::Convergent);
3449 NewCall->takeName(II);
3450 return replaceInstUsesWith(*II, NewCall);
Matt Arsenaultd81f5572017-03-13 18:14:02 +00003451 }
3452
3453 // Canonicalize constants to RHS.
3454 CmpInst::Predicate SwapPred
3455 = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3456 II->setArgOperand(0, Src1);
3457 II->setArgOperand(1, Src0);
3458 II->setArgOperand(2, ConstantInt::get(CC->getType(),
3459 static_cast<int>(SwapPred)));
3460 return II;
3461 }
3462
3463 if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3464 break;
3465
3466 // Canonicalize compare eq with true value to compare != 0
3467 // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3468 // -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3469 // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3470 // -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3471 Value *ExtSrc;
3472 if (CCVal == CmpInst::ICMP_EQ &&
3473 ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3474 (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3475 ExtSrc->getType()->isIntegerTy(1)) {
3476 II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3477 II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3478 return II;
3479 }
3480
3481 CmpInst::Predicate SrcPred;
3482 Value *SrcLHS;
3483 Value *SrcRHS;
3484
3485 // Fold compare eq/ne with 0 from a compare result as the predicate to the
3486 // intrinsic. The typical use is a wave vote function in the library, which
3487 // will be fed from a user code condition compared with 0. Fold in the
3488 // redundant compare.
3489
3490 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3491 // -> llvm.amdgcn.[if]cmp(a, b, pred)
3492 //
3493 // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3494 // -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3495 if (match(Src1, m_Zero()) &&
3496 match(Src0,
3497 m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3498 if (CCVal == CmpInst::ICMP_EQ)
3499 SrcPred = CmpInst::getInversePredicate(SrcPred);
3500
3501 Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3502 Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3503
3504 Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID,
3505 SrcLHS->getType());
3506 Value *Args[] = { SrcLHS, SrcRHS,
3507 ConstantInt::get(CC->getType(), SrcPred) };
3508 CallInst *NewCall = Builder->CreateCall(NewF, Args);
3509 NewCall->takeName(II);
3510 return replaceInstUsesWith(*II, NewCall);
3511 }
3512
3513 break;
3514 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003515 case Intrinsic::stackrestore: {
3516 // If the save is right next to the restore, remove the restore. This can
3517 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003518 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003519 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003520 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00003521 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003522 }
3523 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003524
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003525 // Scan down this block to see if there is another stack restore in the
3526 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003527 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003528 TerminatorInst *TI = II->getParent()->getTerminator();
3529 bool CannotRemove = false;
3530 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003531 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003532 CannotRemove = true;
3533 break;
3534 }
3535 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3536 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3537 // If there is a stackrestore below this one, remove this one.
3538 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003539 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003540
3541 // Bail if we cross over an intrinsic with side effects, such as
3542 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3543 if (II->mayHaveSideEffects()) {
3544 CannotRemove = true;
3545 break;
3546 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003547 } else {
3548 // If we found a non-intrinsic call, we can't remove the stack
3549 // restore.
3550 CannotRemove = true;
3551 break;
3552 }
3553 }
3554 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003555
Bill Wendlingf891bf82011-07-31 06:30:59 +00003556 // If the stack restore is in a return, resume, or unwind block and if there
3557 // are no allocas or calls between the restore and the return, nuke the
3558 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003559 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003560 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003561 break;
3562 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003563 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003564 // Asan needs to poison memory to detect invalid access which is possible
3565 // even for empty lifetime range.
3566 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
3567 break;
3568
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003569 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3570 Intrinsic::lifetime_end, *this))
3571 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003572 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003573 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003574 Value *IIOperand = II->getArgOperand(0);
3575 // Remove an assume if it is immediately followed by an identical assume.
3576 if (match(II->getNextNode(),
3577 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3578 return eraseInstFromFunction(CI);
3579
Hal Finkelf5867a72014-07-25 21:45:17 +00003580 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003581 // Note: New assumption intrinsics created here are registered by
3582 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00003583 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003584 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
3585 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
3586 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003587 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003588 }
3589 // assume(!(a || b)) -> assume(!a); assume(!b);
3590 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00003591 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
3592 II->getName());
3593 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
3594 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003595 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003596 }
Hal Finkel04a15612014-10-04 21:27:06 +00003597
Philip Reames66c6de62014-11-11 23:33:19 +00003598 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3599 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003600 CmpInst::Predicate Pred;
3601 Instruction *LHS;
3602 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3603 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3604 LHS->getType()->isPointerTy() &&
3605 isValidAssumeForContext(II, LHS, &DT)) {
3606 MDNode *MD = MDNode::get(II->getContext(), None);
3607 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3608 return eraseInstFromFunction(*II);
3609
Chandler Carruth24969102015-02-10 08:07:32 +00003610 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003611 // TODO: apply range metadata for range check patterns?
3612 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003613
Hal Finkel04a15612014-10-04 21:27:06 +00003614 // If there is a dominating assume with the same condition as this one,
3615 // then this one is redundant, and should be removed.
Craig Topperb45eabc2017-04-26 16:39:58 +00003616 KnownBits Known(1);
3617 computeKnownBits(IIOperand, Known, 0, II);
Craig Topperf0aeee02017-05-05 17:36:09 +00003618 if (Known.isAllOnes())
Sanjay Patel4b198802016-02-01 22:23:39 +00003619 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003620
Hal Finkel8a9a7832017-01-11 13:24:24 +00003621 // Update the cache of affected values for this assumption (we might be
3622 // here because we just simplified the condition).
3623 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003624 break;
3625 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003626 case Intrinsic::experimental_gc_relocate: {
3627 // Translate facts known about a pointer before relocating into
3628 // facts about the relocate value, while being careful to
3629 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003630 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003631
3632 // Remove the relocation if unused, note that this check is required
3633 // to prevent the cases below from looping forever.
3634 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003635 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003636
3637 // Undef is undef, even after relocation.
3638 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3639 // most practical collectors, but there was discussion in the review thread
3640 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003641 if (isa<UndefValue>(DerivedPtr))
3642 // Use undef of gc_relocate's type to replace it.
3643 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003644
Philip Reamesea4d8e82016-02-09 21:09:22 +00003645 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3646 // The relocation of null will be null for most any collector.
3647 // TODO: provide a hook for this in GCStrategy. There might be some
3648 // weird collector this property does not hold for.
3649 if (isa<ConstantPointerNull>(DerivedPtr))
3650 // Use null-pointer of gc_relocate's type to replace it.
3651 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003652
Philip Reamesea4d8e82016-02-09 21:09:22 +00003653 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00003654 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Reid Klecknerb5180542017-03-21 16:57:19 +00003655 II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003656 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003657
3658 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3659 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003660
Philip Reames9db26ff2014-12-29 23:27:30 +00003661 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00003662 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00003663 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003664
3665 case Intrinsic::experimental_guard: {
Sanjoy Dase0e57952017-02-01 16:34:55 +00003666 // Is this guard followed by another guard?
3667 Instruction *NextInst = II->getNextNode();
3668 Value *NextCond = nullptr;
3669 if (match(NextInst,
3670 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3671 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003672
Simon Pilgrim68168d12017-03-30 12:59:53 +00003673 // Remove a guard that it is immediately preceded by an identical guard.
Sanjoy Dase0e57952017-02-01 16:34:55 +00003674 if (CurrCond == NextCond)
3675 return eraseInstFromFunction(*NextInst);
3676
3677 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3678 II->setArgOperand(0, Builder->CreateAnd(CurrCond, NextCond));
3679 return eraseInstFromFunction(*NextInst);
3680 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003681 break;
3682 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003683 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003684 return visitCallSite(II);
3685}
3686
Davide Italianoaec46172017-01-31 18:09:05 +00003687// Fence instruction simplification
3688Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3689 // Remove identical consecutive fences.
3690 if (auto *NFI = dyn_cast<FenceInst>(FI.getNextNode()))
3691 if (FI.isIdenticalTo(NFI))
3692 return eraseInstFromFunction(FI);
3693 return nullptr;
3694}
3695
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003696// InvokeInst simplification
3697//
3698Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3699 return visitCallSite(&II);
3700}
3701
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003702/// If this cast does not affect the value passed through the varargs area, we
3703/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003704static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003705 const DataLayout &DL,
3706 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003707 const int ix) {
3708 if (!CI->isLosslessCast())
3709 return false;
3710
Philip Reames1a1bdb22014-12-02 18:50:36 +00003711 // If this is a GC intrinsic, avoid munging types. We need types for
3712 // statepoint reconstruction in SelectionDAG.
3713 // TODO: This is probably something which should be expanded to all
3714 // intrinsics since the entire point of intrinsics is that
3715 // they are understandable by the optimizer.
3716 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
3717 return false;
3718
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003719 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003720 // can't change to a type with a different size. If the size were
3721 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003722 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003723 return true;
3724
Jim Grosbach7815f562012-02-03 00:07:04 +00003725 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003726 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00003727 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003728 if (!SrcTy->isSized() || !DstTy->isSized())
3729 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003730 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003731 return false;
3732 return true;
3733}
3734
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003735Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00003736 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003737
Chandler Carruthba4c5172015-01-21 11:23:40 +00003738 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003739 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003740 };
Justin Bogner99798402016-08-05 01:06:44 +00003741 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003742 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00003743 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00003744 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00003745 }
Meador Ingedf796f82012-10-13 16:45:24 +00003746
Craig Topperf40110f2014-04-25 05:29:35 +00003747 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003748}
3749
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003750static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003751 // Strip off at most one level of pointer casts, looking for an alloca. This
3752 // is good enough in practice and simpler than handling any number of casts.
3753 Value *Underlying = TrampMem->stripPointerCasts();
3754 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00003755 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00003756 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003757 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00003758 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003759
Craig Topperf40110f2014-04-25 05:29:35 +00003760 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003761 for (User *U : TrampMem->users()) {
3762 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00003763 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00003764 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003765 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3766 if (InitTrampoline)
3767 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00003768 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003769 InitTrampoline = II;
3770 continue;
3771 }
3772 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3773 // Allow any number of calls to adjust.trampoline.
3774 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00003775 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003776 }
3777
3778 // No call to init.trampoline found.
3779 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003780 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003781
3782 // Check that the alloca is being used in the expected way.
3783 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00003784 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003785
3786 return InitTrampoline;
3787}
3788
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003789static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00003790 Value *TrampMem) {
3791 // Visit all the previous instructions in the basic block, and try to find a
3792 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003793 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3794 E = AdjustTramp->getParent()->begin();
3795 I != E;) {
3796 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00003797 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3798 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3799 II->getOperand(0) == TrampMem)
3800 return II;
3801 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00003802 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003803 }
Craig Topperf40110f2014-04-25 05:29:35 +00003804 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003805}
3806
3807// Given a call to llvm.adjust.trampoline, find and return the corresponding
3808// call to llvm.init.trampoline if the call to the trampoline can be optimized
3809// to a direct call to a function. Otherwise return NULL.
3810//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003811static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003812 Callee = Callee->stripPointerCasts();
3813 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3814 if (!AdjustTramp ||
3815 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003816 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003817
3818 Value *TrampMem = AdjustTramp->getOperand(0);
3819
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003820 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003821 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003822 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003823 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00003824 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003825}
3826
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003827/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003828Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00003829 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00003830 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00003831
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003832 bool Changed = false;
3833
Philip Reamesc25df112015-06-16 20:24:25 +00003834 // Mark any parameters that are known to be non-null with the nonnull
3835 // attribute. This is helpful for inlining calls to functions with null
3836 // checks on their arguments.
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003837 SmallVector<unsigned, 4> ArgNos;
Philip Reamesc25df112015-06-16 20:24:25 +00003838 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00003839
Philip Reamesc25df112015-06-16 20:24:25 +00003840 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00003841 if (V->getType()->isPointerTy() &&
Reid Klecknerfb502d22017-04-14 20:19:02 +00003842 !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00003843 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003844 ArgNos.push_back(ArgNo);
Philip Reamesc25df112015-06-16 20:24:25 +00003845 ArgNo++;
3846 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00003847
Philip Reamesc25df112015-06-16 20:24:25 +00003848 assert(ArgNo == CS.arg_size() && "sanity check");
3849
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003850 if (!ArgNos.empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00003851 AttributeList AS = CS.getAttributes();
Akira Hatanaka237916b2015-12-02 06:58:49 +00003852 LLVMContext &Ctx = CS.getInstruction()->getContext();
Reid Kleckner5fbdd172017-05-31 19:23:09 +00003853 AS = AS.addParamAttribute(Ctx, ArgNos,
3854 Attribute::get(Ctx, Attribute::NonNull));
Akira Hatanaka237916b2015-12-02 06:58:49 +00003855 CS.setAttributes(AS);
3856 Changed = true;
3857 }
3858
Chris Lattner73989652010-12-20 08:25:06 +00003859 // If the callee is a pointer to a function, attempt to move any casts to the
3860 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003861 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00003862 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00003863 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003864
Justin Lebar9d943972016-03-14 20:18:54 +00003865 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
3866 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00003867 if (CS.isConvergent() && !CalleeF->isConvergent() &&
3868 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00003869 DEBUG(dbgs() << "Removing convergent attr from instr "
3870 << CS.getInstruction() << "\n");
3871 CS.setNotConvergent();
3872 return CS.getInstruction();
3873 }
3874
Chris Lattner846a52e2010-02-01 18:11:34 +00003875 // If the call and callee calling conventions don't match, this call must
3876 // be unreachable, as the call is undefined.
3877 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
3878 // Only do this for calls to a function with a body. A prototype may
3879 // not actually end up matching the implementation's calling conv for a
3880 // variety of reasons (e.g. it may be written in assembly).
3881 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003882 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003883 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00003884 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003885 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00003886 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003887 // This allows ValueHandlers and custom metadata to adjust itself.
3888 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003889 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00003890 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00003891 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00003892
Chris Lattner2cecedf2010-02-01 18:04:58 +00003893 // We cannot remove an invoke, because it would change the CFG, just
3894 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00003895 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00003896 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00003897 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003898 }
Justin Lebar9d943972016-03-14 20:18:54 +00003899 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003900
3901 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00003902 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003903 // This allows ValueHandlers and custom metadata to adjust itself.
3904 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003905 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003906 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003907
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003908 if (isa<InvokeInst>(CS.getInstruction())) {
3909 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00003910 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003911 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003912
3913 // This instruction is not reachable, just remove it. We insert a store to
3914 // undef so that we know that this code is not reachable, despite the fact
3915 // that we can't modify the CFG here.
3916 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3917 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3918 CS.getInstruction());
3919
Sanjay Patel4b198802016-02-01 22:23:39 +00003920 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003921 }
3922
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003923 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00003924 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003925
Chris Lattner229907c2011-07-18 04:54:35 +00003926 PointerType *PTy = cast<PointerType>(Callee->getType());
3927 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003928 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00003929 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003930 // See if we can optimize any arguments passed through the varargs area of
3931 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003932 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003933 E = CS.arg_end(); I != E; ++I, ++ix) {
3934 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003935 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003936 *I = CI->getOperand(0);
3937 Changed = true;
3938 }
3939 }
3940 }
3941
3942 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
3943 // Inline asm calls cannot throw - mark them 'nounwind'.
3944 CS.setDoesNotThrow();
3945 Changed = true;
3946 }
3947
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003948 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00003949 // this. None of these calls are seen as possibly dead so go ahead and
3950 // delete the instruction now.
3951 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003952 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00003953 // If we changed something return the result, etc. Otherwise let
3954 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00003955 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00003956 }
3957
Craig Topperf40110f2014-04-25 05:29:35 +00003958 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003959}
3960
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003961/// If the callee is a constexpr cast of a function, attempt to move the cast to
3962/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003963bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00003964 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00003965 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003966 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003967
3968 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00003969 if (Callee->hasFnAttribute("thunk"))
3970 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003971
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003972 Instruction *Caller = CS.getInstruction();
Reid Klecknerb5180542017-03-21 16:57:19 +00003973 const AttributeList &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003974
3975 // Okay, this is a cast from a function to a different type. Unless doing so
3976 // would cause a type conversion of one of our arguments, change this call to
3977 // be a direct call with arguments casted to the appropriate types.
3978 //
Chris Lattner229907c2011-07-18 04:54:35 +00003979 FunctionType *FT = Callee->getFunctionType();
3980 Type *OldRetTy = Caller->getType();
3981 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003982
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003983 // Check to see if we are changing the return type...
3984 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00003985
3986 if (NewRetTy->isStructTy())
3987 return false; // TODO: Handle multiple return values.
3988
David Majnemer9b6b8222015-01-06 08:41:31 +00003989 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003990 if (Callee->isDeclaration())
3991 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003992
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003993 if (!Caller->use_empty() &&
3994 // void -> non-void is handled specially
3995 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00003996 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003997 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003998
3999 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Reid Klecknerb5180542017-03-21 16:57:19 +00004000 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00004001 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004002 return false; // Attribute not compatible with transformed value.
4003 }
4004
4005 // If the callsite is an invoke instruction, and the return value is used by
4006 // a PHI node in a successor, we cannot change the return type of the call
4007 // because there is no place to put the cast instruction (without breaking
4008 // the critical edge). Bail out in this case.
4009 if (!Caller->use_empty())
4010 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00004011 for (User *U : II->users())
4012 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004013 if (PN->getParent() == II->getNormalDest() ||
4014 PN->getParent() == II->getUnwindDest())
4015 return false;
4016 }
4017
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004018 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004019 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4020
David Majnemer9b6b8222015-01-06 08:41:31 +00004021 // Prevent us turning:
4022 // declare void @takes_i32_inalloca(i32* inalloca)
4023 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4024 //
4025 // into:
4026 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00004027 //
4028 // Similarly, avoid folding away bitcasts of byval calls.
4029 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4030 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00004031 return false;
4032
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004033 CallSite::arg_iterator AI = CS.arg_begin();
4034 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004035 Type *ParamTy = FT->getParamType(i);
4036 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004037
David Majnemer9b6b8222015-01-06 08:41:31 +00004038 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004039 return false; // Cannot transform this parameter value.
4040
Reid Klecknerf021fab2017-04-13 23:12:13 +00004041 if (AttrBuilder(CallerPAL.getParamAttributes(i))
4042 .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004043 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00004044
Reid Kleckner26af2ca2014-01-28 02:38:36 +00004045 if (CS.isInAllocaArgument(i))
4046 return false; // Cannot transform to and from inalloca.
4047
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004048 // If the parameter is passed as a byval argument, then we have to have a
4049 // sized type and the sized type has to have the same size as the old type.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004050 if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00004051 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004052 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004053 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00004054
Matt Arsenaultfa252722013-09-27 22:18:51 +00004055 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00004056 if (DL.getTypeAllocSize(CurElTy) !=
4057 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00004058 return false;
4059 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004060 }
4061
Chris Lattneradf38b32011-02-24 05:10:56 +00004062 if (Callee->isDeclaration()) {
4063 // Do not delete arguments unless we have a function body.
4064 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4065 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004066
Chris Lattneradf38b32011-02-24 05:10:56 +00004067 // If the callee is just a declaration, don't change the varargsness of the
4068 // call. We don't want to introduce a varargs call where one doesn't
4069 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00004070 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00004071 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4072 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004073
4074 // If both the callee and the cast type are varargs, we still have to make
4075 // sure the number of fixed parameters are the same or we have the same
4076 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00004077 if (FT->isVarArg() &&
4078 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4079 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00004080 cast<FunctionType>(APTy->getElementType())->getNumParams())
4081 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00004082 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004083
Jim Grosbach0ab54182012-02-03 00:00:50 +00004084 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004085 !CallerPAL.isEmpty()) {
Jim Grosbach0ab54182012-02-03 00:00:50 +00004086 // In this case we have more arguments than the new function type, but we
4087 // won't be dropping them. Check that these extra arguments have attributes
4088 // that are compatible with being a vararg call argument.
Reid Kleckneraa0cec72017-04-19 23:17:47 +00004089 unsigned SRetIdx;
4090 if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4091 SRetIdx > FT->getNumParams())
4092 return false;
4093 }
Jim Grosbach7815f562012-02-03 00:07:04 +00004094
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004095 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00004096 // inserting cast instructions as necessary.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004097 SmallVector<Value *, 8> Args;
4098 SmallVector<AttributeSet, 8> ArgAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004099 Args.reserve(NumActualArgs);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004100 ArgAttrs.reserve(NumActualArgs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004101
4102 // Get any return attributes.
Reid Klecknerb5180542017-03-21 16:57:19 +00004103 AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004104
4105 // If the return value is not being used, the type may not be compatible
4106 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00004107 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004108
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004109 AI = CS.arg_begin();
4110 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004111 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00004112
Reid Klecknerc3fae792017-04-13 18:11:03 +00004113 Value *NewArg = *AI;
4114 if ((*AI)->getType() != ParamTy)
4115 NewArg = Builder->CreateBitOrPointerCast(*AI, ParamTy);
4116 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004117
4118 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004119 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004120 }
4121
4122 // If the function takes more arguments than the call was taking, add them
4123 // now.
Reid Klecknerc3fae792017-04-13 18:11:03 +00004124 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004125 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Reid Klecknerc3fae792017-04-13 18:11:03 +00004126 ArgAttrs.push_back(AttributeSet());
4127 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004128
4129 // If we are removing arguments to the function, emit an obnoxious warning.
4130 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00004131 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4132 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004133 // Add all of the arguments in their promoted form to the arg list.
4134 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00004135 Type *PTy = getPromotedType((*AI)->getType());
Reid Klecknerc3fae792017-04-13 18:11:03 +00004136 Value *NewArg = *AI;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004137 if (PTy != (*AI)->getType()) {
4138 // Must promote to pass through va_arg area!
4139 Instruction::CastOps opcode =
4140 CastInst::getCastOpcode(*AI, false, PTy, false);
Reid Klecknerc3fae792017-04-13 18:11:03 +00004141 NewArg = Builder->CreateCast(opcode, *AI, PTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004142 }
Reid Klecknerc3fae792017-04-13 18:11:03 +00004143 Args.push_back(NewArg);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004144
4145 // Add any parameter attributes.
Reid Klecknerf021fab2017-04-13 23:12:13 +00004146 ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004147 }
4148 }
4149 }
4150
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004151 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004152
4153 if (NewRetTy->isVoidTy())
4154 Caller->setName(""); // Void type should not have a name.
4155
Reid Klecknerc3fae792017-04-13 18:11:03 +00004156 assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4157 "missing argument attributes");
4158 LLVMContext &Ctx = Callee->getContext();
4159 AttributeList NewCallerPAL = AttributeList::get(
4160 Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004161
Sanjoy Das76293462015-11-25 00:42:19 +00004162 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00004163 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00004164
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004165 CallSite NewCS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004166 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004167 NewCS = Builder->CreateInvoke(Callee, II->getNormalDest(),
4168 II->getUnwindDest(), Args, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004169 } else {
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004170 NewCS = Builder->CreateCall(Callee, Args, OpBundles);
4171 cast<CallInst>(NewCS.getInstruction())
4172 ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004173 }
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004174 NewCS->takeName(Caller);
4175 NewCS.setCallingConv(CS.getCallingConv());
4176 NewCS.setAttributes(NewCallerPAL);
4177
4178 // Preserve the weight metadata for the new call instruction. The metadata
4179 // is used by SamplePGO to check callsite's hotness.
4180 uint64_t W;
4181 if (Caller->extractProfTotalWeight(W))
4182 NewCS->setProfWeight(W);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004183
4184 // Insert a cast of the return type as necessary.
Reid Kleckner257cb4e2017-04-13 20:26:38 +00004185 Instruction *NC = NewCS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004186 Value *NV = NC;
4187 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4188 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00004189 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00004190 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004191
4192 // If this is an invoke instruction, we should insert it after the first
4193 // non-phi, instruction in the normal successor block.
4194 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00004195 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004196 InsertNewInstBefore(NC, *I);
4197 } else {
Chris Lattner73989652010-12-20 08:25:06 +00004198 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004199 InsertNewInstBefore(NC, *Caller);
4200 }
4201 Worklist.AddUsersToWorkList(*Caller);
4202 } else {
4203 NV = UndefValue::get(Caller->getType());
4204 }
4205 }
4206
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004207 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00004208 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00004209 else if (Caller->hasValueHandle()) {
4210 if (OldRetTy == NV->getType())
4211 ValueHandleBase::ValueIsRAUWd(Caller, NV);
4212 else
4213 // We cannot call ValueIsRAUWd with a different type, and the
4214 // actual tracked value will disappear.
4215 ValueHandleBase::ValueIsDeleted(Caller);
4216 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00004217
Sanjay Patel4b198802016-02-01 22:23:39 +00004218 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004219 return true;
4220}
4221
Sanjay Patelcd4377c2016-01-20 22:24:38 +00004222/// Turn a call to a function created by init_trampoline / adjust_trampoline
4223/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00004224Instruction *
4225InstCombiner::transformCallThroughTrampoline(CallSite CS,
4226 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004227 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00004228 PointerType *PTy = cast<PointerType>(Callee->getType());
4229 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004230 AttributeList Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004231
4232 // If the call already has the 'nest' attribute somewhere then give up -
4233 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00004234 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00004235 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004236
Duncan Sandsa0984362011-09-06 13:37:06 +00004237 assert(Tramp &&
4238 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004239
Gabor Greif3e44ea12010-07-22 10:37:47 +00004240 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00004241 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004242
Reid Klecknereb9dd5b2017-04-10 23:31:05 +00004243 AttributeList NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004244 if (!NestAttrs.isEmpty()) {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004245 unsigned NestArgNo = 0;
Craig Topperf40110f2014-04-25 05:29:35 +00004246 Type *NestTy = nullptr;
Reid Klecknerc2cb5602017-04-12 00:38:00 +00004247 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004248
4249 // Look for a parameter marked with the 'nest' attribute.
4250 for (FunctionType::param_iterator I = NestFTy->param_begin(),
Reid Klecknerf021fab2017-04-13 23:12:13 +00004251 E = NestFTy->param_end();
4252 I != E; ++NestArgNo, ++I) {
4253 AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4254 if (AS.hasAttribute(Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004255 // Record the parameter type and any other attributes.
4256 NestTy = *I;
Reid Klecknerf021fab2017-04-13 23:12:13 +00004257 NestAttr = AS;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004258 break;
4259 }
Reid Klecknerf021fab2017-04-13 23:12:13 +00004260 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004261
4262 if (NestTy) {
4263 Instruction *Caller = CS.getInstruction();
4264 std::vector<Value*> NewArgs;
Reid Kleckner7f720332017-04-13 00:58:09 +00004265 std::vector<AttributeSet> NewArgAttrs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00004266 NewArgs.reserve(CS.arg_size() + 1);
Reid Kleckner7f720332017-04-13 00:58:09 +00004267 NewArgAttrs.reserve(CS.arg_size());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004268
4269 // Insert the nest argument into the call argument list, which may
4270 // mean appending it. Likewise for attributes.
4271
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004272 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004273 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004274 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4275 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004276 if (ArgNo == NestArgNo) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004277 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00004278 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004279 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00004280 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004281 NewArgs.push_back(NestVal);
Reid Kleckner7f720332017-04-13 00:58:09 +00004282 NewArgAttrs.push_back(NestAttr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004283 }
4284
4285 if (I == E)
4286 break;
4287
4288 // Add the original argument and attributes.
4289 NewArgs.push_back(*I);
Reid Klecknerf021fab2017-04-13 23:12:13 +00004290 NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004291
Reid Klecknerf021fab2017-04-13 23:12:13 +00004292 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004293 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004294 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004295 }
4296
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004297 // The trampoline may have been bitcast to a bogus type (FTy).
4298 // Handle this by synthesizing a new function type, equal to FTy
4299 // with the chain parameter inserted.
4300
Jay Foadb804a2b2011-07-12 14:06:48 +00004301 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004302 NewTypes.reserve(FTy->getNumParams()+1);
4303
4304 // Insert the chain's type into the list of parameter types, which may
4305 // mean appending it.
4306 {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004307 unsigned ArgNo = 0;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004308 FunctionType::param_iterator I = FTy->param_begin(),
4309 E = FTy->param_end();
4310
4311 do {
Reid Klecknerf021fab2017-04-13 23:12:13 +00004312 if (ArgNo == NestArgNo)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004313 // Add the chain's type.
4314 NewTypes.push_back(NestTy);
4315
4316 if (I == E)
4317 break;
4318
4319 // Add the original type.
4320 NewTypes.push_back(*I);
4321
Reid Klecknerf021fab2017-04-13 23:12:13 +00004322 ++ArgNo;
Richard Trieu7a083812016-02-18 22:09:30 +00004323 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004324 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004325 }
4326
4327 // Replace the trampoline call with a direct call. Let the generic
4328 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004329 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004330 FTy->isVarArg());
4331 Constant *NewCallee =
4332 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004333 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004334 PointerType::getUnqual(NewFTy));
Reid Kleckner7f720332017-04-13 00:58:09 +00004335 AttributeList NewPAL =
4336 AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4337 Attrs.getRetAttributes(), NewArgAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004338
David Majnemer231a68c2016-04-29 08:07:20 +00004339 SmallVector<OperandBundleDef, 1> OpBundles;
4340 CS.getOperandBundlesAsDefs(OpBundles);
4341
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004342 Instruction *NewCaller;
4343 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4344 NewCaller = InvokeInst::Create(NewCallee,
4345 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004346 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004347 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4348 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4349 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00004350 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004351 cast<CallInst>(NewCaller)->setTailCallKind(
4352 cast<CallInst>(Caller)->getTailCallKind());
4353 cast<CallInst>(NewCaller)->setCallingConv(
4354 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004355 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4356 }
Eli Friedman49346012011-05-18 19:57:14 +00004357
4358 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004359 }
4360 }
4361
4362 // Replace the trampoline call with a direct call. Since there is no 'nest'
4363 // parameter, there is no need to adjust the argument list. Let the generic
4364 // code sort out any function type mismatches.
4365 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00004366 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004367 ConstantExpr::getBitCast(NestF, PTy);
4368 CS.setCalledFunction(NewCallee);
4369 return CS.getInstruction();
4370}