blob: 23f8035e2aaf4efcd59e4040c5b5167f9d210063 [file] [log] [blame]
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000015#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/None.h"
Meador Ingee3f2b262012-11-30 04:05:06 +000019#include "llvm/ADT/Statistic.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000020#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/Twine.h"
David Majnemer15032582015-05-22 03:56:46 +000023#include "llvm/Analysis/InstructionSimplify.h"
Chris Lattner7a9e47a2010-01-05 07:32:13 +000024#include "llvm/Analysis/MemoryBuiltins.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000025#include "llvm/Analysis/ValueTracking.h"
26#include "llvm/IR/BasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000027#include "llvm/IR/CallSite.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000028#include "llvm/IR/Constant.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/DerivedTypes.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/GlobalVariable.h"
33#include "llvm/IR/InstrTypes.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
36#include "llvm/IR/IntrinsicInst.h"
37#include "llvm/IR/Intrinsics.h"
38#include "llvm/IR/LLVMContext.h"
39#include "llvm/IR/Metadata.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000040#include "llvm/IR/PatternMatch.h"
Philip Reames1a1bdb22014-12-02 18:50:36 +000041#include "llvm/IR/Statepoint.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000042#include "llvm/IR/Type.h"
43#include "llvm/IR/Value.h"
44#include "llvm/IR/ValueHandle.h"
45#include "llvm/Support/Casting.h"
46#include "llvm/Support/Debug.h"
47#include "llvm/Support/MathExtras.h"
Chris Lattner6fcd32e2010-12-25 20:37:57 +000048#include "llvm/Transforms/Utils/Local.h"
Chandler Carruthba4c5172015-01-21 11:23:40 +000049#include "llvm/Transforms/Utils/SimplifyLibCalls.h"
Eugene Zelenkocdc71612016-08-11 17:20:18 +000050#include <algorithm>
51#include <cassert>
52#include <cstdint>
53#include <cstring>
54#include <vector>
55
Chris Lattner7a9e47a2010-01-05 07:32:13 +000056using namespace llvm;
Michael Ilseman536cc322012-12-13 03:13:36 +000057using namespace PatternMatch;
Chris Lattner7a9e47a2010-01-05 07:32:13 +000058
Chandler Carruth964daaa2014-04-22 02:55:47 +000059#define DEBUG_TYPE "instcombine"
60
Meador Ingee3f2b262012-11-30 04:05:06 +000061STATISTIC(NumSimplified, "Number of library calls simplified");
62
Igor Laevsky900ffa32017-02-08 14:32:04 +000063static cl::opt<uint64_t> UnfoldElementAtomicMemcpyMaxElements(
64 "unfold-element-atomic-memcpy-max-elements",
65 cl::init(16),
66 cl::desc("Maximum number of elements in atomic memcpy the optimizer is "
67 "allowed to unfold"));
68
Sanjay Patelcd4377c2016-01-20 22:24:38 +000069/// Return the specified type promoted as it would be to pass though a va_arg
70/// area.
Chris Lattner229907c2011-07-18 04:54:35 +000071static Type *getPromotedType(Type *Ty) {
72 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +000073 if (ITy->getBitWidth() < 32)
74 return Type::getInt32Ty(Ty->getContext());
75 }
76 return Ty;
77}
78
Sanjay Patelcd4377c2016-01-20 22:24:38 +000079/// Given an aggregate type which ultimately holds a single scalar element,
80/// like {{{type}}} or [1 x type], return type.
Dan Gohmand0080c42012-09-13 18:19:06 +000081static Type *reduceToSingleValueType(Type *T) {
82 while (!T->isSingleValueType()) {
83 if (StructType *STy = dyn_cast<StructType>(T)) {
84 if (STy->getNumElements() == 1)
85 T = STy->getElementType(0);
86 else
87 break;
88 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
89 if (ATy->getNumElements() == 1)
90 T = ATy->getElementType();
91 else
92 break;
93 } else
94 break;
95 }
96
97 return T;
98}
Chris Lattner7a9e47a2010-01-05 07:32:13 +000099
Sanjay Patel368ac5d2016-02-21 17:29:33 +0000100/// Return a constant boolean vector that has true elements in all positions
Sanjay Patel24401302016-02-21 17:33:31 +0000101/// where the input constant data vector has an element with the sign bit set.
Sanjay Patel368ac5d2016-02-21 17:29:33 +0000102static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
103 SmallVector<Constant *, 32> BoolVec;
104 IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
105 for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
106 Constant *Elt = V->getElementAsConstant(I);
107 assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
108 "Unexpected constant data vector element type");
109 bool Sign = V->getElementType()->isIntegerTy()
110 ? cast<ConstantInt>(Elt)->isNegative()
111 : cast<ConstantFP>(Elt)->isNegative();
112 BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
113 }
114 return ConstantVector::get(BoolVec);
115}
116
Igor Laevsky900ffa32017-02-08 14:32:04 +0000117Instruction *
118InstCombiner::SimplifyElementAtomicMemCpy(ElementAtomicMemCpyInst *AMI) {
119 // Try to unfold this intrinsic into sequence of explicit atomic loads and
120 // stores.
121 // First check that number of elements is compile time constant.
122 auto *NumElementsCI = dyn_cast<ConstantInt>(AMI->getNumElements());
123 if (!NumElementsCI)
124 return nullptr;
125
126 // Check that there are not too many elements.
127 uint64_t NumElements = NumElementsCI->getZExtValue();
128 if (NumElements >= UnfoldElementAtomicMemcpyMaxElements)
129 return nullptr;
130
131 // Don't unfold into illegal integers
132 uint64_t ElementSizeInBytes = AMI->getElementSizeInBytes() * 8;
133 if (!getDataLayout().isLegalInteger(ElementSizeInBytes))
134 return nullptr;
135
136 // Cast source and destination to the correct type. Intrinsic input arguments
137 // are usually represented as i8*.
138 // Often operands will be explicitly casted to i8* and we can just strip
139 // those casts instead of inserting new ones. However it's easier to rely on
140 // other InstCombine rules which will cover trivial cases anyway.
141 Value *Src = AMI->getRawSource();
142 Value *Dst = AMI->getRawDest();
143 Type *ElementPointerType = Type::getIntNPtrTy(
144 AMI->getContext(), ElementSizeInBytes, Src->getType()->getPointerAddressSpace());
145
146 Value *SrcCasted = Builder->CreatePointerCast(Src, ElementPointerType,
147 "memcpy_unfold.src_casted");
148 Value *DstCasted = Builder->CreatePointerCast(Dst, ElementPointerType,
149 "memcpy_unfold.dst_casted");
150
151 for (uint64_t i = 0; i < NumElements; ++i) {
152 // Get current element addresses
153 ConstantInt *ElementIdxCI =
154 ConstantInt::get(AMI->getContext(), APInt(64, i));
155 Value *SrcElementAddr =
156 Builder->CreateGEP(SrcCasted, ElementIdxCI, "memcpy_unfold.src_addr");
157 Value *DstElementAddr =
158 Builder->CreateGEP(DstCasted, ElementIdxCI, "memcpy_unfold.dst_addr");
159
160 // Load from the source. Transfer alignment information and mark load as
161 // unordered atomic.
162 LoadInst *Load = Builder->CreateLoad(SrcElementAddr, "memcpy_unfold.val");
163 Load->setOrdering(AtomicOrdering::Unordered);
164 // We know alignment of the first element. It is also guaranteed by the
165 // verifier that element size is less or equal than first element alignment
166 // and both of this values are powers of two.
167 // This means that all subsequent accesses are at least element size
168 // aligned.
169 // TODO: We can infer better alignment but there is no evidence that this
170 // will matter.
171 Load->setAlignment(i == 0 ? AMI->getSrcAlignment()
172 : AMI->getElementSizeInBytes());
173 Load->setDebugLoc(AMI->getDebugLoc());
174
175 // Store loaded value via unordered atomic store.
176 StoreInst *Store = Builder->CreateStore(Load, DstElementAddr);
177 Store->setOrdering(AtomicOrdering::Unordered);
178 Store->setAlignment(i == 0 ? AMI->getDstAlignment()
179 : AMI->getElementSizeInBytes());
180 Store->setDebugLoc(AMI->getDebugLoc());
181 }
182
183 // Set the number of elements of the copy to 0, it will be deleted on the
184 // next iteration.
185 AMI->setNumElements(Constant::getNullValue(NumElementsCI->getType()));
186 return AMI;
187}
188
Pete Cooper67cf9a72015-11-19 05:56:52 +0000189Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000190 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
191 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000192 unsigned MinAlign = std::min(DstAlign, SrcAlign);
193 unsigned CopyAlign = MI->getAlignment();
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000194
Pete Cooper67cf9a72015-11-19 05:56:52 +0000195 if (CopyAlign < MinAlign) {
196 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000197 return MI;
198 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000199
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000200 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
201 // load/store.
Gabor Greif0a136c92010-06-24 13:54:33 +0000202 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Craig Topperf40110f2014-04-25 05:29:35 +0000203 if (!MemOpLength) return nullptr;
Jim Grosbach7815f562012-02-03 00:07:04 +0000204
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000205 // Source and destination pointer types are always "i8*" for intrinsic. See
206 // if the size is something we can handle with a single primitive load/store.
207 // A single load+store correctly handles overlapping memory in the memmove
208 // case.
Michael Liao69e172a2012-08-15 03:49:59 +0000209 uint64_t Size = MemOpLength->getLimitedValue();
Alp Tokercb402912014-01-24 17:20:08 +0000210 assert(Size && "0-sized memory transferring should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000211
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000212 if (Size > 8 || (Size&(Size-1)))
Craig Topperf40110f2014-04-25 05:29:35 +0000213 return nullptr; // If not 1/2/4/8 bytes, exit.
Jim Grosbach7815f562012-02-03 00:07:04 +0000214
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000215 // Use an integer load+store unless we can find something better.
Mon P Wangc576ee92010-04-04 03:10:48 +0000216 unsigned SrcAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000217 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greiff3755202010-04-16 15:33:14 +0000218 unsigned DstAddrSp =
Gabor Greif0a136c92010-06-24 13:54:33 +0000219 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wangc576ee92010-04-04 03:10:48 +0000220
Chris Lattner229907c2011-07-18 04:54:35 +0000221 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wangc576ee92010-04-04 03:10:48 +0000222 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
223 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach7815f562012-02-03 00:07:04 +0000224
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000225 // Memcpy forces the use of i8* for the source and destination. That means
226 // that if you're using memcpy to move one double around, you'll get a cast
227 // from double* to i8*. We'd much rather use a double load+store rather than
228 // an i64 load+store, here because this improves the odds that the source or
229 // dest address will be promotable. See if we can find a better type than the
230 // integer datatype.
Gabor Greif589a0b92010-06-24 12:58:35 +0000231 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Craig Topperf40110f2014-04-25 05:29:35 +0000232 MDNode *CopyMD = nullptr;
Gabor Greif589a0b92010-06-24 12:58:35 +0000233 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000234 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000235 ->getElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000236 if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000237 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
238 // down through these levels if so.
Dan Gohmand0080c42012-09-13 18:19:06 +0000239 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach7815f562012-02-03 00:07:04 +0000240
Mon P Wangc576ee92010-04-04 03:10:48 +0000241 if (SrcETy->isSingleValueType()) {
242 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
243 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohman3f553c22012-09-13 21:51:01 +0000244
245 // If the memcpy has metadata describing the members, see if we can
246 // get the TBAA tag describing our copy.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000247 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000248 if (M->getNumOperands() == 3 && M->getOperand(0) &&
249 mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
250 mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky49ac81a2012-10-11 02:05:23 +0000251 M->getOperand(1) &&
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000252 mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
253 mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
254 Size &&
255 M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
Dan Gohman3f553c22012-09-13 21:51:01 +0000256 CopyMD = cast<MDNode>(M->getOperand(2));
257 }
Mon P Wangc576ee92010-04-04 03:10:48 +0000258 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000259 }
260 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000261
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000262 // If the memcpy/memmove provides better alignment info than we can
263 // infer, use it.
Pete Cooper67cf9a72015-11-19 05:56:52 +0000264 SrcAlign = std::max(SrcAlign, CopyAlign);
265 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach7815f562012-02-03 00:07:04 +0000266
Gabor Greif5f3e6562010-06-25 07:57:14 +0000267 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
268 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman49346012011-05-18 19:57:14 +0000269 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
270 L->setAlignment(SrcAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000271 if (CopyMD)
272 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000273 MDNode *LoopMemParallelMD =
274 MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
275 if (LoopMemParallelMD)
276 L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Dorit Nuzman7673ba72016-09-04 07:06:00 +0000277
Eli Friedman49346012011-05-18 19:57:14 +0000278 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
279 S->setAlignment(DstAlign);
Dan Gohman3f553c22012-09-13 21:51:01 +0000280 if (CopyMD)
281 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Dorit Nuzmanabd15f62016-09-04 07:49:39 +0000282 if (LoopMemParallelMD)
283 S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000284
285 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greif5b1370e2010-06-28 16:50:57 +0000286 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000287 return MI;
288}
289
290Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000291 unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
Pete Cooper67cf9a72015-11-19 05:56:52 +0000292 if (MI->getAlignment() < Alignment) {
293 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
294 Alignment, false));
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000295 return MI;
296 }
Jim Grosbach7815f562012-02-03 00:07:04 +0000297
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000298 // Extract the length and alignment and fill if they are constant.
299 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
300 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sands9dff9be2010-02-15 16:12:20 +0000301 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Craig Topperf40110f2014-04-25 05:29:35 +0000302 return nullptr;
Michael Liao69e172a2012-08-15 03:49:59 +0000303 uint64_t Len = LenC->getLimitedValue();
Pete Cooper67cf9a72015-11-19 05:56:52 +0000304 Alignment = MI->getAlignment();
Michael Liao69e172a2012-08-15 03:49:59 +0000305 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach7815f562012-02-03 00:07:04 +0000306
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000307 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
308 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattner229907c2011-07-18 04:54:35 +0000309 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach7815f562012-02-03 00:07:04 +0000310
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000311 Value *Dest = MI->getDest();
Mon P Wang1991c472010-12-20 01:05:30 +0000312 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
313 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
314 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000315
316 // Alignment 0 is identity for alignment 1 for memset, but not store.
317 if (Alignment == 0) Alignment = 1;
Jim Grosbach7815f562012-02-03 00:07:04 +0000318
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000319 // Extract the fill value and store.
320 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman49346012011-05-18 19:57:14 +0000321 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
322 MI->isVolatile());
323 S->setAlignment(Alignment);
Jim Grosbach7815f562012-02-03 00:07:04 +0000324
Chris Lattner7a9e47a2010-01-05 07:32:13 +0000325 // Set the size of the copy to 0, it will be deleted on the next iteration.
326 MI->setLength(Constant::getNullValue(LenC->getType()));
327 return MI;
328 }
329
Simon Pilgrim18617d12015-08-05 08:18:00 +0000330 return nullptr;
331}
332
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000333static Value *simplifyX86immShift(const IntrinsicInst &II,
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000334 InstCombiner::BuilderTy &Builder) {
335 bool LogicalShift = false;
336 bool ShiftLeft = false;
337
338 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000339 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000340 case Intrinsic::x86_sse2_psra_d:
341 case Intrinsic::x86_sse2_psra_w:
342 case Intrinsic::x86_sse2_psrai_d:
343 case Intrinsic::x86_sse2_psrai_w:
344 case Intrinsic::x86_avx2_psra_d:
345 case Intrinsic::x86_avx2_psra_w:
346 case Intrinsic::x86_avx2_psrai_d:
347 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000348 case Intrinsic::x86_avx512_psra_q_128:
349 case Intrinsic::x86_avx512_psrai_q_128:
350 case Intrinsic::x86_avx512_psra_q_256:
351 case Intrinsic::x86_avx512_psrai_q_256:
352 case Intrinsic::x86_avx512_psra_d_512:
353 case Intrinsic::x86_avx512_psra_q_512:
354 case Intrinsic::x86_avx512_psra_w_512:
355 case Intrinsic::x86_avx512_psrai_d_512:
356 case Intrinsic::x86_avx512_psrai_q_512:
357 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000358 LogicalShift = false; ShiftLeft = false;
359 break;
360 case Intrinsic::x86_sse2_psrl_d:
361 case Intrinsic::x86_sse2_psrl_q:
362 case Intrinsic::x86_sse2_psrl_w:
363 case Intrinsic::x86_sse2_psrli_d:
364 case Intrinsic::x86_sse2_psrli_q:
365 case Intrinsic::x86_sse2_psrli_w:
366 case Intrinsic::x86_avx2_psrl_d:
367 case Intrinsic::x86_avx2_psrl_q:
368 case Intrinsic::x86_avx2_psrl_w:
369 case Intrinsic::x86_avx2_psrli_d:
370 case Intrinsic::x86_avx2_psrli_q:
371 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000372 case Intrinsic::x86_avx512_psrl_d_512:
373 case Intrinsic::x86_avx512_psrl_q_512:
374 case Intrinsic::x86_avx512_psrl_w_512:
375 case Intrinsic::x86_avx512_psrli_d_512:
376 case Intrinsic::x86_avx512_psrli_q_512:
377 case Intrinsic::x86_avx512_psrli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000378 LogicalShift = true; ShiftLeft = false;
379 break;
380 case Intrinsic::x86_sse2_psll_d:
381 case Intrinsic::x86_sse2_psll_q:
382 case Intrinsic::x86_sse2_psll_w:
383 case Intrinsic::x86_sse2_pslli_d:
384 case Intrinsic::x86_sse2_pslli_q:
385 case Intrinsic::x86_sse2_pslli_w:
386 case Intrinsic::x86_avx2_psll_d:
387 case Intrinsic::x86_avx2_psll_q:
388 case Intrinsic::x86_avx2_psll_w:
389 case Intrinsic::x86_avx2_pslli_d:
390 case Intrinsic::x86_avx2_pslli_q:
391 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +0000392 case Intrinsic::x86_avx512_psll_d_512:
393 case Intrinsic::x86_avx512_psll_q_512:
394 case Intrinsic::x86_avx512_psll_w_512:
395 case Intrinsic::x86_avx512_pslli_d_512:
396 case Intrinsic::x86_avx512_pslli_q_512:
397 case Intrinsic::x86_avx512_pslli_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +0000398 LogicalShift = true; ShiftLeft = true;
399 break;
400 }
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000401 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
402
Simon Pilgrim3815c162015-08-07 18:22:50 +0000403 // Simplify if count is constant.
404 auto Arg1 = II.getArgOperand(1);
405 auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
406 auto CDV = dyn_cast<ConstantDataVector>(Arg1);
407 auto CInt = dyn_cast<ConstantInt>(Arg1);
408 if (!CAZ && !CDV && !CInt)
Simon Pilgrim18617d12015-08-05 08:18:00 +0000409 return nullptr;
Simon Pilgrim3815c162015-08-07 18:22:50 +0000410
411 APInt Count(64, 0);
412 if (CDV) {
413 // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
414 // operand to compute the shift amount.
415 auto VT = cast<VectorType>(CDV->getType());
416 unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
417 assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
418 unsigned NumSubElts = 64 / BitWidth;
419
420 // Concatenate the sub-elements to create the 64-bit value.
421 for (unsigned i = 0; i != NumSubElts; ++i) {
422 unsigned SubEltIdx = (NumSubElts - 1) - i;
423 auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
424 Count = Count.shl(BitWidth);
425 Count |= SubElt->getValue().zextOrTrunc(64);
426 }
427 }
428 else if (CInt)
429 Count = CInt->getValue();
Simon Pilgrim18617d12015-08-05 08:18:00 +0000430
431 auto Vec = II.getArgOperand(0);
432 auto VT = cast<VectorType>(Vec->getType());
433 auto SVT = VT->getElementType();
Simon Pilgrim3815c162015-08-07 18:22:50 +0000434 unsigned VWidth = VT->getNumElements();
435 unsigned BitWidth = SVT->getPrimitiveSizeInBits();
436
437 // If shift-by-zero then just return the original value.
438 if (Count == 0)
439 return Vec;
440
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000441 // Handle cases when Shift >= BitWidth.
442 if (Count.uge(BitWidth)) {
443 // If LogicalShift - just return zero.
444 if (LogicalShift)
445 return ConstantAggregateZero::get(VT);
446
447 // If ArithmeticShift - clamp Shift to (BitWidth - 1).
448 Count = APInt(64, BitWidth - 1);
449 }
Simon Pilgrim18617d12015-08-05 08:18:00 +0000450
Simon Pilgrim18617d12015-08-05 08:18:00 +0000451 // Get a constant vector of the same type as the first operand.
Simon Pilgrim3815c162015-08-07 18:22:50 +0000452 auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
453 auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000454
455 if (ShiftLeft)
Simon Pilgrim3815c162015-08-07 18:22:50 +0000456 return Builder.CreateShl(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000457
Simon Pilgrima3a72b42015-08-10 20:21:15 +0000458 if (LogicalShift)
459 return Builder.CreateLShr(Vec, ShiftVec);
460
461 return Builder.CreateAShr(Vec, ShiftVec);
Simon Pilgrim18617d12015-08-05 08:18:00 +0000462}
463
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000464// Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
465// Unlike the generic IR shifts, the intrinsics have defined behaviour for out
466// of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
467static Value *simplifyX86varShift(const IntrinsicInst &II,
468 InstCombiner::BuilderTy &Builder) {
469 bool LogicalShift = false;
470 bool ShiftLeft = false;
471
472 switch (II.getIntrinsicID()) {
Craig Topperb4173a52016-11-13 07:26:19 +0000473 default: llvm_unreachable("Unexpected intrinsic!");
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000474 case Intrinsic::x86_avx2_psrav_d:
475 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000476 case Intrinsic::x86_avx512_psrav_q_128:
477 case Intrinsic::x86_avx512_psrav_q_256:
478 case Intrinsic::x86_avx512_psrav_d_512:
479 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000480 case Intrinsic::x86_avx512_psrav_w_128:
481 case Intrinsic::x86_avx512_psrav_w_256:
482 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000483 LogicalShift = false;
484 ShiftLeft = false;
485 break;
486 case Intrinsic::x86_avx2_psrlv_d:
487 case Intrinsic::x86_avx2_psrlv_d_256:
488 case Intrinsic::x86_avx2_psrlv_q:
489 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000490 case Intrinsic::x86_avx512_psrlv_d_512:
491 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000492 case Intrinsic::x86_avx512_psrlv_w_128:
493 case Intrinsic::x86_avx512_psrlv_w_256:
494 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000495 LogicalShift = true;
496 ShiftLeft = false;
497 break;
498 case Intrinsic::x86_avx2_psllv_d:
499 case Intrinsic::x86_avx2_psllv_d_256:
500 case Intrinsic::x86_avx2_psllv_q:
501 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +0000502 case Intrinsic::x86_avx512_psllv_d_512:
503 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +0000504 case Intrinsic::x86_avx512_psllv_w_128:
505 case Intrinsic::x86_avx512_psllv_w_256:
506 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000507 LogicalShift = true;
508 ShiftLeft = true;
509 break;
510 }
511 assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
512
513 // Simplify if all shift amounts are constant/undef.
514 auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
515 if (!CShift)
516 return nullptr;
517
518 auto Vec = II.getArgOperand(0);
519 auto VT = cast<VectorType>(II.getType());
520 auto SVT = VT->getVectorElementType();
521 int NumElts = VT->getNumElements();
522 int BitWidth = SVT->getIntegerBitWidth();
523
524 // Collect each element's shift amount.
525 // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
526 bool AnyOutOfRange = false;
527 SmallVector<int, 8> ShiftAmts;
528 for (int I = 0; I < NumElts; ++I) {
529 auto *CElt = CShift->getAggregateElement(I);
530 if (CElt && isa<UndefValue>(CElt)) {
531 ShiftAmts.push_back(-1);
532 continue;
533 }
534
535 auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
536 if (!COp)
537 return nullptr;
538
539 // Handle out of range shifts.
540 // If LogicalShift - set to BitWidth (special case).
541 // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
542 APInt ShiftVal = COp->getValue();
543 if (ShiftVal.uge(BitWidth)) {
544 AnyOutOfRange = LogicalShift;
545 ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
546 continue;
547 }
548
549 ShiftAmts.push_back((int)ShiftVal.getZExtValue());
550 }
551
552 // If all elements out of range or UNDEF, return vector of zeros/undefs.
553 // ArithmeticShift should only hit this if they are all UNDEF.
554 auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
Eugene Zelenkocdc71612016-08-11 17:20:18 +0000555 if (all_of(ShiftAmts, OutOfRange)) {
Simon Pilgrimdb9893f2016-06-07 10:27:15 +0000556 SmallVector<Constant *, 8> ConstantVec;
557 for (int Idx : ShiftAmts) {
558 if (Idx < 0) {
559 ConstantVec.push_back(UndefValue::get(SVT));
560 } else {
561 assert(LogicalShift && "Logical shift expected");
562 ConstantVec.push_back(ConstantInt::getNullValue(SVT));
563 }
564 }
565 return ConstantVector::get(ConstantVec);
566 }
567
568 // We can't handle only some out of range values with generic logical shifts.
569 if (AnyOutOfRange)
570 return nullptr;
571
572 // Build the shift amount constant vector.
573 SmallVector<Constant *, 8> ShiftVecAmts;
574 for (int Idx : ShiftAmts) {
575 if (Idx < 0)
576 ShiftVecAmts.push_back(UndefValue::get(SVT));
577 else
578 ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
579 }
580 auto ShiftVec = ConstantVector::get(ShiftVecAmts);
581
582 if (ShiftLeft)
583 return Builder.CreateShl(Vec, ShiftVec);
584
585 if (LogicalShift)
586 return Builder.CreateLShr(Vec, ShiftVec);
587
588 return Builder.CreateAShr(Vec, ShiftVec);
589}
590
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000591static Value *simplifyX86muldq(const IntrinsicInst &II,
592 InstCombiner::BuilderTy &Builder) {
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000593 Value *Arg0 = II.getArgOperand(0);
594 Value *Arg1 = II.getArgOperand(1);
595 Type *ResTy = II.getType();
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000596 assert(Arg0->getType()->getScalarSizeInBits() == 32 &&
597 Arg1->getType()->getScalarSizeInBits() == 32 &&
598 ResTy->getScalarSizeInBits() == 64 && "Unexpected muldq/muludq types");
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000599
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000600 // muldq/muludq(undef, undef) -> zero (matches generic mul behavior)
Simon Pilgrim78f86302017-01-24 11:07:41 +0000601 if (isa<UndefValue>(Arg0) || isa<UndefValue>(Arg1))
Simon Pilgrimbb13fda2017-01-23 12:07:32 +0000602 return ConstantAggregateZero::get(ResTy);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000603
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +0000604 // Constant folding.
605 // PMULDQ = (mul(vXi64 sext(shuffle<0,2,..>(Arg0)),
606 // vXi64 sext(shuffle<0,2,..>(Arg1))))
607 // PMULUDQ = (mul(vXi64 zext(shuffle<0,2,..>(Arg0)),
608 // vXi64 zext(shuffle<0,2,..>(Arg1))))
609 if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
610 return nullptr;
611
612 unsigned NumElts = ResTy->getVectorNumElements();
613 assert(Arg0->getType()->getVectorNumElements() == (2 * NumElts) &&
614 Arg1->getType()->getVectorNumElements() == (2 * NumElts) &&
615 "Unexpected muldq/muludq types");
616
617 unsigned IntrinsicID = II.getIntrinsicID();
618 bool IsSigned = (Intrinsic::x86_sse41_pmuldq == IntrinsicID ||
619 Intrinsic::x86_avx2_pmul_dq == IntrinsicID ||
620 Intrinsic::x86_avx512_pmul_dq_512 == IntrinsicID);
621
622 SmallVector<unsigned, 16> ShuffleMask;
623 for (unsigned i = 0; i != NumElts; ++i)
624 ShuffleMask.push_back(i * 2);
625
626 auto *LHS = Builder.CreateShuffleVector(Arg0, Arg0, ShuffleMask);
627 auto *RHS = Builder.CreateShuffleVector(Arg1, Arg1, ShuffleMask);
628
629 if (IsSigned) {
630 LHS = Builder.CreateSExt(LHS, ResTy);
631 RHS = Builder.CreateSExt(RHS, ResTy);
632 } else {
633 LHS = Builder.CreateZExt(LHS, ResTy);
634 RHS = Builder.CreateZExt(RHS, ResTy);
635 }
636
637 return Builder.CreateMul(LHS, RHS);
Simon Pilgrima50a93f2017-01-20 18:20:30 +0000638}
639
Simon Pilgrim6f6b2792017-01-25 14:37:24 +0000640static Value *simplifyX86pack(IntrinsicInst &II, InstCombiner &IC,
641 InstCombiner::BuilderTy &Builder, bool IsSigned) {
642 Value *Arg0 = II.getArgOperand(0);
643 Value *Arg1 = II.getArgOperand(1);
644 Type *ResTy = II.getType();
645
646 // Fast all undef handling.
647 if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
648 return UndefValue::get(ResTy);
649
650 Type *ArgTy = Arg0->getType();
651 unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
652 unsigned NumDstElts = ResTy->getVectorNumElements();
653 unsigned NumSrcElts = ArgTy->getVectorNumElements();
654 assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
655
656 unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
657 unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
658 unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
659 assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
660 "Unexpected packing types");
661
662 // Constant folding.
663 auto *Cst0 = dyn_cast<Constant>(Arg0);
664 auto *Cst1 = dyn_cast<Constant>(Arg1);
665 if (!Cst0 || !Cst1)
666 return nullptr;
667
668 SmallVector<Constant *, 32> Vals;
669 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
670 for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
671 unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
672 auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
673 auto *COp = Cst->getAggregateElement(SrcIdx);
674 if (COp && isa<UndefValue>(COp)) {
675 Vals.push_back(UndefValue::get(ResTy->getScalarType()));
676 continue;
677 }
678
679 auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
680 if (!CInt)
681 return nullptr;
682
683 APInt Val = CInt->getValue();
684 assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
685 "Unexpected constant bitwidth");
686
687 if (IsSigned) {
688 // PACKSS: Truncate signed value with signed saturation.
689 // Source values less than dst minint are saturated to minint.
690 // Source values greater than dst maxint are saturated to maxint.
691 if (Val.isSignedIntN(DstScalarSizeInBits))
692 Val = Val.trunc(DstScalarSizeInBits);
693 else if (Val.isNegative())
694 Val = APInt::getSignedMinValue(DstScalarSizeInBits);
695 else
696 Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
697 } else {
698 // PACKUS: Truncate signed value with unsigned saturation.
699 // Source values less than zero are saturated to zero.
700 // Source values greater than dst maxuint are saturated to maxuint.
701 if (Val.isIntN(DstScalarSizeInBits))
702 Val = Val.trunc(DstScalarSizeInBits);
703 else if (Val.isNegative())
704 Val = APInt::getNullValue(DstScalarSizeInBits);
705 else
706 Val = APInt::getAllOnesValue(DstScalarSizeInBits);
707 }
708
709 Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
710 }
711 }
712
713 return ConstantVector::get(Vals);
714}
715
Simon Pilgrim91e3ac82016-06-07 08:18:35 +0000716static Value *simplifyX86movmsk(const IntrinsicInst &II,
717 InstCombiner::BuilderTy &Builder) {
718 Value *Arg = II.getArgOperand(0);
719 Type *ResTy = II.getType();
720 Type *ArgTy = Arg->getType();
721
722 // movmsk(undef) -> zero as we must ensure the upper bits are zero.
723 if (isa<UndefValue>(Arg))
724 return Constant::getNullValue(ResTy);
725
726 // We can't easily peek through x86_mmx types.
727 if (!ArgTy->isVectorTy())
728 return nullptr;
729
730 auto *C = dyn_cast<Constant>(Arg);
731 if (!C)
732 return nullptr;
733
734 // Extract signbits of the vector input and pack into integer result.
735 APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
736 for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
737 auto *COp = C->getAggregateElement(I);
738 if (!COp)
739 return nullptr;
740 if (isa<UndefValue>(COp))
741 continue;
742
743 auto *CInt = dyn_cast<ConstantInt>(COp);
744 auto *CFp = dyn_cast<ConstantFP>(COp);
745 if (!CInt && !CFp)
746 return nullptr;
747
748 if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
749 Result.setBit(I);
750 }
751
752 return Constant::getIntegerValue(ResTy, Result);
753}
754
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000755static Value *simplifyX86insertps(const IntrinsicInst &II,
Sanjay Patelc86867c2015-04-16 17:52:13 +0000756 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000757 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
758 if (!CInt)
759 return nullptr;
Simon Pilgrim54fcd622015-07-25 20:41:00 +0000760
Sanjay Patel03c03f52016-01-28 00:03:16 +0000761 VectorType *VecTy = cast<VectorType>(II.getType());
762 assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
Sanjay Patelc86867c2015-04-16 17:52:13 +0000763
Sanjay Patel03c03f52016-01-28 00:03:16 +0000764 // The immediate permute control byte looks like this:
765 // [3:0] - zero mask for each 32-bit lane
766 // [5:4] - select one 32-bit destination lane
767 // [7:6] - select one 32-bit source lane
Sanjay Patelc86867c2015-04-16 17:52:13 +0000768
Sanjay Patel03c03f52016-01-28 00:03:16 +0000769 uint8_t Imm = CInt->getZExtValue();
770 uint8_t ZMask = Imm & 0xf;
771 uint8_t DestLane = (Imm >> 4) & 0x3;
772 uint8_t SourceLane = (Imm >> 6) & 0x3;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000773
Sanjay Patel03c03f52016-01-28 00:03:16 +0000774 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000775
Sanjay Patel03c03f52016-01-28 00:03:16 +0000776 // If all zero mask bits are set, this was just a weird way to
777 // generate a zero vector.
778 if (ZMask == 0xf)
779 return ZeroVector;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000780
Sanjay Patel03c03f52016-01-28 00:03:16 +0000781 // Initialize by passing all of the first source bits through.
Craig Topper99d1eab2016-06-12 00:41:19 +0000782 uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000783
Sanjay Patel03c03f52016-01-28 00:03:16 +0000784 // We may replace the second operand with the zero vector.
785 Value *V1 = II.getArgOperand(1);
786
787 if (ZMask) {
788 // If the zero mask is being used with a single input or the zero mask
789 // overrides the destination lane, this is a shuffle with the zero vector.
790 if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
791 (ZMask & (1 << DestLane))) {
792 V1 = ZeroVector;
793 // We may still move 32-bits of the first source vector from one lane
794 // to another.
795 ShuffleMask[DestLane] = SourceLane;
796 // The zero mask may override the previous insert operation.
797 for (unsigned i = 0; i < 4; ++i)
798 if ((ZMask >> i) & 0x1)
799 ShuffleMask[i] = i + 4;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000800 } else {
Sanjay Patel03c03f52016-01-28 00:03:16 +0000801 // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
802 return nullptr;
Sanjay Patelc1d20a32015-04-25 20:55:25 +0000803 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000804 } else {
805 // Replace the selected destination lane with the selected source lane.
806 ShuffleMask[DestLane] = SourceLane + 4;
Sanjay Patelc86867c2015-04-16 17:52:13 +0000807 }
Sanjay Patel03c03f52016-01-28 00:03:16 +0000808
809 return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
Sanjay Patelc86867c2015-04-16 17:52:13 +0000810}
811
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000812/// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
813/// or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000814static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000815 ConstantInt *CILength, ConstantInt *CIIndex,
816 InstCombiner::BuilderTy &Builder) {
817 auto LowConstantHighUndef = [&](uint64_t Val) {
818 Type *IntTy64 = Type::getInt64Ty(II.getContext());
819 Constant *Args[] = {ConstantInt::get(IntTy64, Val),
820 UndefValue::get(IntTy64)};
821 return ConstantVector::get(Args);
822 };
823
824 // See if we're dealing with constant values.
825 Constant *C0 = dyn_cast<Constant>(Op0);
826 ConstantInt *CI0 =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +0000827 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000828 : nullptr;
829
830 // Attempt to constant fold.
831 if (CILength && CIIndex) {
832 // From AMD documentation: "The bit index and field length are each six
833 // bits in length other bits of the field are ignored."
834 APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
835 APInt APLength = CILength->getValue().zextOrTrunc(6);
836
837 unsigned Index = APIndex.getZExtValue();
838
839 // From AMD documentation: "a value of zero in the field length is
840 // defined as length of 64".
841 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
842
843 // From AMD documentation: "If the sum of the bit index + length field
844 // is greater than 64, the results are undefined".
845 unsigned End = Index + Length;
846
847 // Note that both field index and field length are 8-bit quantities.
848 // Since variables 'Index' and 'Length' are unsigned values
849 // obtained from zero-extending field index and field length
850 // respectively, their sum should never wrap around.
851 if (End > 64)
852 return UndefValue::get(II.getType());
853
854 // If we are inserting whole bytes, we can convert this to a shuffle.
855 // Lowering can recognize EXTRQI shuffle masks.
856 if ((Length % 8) == 0 && (Index % 8) == 0) {
857 // Convert bit indices to byte indices.
858 Length /= 8;
859 Index /= 8;
860
861 Type *IntTy8 = Type::getInt8Ty(II.getContext());
862 Type *IntTy32 = Type::getInt32Ty(II.getContext());
863 VectorType *ShufTy = VectorType::get(IntTy8, 16);
864
865 SmallVector<Constant *, 16> ShuffleMask;
866 for (int i = 0; i != (int)Length; ++i)
867 ShuffleMask.push_back(
868 Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
869 for (int i = Length; i != 8; ++i)
870 ShuffleMask.push_back(
871 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
872 for (int i = 8; i != 16; ++i)
873 ShuffleMask.push_back(UndefValue::get(IntTy32));
874
875 Value *SV = Builder.CreateShuffleVector(
876 Builder.CreateBitCast(Op0, ShufTy),
877 ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
878 return Builder.CreateBitCast(SV, II.getType());
879 }
880
881 // Constant Fold - shift Index'th bit to lowest position and mask off
882 // Length bits.
883 if (CI0) {
884 APInt Elt = CI0->getValue();
885 Elt = Elt.lshr(Index).zextOrTrunc(Length);
886 return LowConstantHighUndef(Elt.getZExtValue());
887 }
888
889 // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
890 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
891 Value *Args[] = {Op0, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000892 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000893 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
894 return Builder.CreateCall(F, Args);
895 }
896 }
897
898 // Constant Fold - extraction from zero is always {zero, undef}.
899 if (CI0 && CI0->equalsInt(0))
900 return LowConstantHighUndef(0);
901
902 return nullptr;
903}
904
905/// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
906/// folding or conversion to a shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +0000907static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000908 APInt APLength, APInt APIndex,
909 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000910 // From AMD documentation: "The bit index and field length are each six bits
911 // in length other bits of the field are ignored."
912 APIndex = APIndex.zextOrTrunc(6);
913 APLength = APLength.zextOrTrunc(6);
914
915 // Attempt to constant fold.
916 unsigned Index = APIndex.getZExtValue();
917
918 // From AMD documentation: "a value of zero in the field length is
919 // defined as length of 64".
920 unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
921
922 // From AMD documentation: "If the sum of the bit index + length field
923 // is greater than 64, the results are undefined".
924 unsigned End = Index + Length;
925
926 // Note that both field index and field length are 8-bit quantities.
927 // Since variables 'Index' and 'Length' are unsigned values
928 // obtained from zero-extending field index and field length
929 // respectively, their sum should never wrap around.
930 if (End > 64)
931 return UndefValue::get(II.getType());
932
933 // If we are inserting whole bytes, we can convert this to a shuffle.
934 // Lowering can recognize INSERTQI shuffle masks.
935 if ((Length % 8) == 0 && (Index % 8) == 0) {
936 // Convert bit indices to byte indices.
937 Length /= 8;
938 Index /= 8;
939
940 Type *IntTy8 = Type::getInt8Ty(II.getContext());
941 Type *IntTy32 = Type::getInt32Ty(II.getContext());
942 VectorType *ShufTy = VectorType::get(IntTy8, 16);
943
944 SmallVector<Constant *, 16> ShuffleMask;
945 for (int i = 0; i != (int)Index; ++i)
946 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
947 for (int i = 0; i != (int)Length; ++i)
948 ShuffleMask.push_back(
949 Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
950 for (int i = Index + Length; i != 8; ++i)
951 ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
952 for (int i = 8; i != 16; ++i)
953 ShuffleMask.push_back(UndefValue::get(IntTy32));
954
955 Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
956 Builder.CreateBitCast(Op1, ShufTy),
957 ConstantVector::get(ShuffleMask));
958 return Builder.CreateBitCast(SV, II.getType());
959 }
960
961 // See if we're dealing with constant values.
962 Constant *C0 = dyn_cast<Constant>(Op0);
963 Constant *C1 = dyn_cast<Constant>(Op1);
964 ConstantInt *CI00 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000965 C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000966 : nullptr;
967 ConstantInt *CI10 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +0000968 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000969 : nullptr;
970
971 // Constant Fold - insert bottom Length bits starting at the Index'th bit.
972 if (CI00 && CI10) {
973 APInt V00 = CI00->getValue();
974 APInt V10 = CI10->getValue();
975 APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
976 V00 = V00 & ~Mask;
977 V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
978 APInt Val = V00 | V10;
979 Type *IntTy64 = Type::getInt64Ty(II.getContext());
980 Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
981 UndefValue::get(IntTy64)};
982 return ConstantVector::get(Args);
983 }
984
985 // If we were an INSERTQ call, we'll save demanded elements if we convert to
986 // INSERTQI.
987 if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
988 Type *IntTy8 = Type::getInt8Ty(II.getContext());
989 Constant *CILength = ConstantInt::get(IntTy8, Length, false);
990 Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
991
992 Value *Args[] = {Op0, Op1, CILength, CIIndex};
Sanjay Patelaf674fb2015-12-14 17:24:23 +0000993 Module *M = II.getModule();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +0000994 Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
995 return Builder.CreateCall(F, Args);
996 }
997
998 return nullptr;
999}
1000
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001001/// Attempt to convert pshufb* to shufflevector if the mask is constant.
1002static Value *simplifyX86pshufb(const IntrinsicInst &II,
1003 InstCombiner::BuilderTy &Builder) {
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001004 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1005 if (!V)
1006 return nullptr;
1007
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001008 auto *VecTy = cast<VectorType>(II.getType());
1009 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1010 unsigned NumElts = VecTy->getNumElements();
Craig Topper9a63d7a2016-12-11 00:23:50 +00001011 assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001012 "Unexpected number of elements in shuffle mask!");
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001013
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001014 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper9a63d7a2016-12-11 00:23:50 +00001015 Constant *Indexes[64] = {nullptr};
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001016
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001017 // Each byte in the shuffle control mask forms an index to permute the
1018 // corresponding byte in the destination operand.
1019 for (unsigned I = 0; I < NumElts; ++I) {
1020 Constant *COp = V->getAggregateElement(I);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001021 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001022 return nullptr;
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001023
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001024 if (isa<UndefValue>(COp)) {
1025 Indexes[I] = UndefValue::get(MaskEltTy);
1026 continue;
1027 }
1028
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001029 int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
1030
1031 // If the most significant bit (bit[7]) of each byte of the shuffle
1032 // control mask is set, then zero is written in the result byte.
1033 // The zero vector is in the right-hand side of the resulting
1034 // shufflevector.
1035
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001036 // The value of each index for the high 128-bit lane is the least
1037 // significant 4 bits of the respective shuffle control byte.
1038 Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
1039 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrimbf60cc42016-04-29 21:34:54 +00001040 }
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001041
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001042 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001043 auto V1 = II.getArgOperand(0);
Simon Pilgrime5e8c2f2016-05-01 19:26:21 +00001044 auto V2 = Constant::getNullValue(VecTy);
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00001045 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1046}
1047
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001048/// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1049static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1050 InstCombiner::BuilderTy &Builder) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001051 Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1052 if (!V)
1053 return nullptr;
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001054
Craig Topper58917f32016-12-11 01:59:36 +00001055 auto *VecTy = cast<VectorType>(II.getType());
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001056 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Craig Topper58917f32016-12-11 01:59:36 +00001057 unsigned NumElts = VecTy->getVectorNumElements();
1058 bool IsPD = VecTy->getScalarType()->isDoubleTy();
1059 unsigned NumLaneElts = IsPD ? 2 : 4;
1060 assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001061
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001062 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Topper58917f32016-12-11 01:59:36 +00001063 Constant *Indexes[16] = {nullptr};
Simon Pilgrim640f9962016-04-30 07:23:30 +00001064
1065 // The intrinsics only read one or two bits, clear the rest.
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001066 for (unsigned I = 0; I < NumElts; ++I) {
Simon Pilgrim640f9962016-04-30 07:23:30 +00001067 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001068 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim640f9962016-04-30 07:23:30 +00001069 return nullptr;
1070
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001071 if (isa<UndefValue>(COp)) {
1072 Indexes[I] = UndefValue::get(MaskEltTy);
1073 continue;
1074 }
1075
1076 APInt Index = cast<ConstantInt>(COp)->getValue();
1077 Index = Index.zextOrTrunc(32).getLoBits(2);
Simon Pilgrim640f9962016-04-30 07:23:30 +00001078
1079 // The PD variants uses bit 1 to select per-lane element index, so
1080 // shift down to convert to generic shuffle mask index.
Craig Topper58917f32016-12-11 01:59:36 +00001081 if (IsPD)
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001082 Index = Index.lshr(1);
1083
1084 // The _256 variants are a bit trickier since the mask bits always index
1085 // into the corresponding 128 half. In order to convert to a generic
1086 // shuffle, we have to make that explicit.
Craig Topper58917f32016-12-11 01:59:36 +00001087 Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001088
1089 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001090 }
1091
Simon Pilgrimeeacc402016-05-01 20:22:42 +00001092 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00001093 auto V1 = II.getArgOperand(0);
1094 auto V2 = UndefValue::get(V1->getType());
1095 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1096}
1097
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001098/// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1099static Value *simplifyX86vpermv(const IntrinsicInst &II,
1100 InstCombiner::BuilderTy &Builder) {
1101 auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1102 if (!V)
1103 return nullptr;
1104
Simon Pilgrimca140b12016-05-01 20:43:02 +00001105 auto *VecTy = cast<VectorType>(II.getType());
1106 auto *MaskEltTy = Type::getInt32Ty(II.getContext());
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001107 unsigned Size = VecTy->getNumElements();
Craig Toppere3280452016-12-25 23:58:57 +00001108 assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1109 "Unexpected shuffle mask size");
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001110
Simon Pilgrimca140b12016-05-01 20:43:02 +00001111 // Construct a shuffle mask from constant integers or UNDEFs.
Craig Toppere3280452016-12-25 23:58:57 +00001112 Constant *Indexes[64] = {nullptr};
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001113
1114 for (unsigned I = 0; I < Size; ++I) {
1115 Constant *COp = V->getAggregateElement(I);
Simon Pilgrimca140b12016-05-01 20:43:02 +00001116 if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001117 return nullptr;
1118
Simon Pilgrimca140b12016-05-01 20:43:02 +00001119 if (isa<UndefValue>(COp)) {
1120 Indexes[I] = UndefValue::get(MaskEltTy);
1121 continue;
1122 }
1123
Craig Toppere3280452016-12-25 23:58:57 +00001124 uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1125 Index &= Size - 1;
Simon Pilgrimca140b12016-05-01 20:43:02 +00001126 Indexes[I] = ConstantInt::get(MaskEltTy, Index);
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001127 }
1128
Simon Pilgrimca140b12016-05-01 20:43:02 +00001129 auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00001130 auto V1 = II.getArgOperand(0);
1131 auto V2 = UndefValue::get(VecTy);
1132 return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1133}
1134
Sanjay Patelccf5f242015-03-20 21:47:56 +00001135/// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
1136/// source vectors, unless a zero bit is set. If a zero bit is set,
1137/// then ignore that half of the mask and clear that half of the vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001138static Value *simplifyX86vperm2(const IntrinsicInst &II,
Sanjay Patelccf5f242015-03-20 21:47:56 +00001139 InstCombiner::BuilderTy &Builder) {
Sanjay Patel03c03f52016-01-28 00:03:16 +00001140 auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
1141 if (!CInt)
1142 return nullptr;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001143
Sanjay Patel03c03f52016-01-28 00:03:16 +00001144 VectorType *VecTy = cast<VectorType>(II.getType());
1145 ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001146
Sanjay Patel03c03f52016-01-28 00:03:16 +00001147 // The immediate permute control byte looks like this:
1148 // [1:0] - select 128 bits from sources for low half of destination
1149 // [2] - ignore
1150 // [3] - zero low half of destination
1151 // [5:4] - select 128 bits from sources for high half of destination
1152 // [6] - ignore
1153 // [7] - zero high half of destination
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001154
Sanjay Patel03c03f52016-01-28 00:03:16 +00001155 uint8_t Imm = CInt->getZExtValue();
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001156
Sanjay Patel03c03f52016-01-28 00:03:16 +00001157 bool LowHalfZero = Imm & 0x08;
1158 bool HighHalfZero = Imm & 0x80;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001159
Sanjay Patel03c03f52016-01-28 00:03:16 +00001160 // If both zero mask bits are set, this was just a weird way to
1161 // generate a zero vector.
1162 if (LowHalfZero && HighHalfZero)
1163 return ZeroVector;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001164
Sanjay Patel03c03f52016-01-28 00:03:16 +00001165 // If 0 or 1 zero mask bits are set, this is a simple shuffle.
1166 unsigned NumElts = VecTy->getNumElements();
1167 unsigned HalfSize = NumElts / 2;
Craig Topper99d1eab2016-06-12 00:41:19 +00001168 SmallVector<uint32_t, 8> ShuffleMask(NumElts);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001169
Sanjay Patel03c03f52016-01-28 00:03:16 +00001170 // The high bit of the selection field chooses the 1st or 2nd operand.
1171 bool LowInputSelect = Imm & 0x02;
1172 bool HighInputSelect = Imm & 0x20;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001173
Sanjay Patel03c03f52016-01-28 00:03:16 +00001174 // The low bit of the selection field chooses the low or high half
1175 // of the selected operand.
1176 bool LowHalfSelect = Imm & 0x01;
1177 bool HighHalfSelect = Imm & 0x10;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001178
Sanjay Patel03c03f52016-01-28 00:03:16 +00001179 // Determine which operand(s) are actually in use for this instruction.
1180 Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
1181 Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
Simon Pilgrim54fcd622015-07-25 20:41:00 +00001182
Sanjay Patel03c03f52016-01-28 00:03:16 +00001183 // If needed, replace operands based on zero mask.
1184 V0 = LowHalfZero ? ZeroVector : V0;
1185 V1 = HighHalfZero ? ZeroVector : V1;
Sanjay Patelccf5f242015-03-20 21:47:56 +00001186
Sanjay Patel03c03f52016-01-28 00:03:16 +00001187 // Permute low half of result.
1188 unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
1189 for (unsigned i = 0; i < HalfSize; ++i)
1190 ShuffleMask[i] = StartIndex + i;
Sanjay Patel43a87fd2015-03-24 20:36:42 +00001191
Sanjay Patel03c03f52016-01-28 00:03:16 +00001192 // Permute high half of result.
1193 StartIndex = HighHalfSelect ? HalfSize : 0;
1194 StartIndex += NumElts;
1195 for (unsigned i = 0; i < HalfSize; ++i)
1196 ShuffleMask[i + HalfSize] = StartIndex + i;
1197
1198 return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
Sanjay Patelccf5f242015-03-20 21:47:56 +00001199}
1200
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001201/// Decode XOP integer vector comparison intrinsics.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00001202static Value *simplifyX86vpcom(const IntrinsicInst &II,
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001203 InstCombiner::BuilderTy &Builder,
1204 bool IsSigned) {
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001205 if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1206 uint64_t Imm = CInt->getZExtValue() & 0x7;
1207 VectorType *VecTy = cast<VectorType>(II.getType());
1208 CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1209
1210 switch (Imm) {
1211 case 0x0:
1212 Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1213 break;
1214 case 0x1:
1215 Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1216 break;
1217 case 0x2:
1218 Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1219 break;
1220 case 0x3:
1221 Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1222 break;
1223 case 0x4:
1224 Pred = ICmpInst::ICMP_EQ; break;
1225 case 0x5:
1226 Pred = ICmpInst::ICMP_NE; break;
1227 case 0x6:
1228 return ConstantInt::getSigned(VecTy, 0); // FALSE
1229 case 0x7:
1230 return ConstantInt::getSigned(VecTy, -1); // TRUE
1231 }
1232
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00001233 if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1234 II.getArgOperand(1)))
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00001235 return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1236 }
1237 return nullptr;
1238}
1239
Craig Toppere3280452016-12-25 23:58:57 +00001240// Emit a select instruction and appropriate bitcasts to help simplify
1241// masked intrinsics.
1242static Value *emitX86MaskSelect(Value *Mask, Value *Op0, Value *Op1,
1243 InstCombiner::BuilderTy &Builder) {
Craig Topper99163632016-12-30 23:06:28 +00001244 unsigned VWidth = Op0->getType()->getVectorNumElements();
1245
1246 // If the mask is all ones we don't need the select. But we need to check
1247 // only the bit thats will be used in case VWidth is less than 8.
1248 if (auto *C = dyn_cast<ConstantInt>(Mask))
1249 if (C->getValue().zextOrTrunc(VWidth).isAllOnesValue())
1250 return Op0;
1251
Craig Toppere3280452016-12-25 23:58:57 +00001252 auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
1253 cast<IntegerType>(Mask->getType())->getBitWidth());
1254 Mask = Builder.CreateBitCast(Mask, MaskTy);
1255
1256 // If we have less than 8 elements, then the starting mask was an i8 and
1257 // we need to extract down to the right number of elements.
Craig Toppere3280452016-12-25 23:58:57 +00001258 if (VWidth < 8) {
1259 uint32_t Indices[4];
1260 for (unsigned i = 0; i != VWidth; ++i)
1261 Indices[i] = i;
1262 Mask = Builder.CreateShuffleVector(Mask, Mask,
1263 makeArrayRef(Indices, VWidth),
1264 "extract");
1265 }
1266
1267 return Builder.CreateSelect(Mask, Op0, Op1);
1268}
1269
Sanjay Patel0069f562016-01-31 16:35:23 +00001270static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1271 Value *Arg0 = II.getArgOperand(0);
1272 Value *Arg1 = II.getArgOperand(1);
1273
1274 // fmin(x, x) -> x
1275 if (Arg0 == Arg1)
1276 return Arg0;
1277
1278 const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1279
1280 // fmin(x, nan) -> x
1281 if (C1 && C1->isNaN())
1282 return Arg0;
1283
1284 // This is the value because if undef were NaN, we would return the other
1285 // value and cannot return a NaN unless both operands are.
1286 //
1287 // fmin(undef, x) -> x
1288 if (isa<UndefValue>(Arg0))
1289 return Arg1;
1290
1291 // fmin(x, undef) -> x
1292 if (isa<UndefValue>(Arg1))
1293 return Arg0;
1294
1295 Value *X = nullptr;
1296 Value *Y = nullptr;
1297 if (II.getIntrinsicID() == Intrinsic::minnum) {
1298 // fmin(x, fmin(x, y)) -> fmin(x, y)
1299 // fmin(y, fmin(x, y)) -> fmin(x, y)
1300 if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1301 if (Arg0 == X || Arg0 == Y)
1302 return Arg1;
1303 }
1304
1305 // fmin(fmin(x, y), x) -> fmin(x, y)
1306 // fmin(fmin(x, y), y) -> fmin(x, y)
1307 if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1308 if (Arg1 == X || Arg1 == Y)
1309 return Arg0;
1310 }
1311
1312 // TODO: fmin(nnan x, inf) -> x
1313 // TODO: fmin(nnan ninf x, flt_max) -> x
1314 if (C1 && C1->isInfinity()) {
1315 // fmin(x, -inf) -> -inf
1316 if (C1->isNegative())
1317 return Arg1;
1318 }
1319 } else {
1320 assert(II.getIntrinsicID() == Intrinsic::maxnum);
1321 // fmax(x, fmax(x, y)) -> fmax(x, y)
1322 // fmax(y, fmax(x, y)) -> fmax(x, y)
1323 if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1324 if (Arg0 == X || Arg0 == Y)
1325 return Arg1;
1326 }
1327
1328 // fmax(fmax(x, y), x) -> fmax(x, y)
1329 // fmax(fmax(x, y), y) -> fmax(x, y)
1330 if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1331 if (Arg1 == X || Arg1 == Y)
1332 return Arg0;
1333 }
1334
1335 // TODO: fmax(nnan x, -inf) -> x
1336 // TODO: fmax(nnan ninf x, -flt_max) -> x
1337 if (C1 && C1->isInfinity()) {
1338 // fmax(x, inf) -> inf
1339 if (!C1->isNegative())
1340 return Arg1;
1341 }
1342 }
1343 return nullptr;
1344}
1345
David Majnemer666aa942016-07-14 06:58:42 +00001346static bool maskIsAllOneOrUndef(Value *Mask) {
1347 auto *ConstMask = dyn_cast<Constant>(Mask);
1348 if (!ConstMask)
1349 return false;
1350 if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1351 return true;
1352 for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1353 ++I) {
1354 if (auto *MaskElt = ConstMask->getAggregateElement(I))
1355 if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1356 continue;
1357 return false;
1358 }
1359 return true;
1360}
1361
Sanjay Patelb695c552016-02-01 17:00:10 +00001362static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1363 InstCombiner::BuilderTy &Builder) {
David Majnemer666aa942016-07-14 06:58:42 +00001364 // If the mask is all ones or undefs, this is a plain vector load of the 1st
1365 // argument.
1366 if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
Sanjay Patelb695c552016-02-01 17:00:10 +00001367 Value *LoadPtr = II.getArgOperand(0);
1368 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1369 return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1370 }
1371
1372 return nullptr;
1373}
1374
Sanjay Patel04f792b2016-02-01 19:39:52 +00001375static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1376 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1377 if (!ConstMask)
1378 return nullptr;
1379
1380 // If the mask is all zeros, this instruction does nothing.
1381 if (ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001382 return IC.eraseInstFromFunction(II);
Sanjay Patel04f792b2016-02-01 19:39:52 +00001383
1384 // If the mask is all ones, this is a plain vector store of the 1st argument.
1385 if (ConstMask->isAllOnesValue()) {
1386 Value *StorePtr = II.getArgOperand(1);
1387 unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1388 return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1389 }
1390
1391 return nullptr;
1392}
1393
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001394static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1395 // If the mask is all zeros, return the "passthru" argument of the gather.
1396 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1397 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001398 return IC.replaceInstUsesWith(II, II.getArgOperand(3));
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001399
1400 return nullptr;
1401}
1402
1403static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1404 // If the mask is all zeros, a scatter does nothing.
1405 auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1406 if (ConstMask && ConstMask->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001407 return IC.eraseInstFromFunction(II);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001408
1409 return nullptr;
1410}
1411
Amaury Sechet763c59d2016-08-18 20:43:50 +00001412static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1413 assert((II.getIntrinsicID() == Intrinsic::cttz ||
1414 II.getIntrinsicID() == Intrinsic::ctlz) &&
1415 "Expected cttz or ctlz intrinsic");
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001416 Value *Op0 = II.getArgOperand(0);
1417 // FIXME: Try to simplify vectors of integers.
1418 auto *IT = dyn_cast<IntegerType>(Op0->getType());
1419 if (!IT)
1420 return nullptr;
1421
1422 unsigned BitWidth = IT->getBitWidth();
1423 APInt KnownZero(BitWidth, 0);
1424 APInt KnownOne(BitWidth, 0);
1425 IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1426
1427 // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1428 bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1429 unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1430 : KnownOne.countLeadingZeros();
1431 APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1432 : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1433
1434 // If all bits above (ctlz) or below (cttz) the first known one are known
1435 // zero, this value is constant.
1436 // FIXME: This should be in InstSimplify because we're replacing an
1437 // instruction with a constant.
Amaury Sechet763c59d2016-08-18 20:43:50 +00001438 if ((Mask & KnownZero) == Mask) {
1439 auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1440 return IC.replaceInstUsesWith(II, C);
1441 }
1442
1443 // If the input to cttz/ctlz is known to be non-zero,
1444 // then change the 'ZeroIsUndef' parameter to 'true'
1445 // because we know the zero behavior can't affect the result.
1446 if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1447 if (!match(II.getArgOperand(1), m_One())) {
1448 II.setOperand(1, IC.Builder->getTrue());
1449 return &II;
1450 }
1451 }
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001452
1453 return nullptr;
1454}
1455
Sanjay Patel1ace9932016-02-26 21:04:14 +00001456// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1457// XMM register mask efficiently, we could transform all x86 masked intrinsics
1458// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel98a71502016-02-29 23:16:48 +00001459static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1460 Value *Ptr = II.getOperand(0);
1461 Value *Mask = II.getOperand(1);
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001462 Constant *ZeroVec = Constant::getNullValue(II.getType());
Sanjay Patel98a71502016-02-29 23:16:48 +00001463
1464 // Special case a zero mask since that's not a ConstantDataVector.
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001465 // This masked load instruction creates a zero vector.
Sanjay Patel98a71502016-02-29 23:16:48 +00001466 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001467 return IC.replaceInstUsesWith(II, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001468
1469 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1470 if (!ConstMask)
1471 return nullptr;
1472
1473 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1474 // to allow target-independent optimizations.
1475
1476 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1477 // the LLVM intrinsic definition for the pointer argument.
1478 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1479 PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1480 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1481
1482 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1483 // on each element's most significant bit (the sign bit).
1484 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1485
Sanjay Patel5e5056d2016-04-12 23:16:23 +00001486 // The pass-through vector for an x86 masked load is a zero vector.
1487 CallInst *NewMaskedLoad =
1488 IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
Sanjay Patel98a71502016-02-29 23:16:48 +00001489 return IC.replaceInstUsesWith(II, NewMaskedLoad);
1490}
1491
1492// TODO: If the x86 backend knew how to convert a bool vector mask back to an
1493// XMM register mask efficiently, we could transform all x86 masked intrinsics
1494// to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
Sanjay Patel1ace9932016-02-26 21:04:14 +00001495static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1496 Value *Ptr = II.getOperand(0);
1497 Value *Mask = II.getOperand(1);
1498 Value *Vec = II.getOperand(2);
1499
1500 // Special case a zero mask since that's not a ConstantDataVector:
1501 // this masked store instruction does nothing.
1502 if (isa<ConstantAggregateZero>(Mask)) {
1503 IC.eraseInstFromFunction(II);
1504 return true;
1505 }
1506
Sanjay Patelc4acbae2016-03-12 15:16:59 +00001507 // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1508 // anything else at this level.
1509 if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1510 return false;
1511
Sanjay Patel1ace9932016-02-26 21:04:14 +00001512 auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1513 if (!ConstMask)
1514 return false;
1515
1516 // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1517 // to allow target-independent optimizations.
1518
1519 // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1520 // the LLVM intrinsic definition for the pointer argument.
1521 unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1522 PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
Sanjay Patel1ace9932016-02-26 21:04:14 +00001523 Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1524
1525 // Second, convert the x86 XMM integer vector mask to a vector of bools based
1526 // on each element's most significant bit (the sign bit).
1527 Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1528
1529 IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1530
1531 // 'Replace uses' doesn't work for stores. Erase the original masked store.
1532 IC.eraseInstFromFunction(II);
1533 return true;
1534}
1535
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001536// Returns true iff the 2 intrinsics have the same operands, limiting the
1537// comparison to the first NumOperands.
1538static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1539 unsigned NumOperands) {
1540 assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1541 assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1542 for (unsigned i = 0; i < NumOperands; i++)
1543 if (I.getArgOperand(i) != E.getArgOperand(i))
1544 return false;
1545 return true;
1546}
1547
1548// Remove trivially empty start/end intrinsic ranges, i.e. a start
1549// immediately followed by an end (ignoring debuginfo or other
1550// start/end intrinsics in between). As this handles only the most trivial
1551// cases, tracking the nesting level is not needed:
1552//
1553// call @llvm.foo.start(i1 0) ; &I
1554// call @llvm.foo.start(i1 0)
1555// call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1556// call @llvm.foo.end(i1 0)
1557static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1558 unsigned EndID, InstCombiner &IC) {
1559 assert(I.getIntrinsicID() == StartID &&
1560 "Start intrinsic does not have expected ID");
1561 BasicBlock::iterator BI(I), BE(I.getParent()->end());
1562 for (++BI; BI != BE; ++BI) {
1563 if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1564 if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1565 continue;
1566 if (E->getIntrinsicID() == EndID &&
1567 haveSameOperands(I, *E, E->getNumArgOperands())) {
1568 IC.eraseInstFromFunction(*E);
1569 IC.eraseInstFromFunction(I);
1570 return true;
1571 }
1572 }
1573 break;
1574 }
1575
1576 return false;
1577}
1578
Justin Lebar698c31b2017-01-27 00:58:58 +00001579// Convert NVVM intrinsics to target-generic LLVM code where possible.
1580static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1581 // Each NVVM intrinsic we can simplify can be replaced with one of:
1582 //
1583 // * an LLVM intrinsic,
1584 // * an LLVM cast operation,
1585 // * an LLVM binary operation, or
1586 // * ad-hoc LLVM IR for the particular operation.
1587
1588 // Some transformations are only valid when the module's
1589 // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1590 // transformations are valid regardless of the module's ftz setting.
1591 enum FtzRequirementTy {
1592 FTZ_Any, // Any ftz setting is ok.
1593 FTZ_MustBeOn, // Transformation is valid only if ftz is on.
1594 FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1595 };
1596 // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1597 // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1598 // simplify.
1599 enum SpecialCase {
1600 SPC_Reciprocal,
1601 };
1602
1603 // SimplifyAction is a poor-man's variant (plus an additional flag) that
1604 // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1605 struct SimplifyAction {
1606 // Invariant: At most one of these Optionals has a value.
1607 Optional<Intrinsic::ID> IID;
1608 Optional<Instruction::CastOps> CastOp;
1609 Optional<Instruction::BinaryOps> BinaryOp;
1610 Optional<SpecialCase> Special;
1611
1612 FtzRequirementTy FtzRequirement = FTZ_Any;
1613
1614 SimplifyAction() = default;
1615
1616 SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1617 : IID(IID), FtzRequirement(FtzReq) {}
1618
1619 // Cast operations don't have anything to do with FTZ, so we skip that
1620 // argument.
1621 SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1622
1623 SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1624 : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1625
1626 SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1627 : Special(Special), FtzRequirement(FtzReq) {}
1628 };
1629
1630 // Try to generate a SimplifyAction describing how to replace our
1631 // IntrinsicInstr with target-generic LLVM IR.
1632 const SimplifyAction Action = [II]() -> SimplifyAction {
1633 switch (II->getIntrinsicID()) {
1634
1635 // NVVM intrinsics that map directly to LLVM intrinsics.
1636 case Intrinsic::nvvm_ceil_d:
1637 return {Intrinsic::ceil, FTZ_Any};
1638 case Intrinsic::nvvm_ceil_f:
1639 return {Intrinsic::ceil, FTZ_MustBeOff};
1640 case Intrinsic::nvvm_ceil_ftz_f:
1641 return {Intrinsic::ceil, FTZ_MustBeOn};
1642 case Intrinsic::nvvm_fabs_d:
1643 return {Intrinsic::fabs, FTZ_Any};
1644 case Intrinsic::nvvm_fabs_f:
1645 return {Intrinsic::fabs, FTZ_MustBeOff};
1646 case Intrinsic::nvvm_fabs_ftz_f:
1647 return {Intrinsic::fabs, FTZ_MustBeOn};
1648 case Intrinsic::nvvm_floor_d:
1649 return {Intrinsic::floor, FTZ_Any};
1650 case Intrinsic::nvvm_floor_f:
1651 return {Intrinsic::floor, FTZ_MustBeOff};
1652 case Intrinsic::nvvm_floor_ftz_f:
1653 return {Intrinsic::floor, FTZ_MustBeOn};
1654 case Intrinsic::nvvm_fma_rn_d:
1655 return {Intrinsic::fma, FTZ_Any};
1656 case Intrinsic::nvvm_fma_rn_f:
1657 return {Intrinsic::fma, FTZ_MustBeOff};
1658 case Intrinsic::nvvm_fma_rn_ftz_f:
1659 return {Intrinsic::fma, FTZ_MustBeOn};
1660 case Intrinsic::nvvm_fmax_d:
1661 return {Intrinsic::maxnum, FTZ_Any};
1662 case Intrinsic::nvvm_fmax_f:
1663 return {Intrinsic::maxnum, FTZ_MustBeOff};
1664 case Intrinsic::nvvm_fmax_ftz_f:
1665 return {Intrinsic::maxnum, FTZ_MustBeOn};
1666 case Intrinsic::nvvm_fmin_d:
1667 return {Intrinsic::minnum, FTZ_Any};
1668 case Intrinsic::nvvm_fmin_f:
1669 return {Intrinsic::minnum, FTZ_MustBeOff};
1670 case Intrinsic::nvvm_fmin_ftz_f:
1671 return {Intrinsic::minnum, FTZ_MustBeOn};
1672 case Intrinsic::nvvm_round_d:
1673 return {Intrinsic::round, FTZ_Any};
1674 case Intrinsic::nvvm_round_f:
1675 return {Intrinsic::round, FTZ_MustBeOff};
1676 case Intrinsic::nvvm_round_ftz_f:
1677 return {Intrinsic::round, FTZ_MustBeOn};
1678 case Intrinsic::nvvm_sqrt_rn_d:
1679 return {Intrinsic::sqrt, FTZ_Any};
1680 case Intrinsic::nvvm_sqrt_f:
1681 // nvvm_sqrt_f is a special case. For most intrinsics, foo_ftz_f is the
1682 // ftz version, and foo_f is the non-ftz version. But nvvm_sqrt_f adopts
1683 // the ftz-ness of the surrounding code. sqrt_rn_f and sqrt_rn_ftz_f are
1684 // the versions with explicit ftz-ness.
1685 return {Intrinsic::sqrt, FTZ_Any};
1686 case Intrinsic::nvvm_sqrt_rn_f:
1687 return {Intrinsic::sqrt, FTZ_MustBeOff};
1688 case Intrinsic::nvvm_sqrt_rn_ftz_f:
1689 return {Intrinsic::sqrt, FTZ_MustBeOn};
1690 case Intrinsic::nvvm_trunc_d:
1691 return {Intrinsic::trunc, FTZ_Any};
1692 case Intrinsic::nvvm_trunc_f:
1693 return {Intrinsic::trunc, FTZ_MustBeOff};
1694 case Intrinsic::nvvm_trunc_ftz_f:
1695 return {Intrinsic::trunc, FTZ_MustBeOn};
1696
1697 // NVVM intrinsics that map to LLVM cast operations.
1698 //
1699 // Note that llvm's target-generic conversion operators correspond to the rz
1700 // (round to zero) versions of the nvvm conversion intrinsics, even though
1701 // most everything else here uses the rn (round to nearest even) nvvm ops.
1702 case Intrinsic::nvvm_d2i_rz:
1703 case Intrinsic::nvvm_f2i_rz:
1704 case Intrinsic::nvvm_d2ll_rz:
1705 case Intrinsic::nvvm_f2ll_rz:
1706 return {Instruction::FPToSI};
1707 case Intrinsic::nvvm_d2ui_rz:
1708 case Intrinsic::nvvm_f2ui_rz:
1709 case Intrinsic::nvvm_d2ull_rz:
1710 case Intrinsic::nvvm_f2ull_rz:
1711 return {Instruction::FPToUI};
1712 case Intrinsic::nvvm_i2d_rz:
1713 case Intrinsic::nvvm_i2f_rz:
1714 case Intrinsic::nvvm_ll2d_rz:
1715 case Intrinsic::nvvm_ll2f_rz:
1716 return {Instruction::SIToFP};
1717 case Intrinsic::nvvm_ui2d_rz:
1718 case Intrinsic::nvvm_ui2f_rz:
1719 case Intrinsic::nvvm_ull2d_rz:
1720 case Intrinsic::nvvm_ull2f_rz:
1721 return {Instruction::UIToFP};
1722
1723 // NVVM intrinsics that map to LLVM binary ops.
1724 case Intrinsic::nvvm_add_rn_d:
1725 return {Instruction::FAdd, FTZ_Any};
1726 case Intrinsic::nvvm_add_rn_f:
1727 return {Instruction::FAdd, FTZ_MustBeOff};
1728 case Intrinsic::nvvm_add_rn_ftz_f:
1729 return {Instruction::FAdd, FTZ_MustBeOn};
1730 case Intrinsic::nvvm_mul_rn_d:
1731 return {Instruction::FMul, FTZ_Any};
1732 case Intrinsic::nvvm_mul_rn_f:
1733 return {Instruction::FMul, FTZ_MustBeOff};
1734 case Intrinsic::nvvm_mul_rn_ftz_f:
1735 return {Instruction::FMul, FTZ_MustBeOn};
1736 case Intrinsic::nvvm_div_rn_d:
1737 return {Instruction::FDiv, FTZ_Any};
1738 case Intrinsic::nvvm_div_rn_f:
1739 return {Instruction::FDiv, FTZ_MustBeOff};
1740 case Intrinsic::nvvm_div_rn_ftz_f:
1741 return {Instruction::FDiv, FTZ_MustBeOn};
1742
1743 // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1744 // need special handling.
1745 //
1746 // We seem to be mising intrinsics for rcp.approx.{ftz.}f32, which is just
1747 // as well.
1748 case Intrinsic::nvvm_rcp_rn_d:
1749 return {SPC_Reciprocal, FTZ_Any};
1750 case Intrinsic::nvvm_rcp_rn_f:
1751 return {SPC_Reciprocal, FTZ_MustBeOff};
1752 case Intrinsic::nvvm_rcp_rn_ftz_f:
1753 return {SPC_Reciprocal, FTZ_MustBeOn};
1754
1755 // We do not currently simplify intrinsics that give an approximate answer.
1756 // These include:
1757 //
1758 // - nvvm_cos_approx_{f,ftz_f}
1759 // - nvvm_ex2_approx_{d,f,ftz_f}
1760 // - nvvm_lg2_approx_{d,f,ftz_f}
1761 // - nvvm_sin_approx_{f,ftz_f}
1762 // - nvvm_sqrt_approx_{f,ftz_f}
1763 // - nvvm_rsqrt_approx_{d,f,ftz_f}
1764 // - nvvm_div_approx_{ftz_d,ftz_f,f}
1765 // - nvvm_rcp_approx_ftz_d
1766 //
1767 // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1768 // means that fastmath is enabled in the intrinsic. Unfortunately only
1769 // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1770 // information gets lost and we can't select on it.
1771 //
1772 // TODO: div and rcp are lowered to a binary op, so these we could in theory
1773 // lower them to "fast fdiv".
1774
1775 default:
1776 return {};
1777 }
1778 }();
1779
1780 // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1781 // can bail out now. (Notice that in the case that IID is not an NVVM
1782 // intrinsic, we don't have to look up any module metadata, as
1783 // FtzRequirementTy will be FTZ_Any.)
1784 if (Action.FtzRequirement != FTZ_Any) {
1785 bool FtzEnabled =
1786 II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1787 "true";
1788
1789 if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1790 return nullptr;
1791 }
1792
1793 // Simplify to target-generic intrinsic.
1794 if (Action.IID) {
1795 SmallVector<Value *, 4> Args(II->arg_operands());
1796 // All the target-generic intrinsics currently of interest to us have one
1797 // type argument, equal to that of the nvvm intrinsic's argument.
Justin Lebare3ac0fb2017-01-27 01:49:39 +00001798 Type *Tys[] = {II->getArgOperand(0)->getType()};
Justin Lebar698c31b2017-01-27 00:58:58 +00001799 return CallInst::Create(
1800 Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1801 }
1802
1803 // Simplify to target-generic binary op.
1804 if (Action.BinaryOp)
1805 return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1806 II->getArgOperand(1), II->getName());
1807
1808 // Simplify to target-generic cast op.
1809 if (Action.CastOp)
1810 return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1811 II->getName());
1812
1813 // All that's left are the special cases.
1814 if (!Action.Special)
1815 return nullptr;
1816
1817 switch (*Action.Special) {
1818 case SPC_Reciprocal:
1819 // Simplify reciprocal.
1820 return BinaryOperator::Create(
1821 Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1822 II->getArgOperand(0), II->getName());
1823 }
Justin Lebar25ebe2d2017-01-27 02:04:07 +00001824 llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
Justin Lebar698c31b2017-01-27 00:58:58 +00001825}
1826
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00001827Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1828 removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1829 return nullptr;
1830}
1831
1832Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1833 removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1834 return nullptr;
1835}
1836
Sanjay Patelcd4377c2016-01-20 22:24:38 +00001837/// CallInst simplification. This mostly only handles folding of intrinsic
1838/// instructions. For normal calls, it allows visitCallSite to do the heavy
1839/// lifting.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001840Instruction *InstCombiner::visitCallInst(CallInst &CI) {
David Majnemer15032582015-05-22 03:56:46 +00001841 auto Args = CI.arg_operands();
1842 if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001843 &TLI, &DT, &AC))
Sanjay Patel4b198802016-02-01 22:23:39 +00001844 return replaceInstUsesWith(CI, V);
David Majnemer15032582015-05-22 03:56:46 +00001845
Justin Bogner99798402016-08-05 01:06:44 +00001846 if (isFreeCall(&CI, &TLI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001847 return visitFree(CI);
1848
1849 // If the caller function is nounwind, mark the call as nounwind, even if the
1850 // callee isn't.
Sanjay Patel5a470952016-08-11 15:16:06 +00001851 if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001852 CI.setDoesNotThrow();
1853 return &CI;
1854 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001855
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001856 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1857 if (!II) return visitCallSite(&CI);
Gabor Greif589a0b92010-06-24 12:58:35 +00001858
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001859 // Intrinsics cannot occur in an invoke, so handle them here instead of in
1860 // visitCallSite.
1861 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1862 bool Changed = false;
1863
1864 // memmove/cpy/set of zero bytes is a noop.
1865 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattnerc663a672010-10-01 05:51:02 +00001866 if (NumBytes->isNullValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00001867 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001868
1869 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1870 if (CI->getZExtValue() == 1) {
1871 // Replace the instruction with just byte operations. We would
1872 // transform other cases to loads/stores, but we don't know if
1873 // alignment is sufficient.
1874 }
1875 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001876
Chris Lattnerc663a672010-10-01 05:51:02 +00001877 // No other transformations apply to volatile transfers.
1878 if (MI->isVolatile())
Craig Topperf40110f2014-04-25 05:29:35 +00001879 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001880
1881 // If we have a memmove and the source operation is a constant global,
1882 // then the source and dest pointers can't alias, so we can change this
1883 // into a call to memcpy.
1884 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1885 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1886 if (GVSrc->isConstant()) {
Sanjay Patelaf674fb2015-12-14 17:24:23 +00001887 Module *M = CI.getModule();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001888 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foadb804a2b2011-07-12 14:06:48 +00001889 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1890 CI.getArgOperand(1)->getType(),
1891 CI.getArgOperand(2)->getType() };
Benjamin Kramere6e19332011-07-14 17:45:39 +00001892 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001893 Changed = true;
1894 }
1895 }
1896
1897 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1898 // memmove(x,x,size) -> noop.
1899 if (MTI->getSource() == MTI->getDest())
Sanjay Patel4b198802016-02-01 22:23:39 +00001900 return eraseInstFromFunction(CI);
Eric Christopher7258dcd2010-04-16 23:37:20 +00001901 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001902
Eric Christopher7258dcd2010-04-16 23:37:20 +00001903 // If we can determine a pointer alignment that is bigger than currently
1904 // set, update the alignment.
Pete Cooper67cf9a72015-11-19 05:56:52 +00001905 if (isa<MemTransferInst>(MI)) {
1906 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001907 return I;
1908 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1909 if (Instruction *I = SimplifyMemSet(MSI))
1910 return I;
1911 }
Gabor Greif590d95e2010-06-24 13:42:49 +00001912
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001913 if (Changed) return II;
1914 }
Jim Grosbach7815f562012-02-03 00:07:04 +00001915
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001916 if (auto *AMI = dyn_cast<ElementAtomicMemCpyInst>(II)) {
1917 if (Constant *C = dyn_cast<Constant>(AMI->getNumElements()))
1918 if (C->isNullValue())
1919 return eraseInstFromFunction(*AMI);
Igor Laevsky900ffa32017-02-08 14:32:04 +00001920
1921 if (Instruction *I = SimplifyElementAtomicMemCpy(AMI))
1922 return I;
Igor Laevsky4b317fa2017-02-08 14:23:47 +00001923 }
1924
Justin Lebar698c31b2017-01-27 00:58:58 +00001925 if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1926 return I;
1927
Sanjay Patel1c600c62016-01-20 16:41:43 +00001928 auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1929 unsigned DemandedWidth) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00001930 APInt UndefElts(Width, 0);
1931 APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1932 return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1933 };
1934
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001935 switch (II->getIntrinsicID()) {
1936 default: break;
George Burgess IV3f089142016-12-20 23:46:36 +00001937 case Intrinsic::objectsize:
1938 if (ConstantInt *N =
1939 lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1940 return replaceInstUsesWith(CI, N);
Craig Topperf40110f2014-04-25 05:29:35 +00001941 return nullptr;
George Burgess IV3f089142016-12-20 23:46:36 +00001942
Michael Ilseman536cc322012-12-13 03:13:36 +00001943 case Intrinsic::bswap: {
1944 Value *IIOperand = II->getArgOperand(0);
Craig Topperf40110f2014-04-25 05:29:35 +00001945 Value *X = nullptr;
Michael Ilseman536cc322012-12-13 03:13:36 +00001946
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001947 // bswap(bswap(x)) -> x
Michael Ilseman536cc322012-12-13 03:13:36 +00001948 if (match(IIOperand, m_BSwap(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001949 return replaceInstUsesWith(CI, X);
Jim Grosbach7815f562012-02-03 00:07:04 +00001950
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001951 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Michael Ilseman536cc322012-12-13 03:13:36 +00001952 if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1953 unsigned C = X->getType()->getPrimitiveSizeInBits() -
1954 IIOperand->getType()->getPrimitiveSizeInBits();
1955 Value *CV = ConstantInt::get(X->getType(), C);
1956 Value *V = Builder->CreateLShr(X, CV);
1957 return new TruncInst(V, IIOperand->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001958 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001959 break;
Michael Ilseman536cc322012-12-13 03:13:36 +00001960 }
1961
James Molloy2d09c002015-11-12 12:39:41 +00001962 case Intrinsic::bitreverse: {
1963 Value *IIOperand = II->getArgOperand(0);
1964 Value *X = nullptr;
1965
1966 // bitreverse(bitreverse(x)) -> x
1967 if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
Sanjay Patel4b198802016-02-01 22:23:39 +00001968 return replaceInstUsesWith(CI, X);
James Molloy2d09c002015-11-12 12:39:41 +00001969 break;
1970 }
1971
Sanjay Patelb695c552016-02-01 17:00:10 +00001972 case Intrinsic::masked_load:
1973 if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00001974 return replaceInstUsesWith(CI, SimplifiedMaskedOp);
Sanjay Patelb695c552016-02-01 17:00:10 +00001975 break;
Sanjay Patel04f792b2016-02-01 19:39:52 +00001976 case Intrinsic::masked_store:
1977 return simplifyMaskedStore(*II, *this);
Sanjay Patel103ab7d2016-02-01 22:10:26 +00001978 case Intrinsic::masked_gather:
1979 return simplifyMaskedGather(*II, *this);
1980 case Intrinsic::masked_scatter:
1981 return simplifyMaskedScatter(*II, *this);
Sanjay Patelb695c552016-02-01 17:00:10 +00001982
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001983 case Intrinsic::powi:
Gabor Greif589a0b92010-06-24 12:58:35 +00001984 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001985 // powi(x, 0) -> 1.0
1986 if (Power->isZero())
Sanjay Patel4b198802016-02-01 22:23:39 +00001987 return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001988 // powi(x, 1) -> x
1989 if (Power->isOne())
Sanjay Patel4b198802016-02-01 22:23:39 +00001990 return replaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001991 // powi(x, -1) -> 1/x
1992 if (Power->isAllOnesValue())
1993 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greif589a0b92010-06-24 12:58:35 +00001994 II->getArgOperand(0));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00001995 }
1996 break;
Jim Grosbach7815f562012-02-03 00:07:04 +00001997
Sanjay Patel8e3ab172016-08-05 22:42:46 +00001998 case Intrinsic::cttz:
1999 case Intrinsic::ctlz:
Amaury Sechet763c59d2016-08-18 20:43:50 +00002000 if (auto *I = foldCttzCtlz(*II, *this))
2001 return I;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002002 break;
Sanjoy Dasb0984472015-04-08 04:27:22 +00002003
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002004 case Intrinsic::uadd_with_overflow:
2005 case Intrinsic::sadd_with_overflow:
2006 case Intrinsic::umul_with_overflow:
2007 case Intrinsic::smul_with_overflow:
Gabor Greif5b1370e2010-06-28 16:50:57 +00002008 if (isa<Constant>(II->getArgOperand(0)) &&
2009 !isa<Constant>(II->getArgOperand(1))) {
Sanjoy Dasb0984472015-04-08 04:27:22 +00002010 // Canonicalize constants into the RHS.
Gabor Greif5b1370e2010-06-28 16:50:57 +00002011 Value *LHS = II->getArgOperand(0);
2012 II->setArgOperand(0, II->getArgOperand(1));
2013 II->setArgOperand(1, LHS);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002014 return II;
2015 }
Justin Bognercd1d5aa2016-08-17 20:30:52 +00002016 LLVM_FALLTHROUGH;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002017
Nick Lewyckyabe2cc12015-04-13 19:17:37 +00002018 case Intrinsic::usub_with_overflow:
2019 case Intrinsic::ssub_with_overflow: {
Sanjoy Dasb0984472015-04-08 04:27:22 +00002020 OverflowCheckFlavor OCF =
2021 IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
2022 assert(OCF != OCF_INVALID && "unexpected!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002023
Sanjoy Dasb0984472015-04-08 04:27:22 +00002024 Value *OperationResult = nullptr;
2025 Constant *OverflowResult = nullptr;
2026 if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
2027 *II, OperationResult, OverflowResult))
2028 return CreateOverflowTuple(II, OperationResult, OverflowResult);
Benjamin Kramera420df22014-07-04 10:22:21 +00002029
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002030 break;
Erik Eckstein096ff7d2014-12-11 08:02:30 +00002031 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002032
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002033 case Intrinsic::minnum:
2034 case Intrinsic::maxnum: {
2035 Value *Arg0 = II->getArgOperand(0);
2036 Value *Arg1 = II->getArgOperand(1);
Sanjay Patel0069f562016-01-31 16:35:23 +00002037 // Canonicalize constants to the RHS.
2038 if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002039 II->setArgOperand(0, Arg1);
2040 II->setArgOperand(1, Arg0);
2041 return II;
2042 }
Sanjay Patel0069f562016-01-31 16:35:23 +00002043 if (Value *V = simplifyMinnumMaxnum(*II))
Sanjay Patel4b198802016-02-01 22:23:39 +00002044 return replaceInstUsesWith(*II, V);
Matt Arsenaultd6511b42014-10-21 23:00:20 +00002045 break;
2046 }
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002047 case Intrinsic::fma:
2048 case Intrinsic::fmuladd: {
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002049 Value *Src0 = II->getArgOperand(0);
2050 Value *Src1 = II->getArgOperand(1);
2051
Matt Arsenaultb264c942017-01-03 04:32:35 +00002052 // Canonicalize constants into the RHS.
2053 if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
2054 II->setArgOperand(0, Src1);
2055 II->setArgOperand(1, Src0);
2056 std::swap(Src0, Src1);
2057 }
2058
2059 Value *LHS = nullptr;
2060 Value *RHS = nullptr;
2061
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002062 // fma fneg(x), fneg(y), z -> fma x, y, z
2063 if (match(Src0, m_FNeg(m_Value(LHS))) &&
2064 match(Src1, m_FNeg(m_Value(RHS)))) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002065 II->setArgOperand(0, LHS);
2066 II->setArgOperand(1, RHS);
2067 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002068 }
2069
2070 // fma fabs(x), fabs(x), z -> fma x, x, z
2071 if (match(Src0, m_Intrinsic<Intrinsic::fabs>(m_Value(LHS))) &&
2072 match(Src1, m_Intrinsic<Intrinsic::fabs>(m_Value(RHS))) && LHS == RHS) {
Matt Arsenault3f509042017-01-10 23:17:52 +00002073 II->setArgOperand(0, LHS);
2074 II->setArgOperand(1, RHS);
2075 return II;
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002076 }
2077
Matt Arsenaultb264c942017-01-03 04:32:35 +00002078 // fma x, 1, z -> fadd x, z
2079 if (match(Src1, m_FPOne())) {
2080 Instruction *RI = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2081 RI->copyFastMathFlags(II);
2082 return RI;
2083 }
2084
Matt Arsenault1cc294c2017-01-03 04:32:31 +00002085 break;
2086 }
Matt Arsenault56ff4832017-01-03 22:40:34 +00002087 case Intrinsic::fabs: {
2088 Value *Cond;
2089 Constant *LHS, *RHS;
2090 if (match(II->getArgOperand(0),
2091 m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
2092 CallInst *Call0 = Builder->CreateCall(II->getCalledFunction(), {LHS});
2093 CallInst *Call1 = Builder->CreateCall(II->getCalledFunction(), {RHS});
2094 return SelectInst::Create(Cond, Call0, Call1);
2095 }
2096
Matt Arsenault954a6242017-01-23 23:55:08 +00002097 LLVM_FALLTHROUGH;
2098 }
2099 case Intrinsic::ceil:
2100 case Intrinsic::floor:
2101 case Intrinsic::round:
2102 case Intrinsic::nearbyint:
2103 case Intrinsic::trunc: {
Matt Arsenault72333442017-01-17 00:10:40 +00002104 Value *ExtSrc;
2105 if (match(II->getArgOperand(0), m_FPExt(m_Value(ExtSrc))) &&
2106 II->getArgOperand(0)->hasOneUse()) {
2107 // fabs (fpext x) -> fpext (fabs x)
Matt Arsenault954a6242017-01-23 23:55:08 +00002108 Value *F = Intrinsic::getDeclaration(II->getModule(), II->getIntrinsicID(),
Matt Arsenault72333442017-01-17 00:10:40 +00002109 { ExtSrc->getType() });
2110 CallInst *NewFabs = Builder->CreateCall(F, ExtSrc);
2111 NewFabs->copyFastMathFlags(II);
2112 NewFabs->takeName(II);
2113 return new FPExtInst(NewFabs, II->getType());
2114 }
2115
Matt Arsenault56ff4832017-01-03 22:40:34 +00002116 break;
2117 }
Matt Arsenault3bdd75d2017-01-04 22:49:03 +00002118 case Intrinsic::cos:
2119 case Intrinsic::amdgcn_cos: {
2120 Value *SrcSrc;
2121 Value *Src = II->getArgOperand(0);
2122 if (match(Src, m_FNeg(m_Value(SrcSrc))) ||
2123 match(Src, m_Intrinsic<Intrinsic::fabs>(m_Value(SrcSrc)))) {
2124 // cos(-x) -> cos(x)
2125 // cos(fabs(x)) -> cos(x)
2126 II->setArgOperand(0, SrcSrc);
2127 return II;
2128 }
2129
2130 break;
2131 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002132 case Intrinsic::ppc_altivec_lvx:
2133 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingb902f1d2011-04-13 00:36:11 +00002134 // Turn PPC lvx -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002135 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002136 &DT) >= 16) {
Gabor Greif589a0b92010-06-24 12:58:35 +00002137 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002138 PointerType::getUnqual(II->getType()));
2139 return new LoadInst(Ptr);
2140 }
2141 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002142 case Intrinsic::ppc_vsx_lxvw4x:
2143 case Intrinsic::ppc_vsx_lxvd2x: {
2144 // Turn PPC VSX loads into normal loads.
2145 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2146 PointerType::getUnqual(II->getType()));
2147 return new LoadInst(Ptr, Twine(""), false, 1);
2148 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002149 case Intrinsic::ppc_altivec_stvx:
2150 case Intrinsic::ppc_altivec_stvxl:
2151 // Turn stvx -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002152 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002153 &DT) >= 16) {
Jim Grosbach7815f562012-02-03 00:07:04 +00002154 Type *OpPtrTy =
Gabor Greifa6d75e22010-06-24 15:51:11 +00002155 PointerType::getUnqual(II->getArgOperand(0)->getType());
2156 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2157 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002158 }
2159 break;
Bill Schmidt72954782014-11-12 04:19:40 +00002160 case Intrinsic::ppc_vsx_stxvw4x:
2161 case Intrinsic::ppc_vsx_stxvd2x: {
2162 // Turn PPC VSX stores into normal stores.
2163 Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
2164 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2165 return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2166 }
Hal Finkel221f4672015-02-26 18:56:03 +00002167 case Intrinsic::ppc_qpx_qvlfs:
2168 // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002169 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002170 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00002171 Type *VTy = VectorType::get(Builder->getFloatTy(),
2172 II->getType()->getVectorNumElements());
Hal Finkel221f4672015-02-26 18:56:03 +00002173 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Hal Finkelf0d68d72015-05-11 06:37:03 +00002174 PointerType::getUnqual(VTy));
2175 Value *Load = Builder->CreateLoad(Ptr);
2176 return new FPExtInst(Load, II->getType());
Hal Finkel221f4672015-02-26 18:56:03 +00002177 }
2178 break;
2179 case Intrinsic::ppc_qpx_qvlfd:
2180 // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002181 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002182 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002183 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
2184 PointerType::getUnqual(II->getType()));
2185 return new LoadInst(Ptr);
2186 }
2187 break;
2188 case Intrinsic::ppc_qpx_qvstfs:
2189 // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002190 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002191 &DT) >= 16) {
Hal Finkelf0d68d72015-05-11 06:37:03 +00002192 Type *VTy = VectorType::get(Builder->getFloatTy(),
2193 II->getArgOperand(0)->getType()->getVectorNumElements());
2194 Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
2195 Type *OpPtrTy = PointerType::getUnqual(VTy);
Hal Finkel221f4672015-02-26 18:56:03 +00002196 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
Hal Finkelf0d68d72015-05-11 06:37:03 +00002197 return new StoreInst(TOp, Ptr);
Hal Finkel221f4672015-02-26 18:56:03 +00002198 }
2199 break;
2200 case Intrinsic::ppc_qpx_qvstfd:
2201 // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
Daniel Jasperaec2fa32016-12-19 08:22:17 +00002202 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
Justin Bogner99798402016-08-05 01:06:44 +00002203 &DT) >= 32) {
Hal Finkel221f4672015-02-26 18:56:03 +00002204 Type *OpPtrTy =
2205 PointerType::getUnqual(II->getArgOperand(0)->getType());
2206 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
2207 return new StoreInst(II->getArgOperand(0), Ptr);
2208 }
2209 break;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002210
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002211 case Intrinsic::x86_vcvtph2ps_128:
2212 case Intrinsic::x86_vcvtph2ps_256: {
2213 auto Arg = II->getArgOperand(0);
2214 auto ArgType = cast<VectorType>(Arg->getType());
2215 auto RetType = cast<VectorType>(II->getType());
2216 unsigned ArgWidth = ArgType->getNumElements();
2217 unsigned RetWidth = RetType->getNumElements();
2218 assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2219 assert(ArgType->isIntOrIntVectorTy() &&
2220 ArgType->getScalarSizeInBits() == 16 &&
2221 "CVTPH2PS input type should be 16-bit integer vector");
2222 assert(RetType->getScalarType()->isFloatTy() &&
2223 "CVTPH2PS output type should be 32-bit float vector");
2224
2225 // Constant folding: Convert to generic half to single conversion.
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002226 if (isa<ConstantAggregateZero>(Arg))
Sanjay Patel4b198802016-02-01 22:23:39 +00002227 return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002228
Simon Pilgrim48ffca02015-09-12 14:00:17 +00002229 if (isa<ConstantDataVector>(Arg)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002230 auto VectorHalfAsShorts = Arg;
2231 if (RetWidth < ArgWidth) {
Craig Topper99d1eab2016-06-12 00:41:19 +00002232 SmallVector<uint32_t, 8> SubVecMask;
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002233 for (unsigned i = 0; i != RetWidth; ++i)
2234 SubVecMask.push_back((int)i);
2235 VectorHalfAsShorts = Builder->CreateShuffleVector(
2236 Arg, UndefValue::get(ArgType), SubVecMask);
2237 }
2238
2239 auto VectorHalfType =
2240 VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2241 auto VectorHalfs =
2242 Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2243 auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
Sanjay Patel4b198802016-02-01 22:23:39 +00002244 return replaceInstUsesWith(*II, VectorFloats);
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002245 }
2246
2247 // We only use the lowest lanes of the argument.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002248 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
Simon Pilgrim20c607b2015-09-12 13:39:53 +00002249 II->setArgOperand(0, V);
2250 return II;
2251 }
2252 break;
2253 }
2254
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002255 case Intrinsic::x86_sse_cvtss2si:
2256 case Intrinsic::x86_sse_cvtss2si64:
2257 case Intrinsic::x86_sse_cvttss2si:
2258 case Intrinsic::x86_sse_cvttss2si64:
2259 case Intrinsic::x86_sse2_cvtsd2si:
2260 case Intrinsic::x86_sse2_cvtsd2si64:
2261 case Intrinsic::x86_sse2_cvttsd2si:
Craig Topperaeaa52c2016-12-14 07:46:12 +00002262 case Intrinsic::x86_sse2_cvttsd2si64:
2263 case Intrinsic::x86_avx512_vcvtss2si32:
2264 case Intrinsic::x86_avx512_vcvtss2si64:
2265 case Intrinsic::x86_avx512_vcvtss2usi32:
2266 case Intrinsic::x86_avx512_vcvtss2usi64:
2267 case Intrinsic::x86_avx512_vcvtsd2si32:
2268 case Intrinsic::x86_avx512_vcvtsd2si64:
2269 case Intrinsic::x86_avx512_vcvtsd2usi32:
2270 case Intrinsic::x86_avx512_vcvtsd2usi64:
2271 case Intrinsic::x86_avx512_cvttss2si:
2272 case Intrinsic::x86_avx512_cvttss2si64:
2273 case Intrinsic::x86_avx512_cvttss2usi:
2274 case Intrinsic::x86_avx512_cvttss2usi64:
2275 case Intrinsic::x86_avx512_cvttsd2si:
2276 case Intrinsic::x86_avx512_cvttsd2si64:
2277 case Intrinsic::x86_avx512_cvttsd2usi:
2278 case Intrinsic::x86_avx512_cvttsd2usi64: {
Chandler Carruthcf414cf2011-01-10 07:19:37 +00002279 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002280 // we can simplify the input based on that, do so now.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002281 Value *Arg = II->getArgOperand(0);
2282 unsigned VWidth = Arg->getType()->getVectorNumElements();
2283 if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
Gabor Greif5b1370e2010-06-28 16:50:57 +00002284 II->setArgOperand(0, V);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002285 return II;
2286 }
Simon Pilgrim18617d12015-08-05 08:18:00 +00002287 break;
2288 }
2289
Simon Pilgrim91e3ac82016-06-07 08:18:35 +00002290 case Intrinsic::x86_mmx_pmovmskb:
2291 case Intrinsic::x86_sse_movmsk_ps:
2292 case Intrinsic::x86_sse2_movmsk_pd:
2293 case Intrinsic::x86_sse2_pmovmskb_128:
2294 case Intrinsic::x86_avx_movmsk_pd_256:
2295 case Intrinsic::x86_avx_movmsk_ps_256:
2296 case Intrinsic::x86_avx2_pmovmskb: {
2297 if (Value *V = simplifyX86movmsk(*II, *Builder))
2298 return replaceInstUsesWith(*II, V);
2299 break;
2300 }
2301
Simon Pilgrim471efd22016-02-20 23:17:35 +00002302 case Intrinsic::x86_sse_comieq_ss:
2303 case Intrinsic::x86_sse_comige_ss:
2304 case Intrinsic::x86_sse_comigt_ss:
2305 case Intrinsic::x86_sse_comile_ss:
2306 case Intrinsic::x86_sse_comilt_ss:
2307 case Intrinsic::x86_sse_comineq_ss:
2308 case Intrinsic::x86_sse_ucomieq_ss:
2309 case Intrinsic::x86_sse_ucomige_ss:
2310 case Intrinsic::x86_sse_ucomigt_ss:
2311 case Intrinsic::x86_sse_ucomile_ss:
2312 case Intrinsic::x86_sse_ucomilt_ss:
2313 case Intrinsic::x86_sse_ucomineq_ss:
2314 case Intrinsic::x86_sse2_comieq_sd:
2315 case Intrinsic::x86_sse2_comige_sd:
2316 case Intrinsic::x86_sse2_comigt_sd:
2317 case Intrinsic::x86_sse2_comile_sd:
2318 case Intrinsic::x86_sse2_comilt_sd:
2319 case Intrinsic::x86_sse2_comineq_sd:
2320 case Intrinsic::x86_sse2_ucomieq_sd:
2321 case Intrinsic::x86_sse2_ucomige_sd:
2322 case Intrinsic::x86_sse2_ucomigt_sd:
2323 case Intrinsic::x86_sse2_ucomile_sd:
2324 case Intrinsic::x86_sse2_ucomilt_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002325 case Intrinsic::x86_sse2_ucomineq_sd:
Craig Topperd00db692016-12-31 00:45:06 +00002326 case Intrinsic::x86_avx512_vcomi_ss:
2327 case Intrinsic::x86_avx512_vcomi_sd:
Craig Topperd9639532016-12-11 07:42:04 +00002328 case Intrinsic::x86_avx512_mask_cmp_ss:
2329 case Intrinsic::x86_avx512_mask_cmp_sd: {
Simon Pilgrim471efd22016-02-20 23:17:35 +00002330 // These intrinsics only demand the 0th element of their input vectors. If
2331 // we can simplify the input based on that, do so now.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002332 bool MadeChange = false;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002333 Value *Arg0 = II->getArgOperand(0);
2334 Value *Arg1 = II->getArgOperand(1);
2335 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2336 if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2337 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002338 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002339 }
2340 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2341 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002342 MadeChange = true;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002343 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002344 if (MadeChange)
2345 return II;
Simon Pilgrim471efd22016-02-20 23:17:35 +00002346 break;
2347 }
2348
Craig Topper020b2282016-12-27 00:23:16 +00002349 case Intrinsic::x86_avx512_mask_add_ps_512:
2350 case Intrinsic::x86_avx512_mask_div_ps_512:
2351 case Intrinsic::x86_avx512_mask_mul_ps_512:
2352 case Intrinsic::x86_avx512_mask_sub_ps_512:
2353 case Intrinsic::x86_avx512_mask_add_pd_512:
2354 case Intrinsic::x86_avx512_mask_div_pd_512:
2355 case Intrinsic::x86_avx512_mask_mul_pd_512:
2356 case Intrinsic::x86_avx512_mask_sub_pd_512:
2357 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2358 // IR operations.
2359 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2360 if (R->getValue() == 4) {
2361 Value *Arg0 = II->getArgOperand(0);
2362 Value *Arg1 = II->getArgOperand(1);
2363
2364 Value *V;
2365 switch (II->getIntrinsicID()) {
2366 default: llvm_unreachable("Case stmts out of sync!");
2367 case Intrinsic::x86_avx512_mask_add_ps_512:
2368 case Intrinsic::x86_avx512_mask_add_pd_512:
2369 V = Builder->CreateFAdd(Arg0, Arg1);
2370 break;
2371 case Intrinsic::x86_avx512_mask_sub_ps_512:
2372 case Intrinsic::x86_avx512_mask_sub_pd_512:
2373 V = Builder->CreateFSub(Arg0, Arg1);
2374 break;
2375 case Intrinsic::x86_avx512_mask_mul_ps_512:
2376 case Intrinsic::x86_avx512_mask_mul_pd_512:
2377 V = Builder->CreateFMul(Arg0, Arg1);
2378 break;
2379 case Intrinsic::x86_avx512_mask_div_ps_512:
2380 case Intrinsic::x86_avx512_mask_div_pd_512:
2381 V = Builder->CreateFDiv(Arg0, Arg1);
2382 break;
2383 }
2384
2385 // Create a select for the masking.
2386 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2387 *Builder);
2388 return replaceInstUsesWith(*II, V);
2389 }
2390 }
2391 break;
2392
Craig Topper790d0fa2016-12-11 07:42:01 +00002393 case Intrinsic::x86_avx512_mask_add_ss_round:
2394 case Intrinsic::x86_avx512_mask_div_ss_round:
2395 case Intrinsic::x86_avx512_mask_mul_ss_round:
2396 case Intrinsic::x86_avx512_mask_sub_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002397 case Intrinsic::x86_avx512_mask_add_sd_round:
2398 case Intrinsic::x86_avx512_mask_div_sd_round:
2399 case Intrinsic::x86_avx512_mask_mul_sd_round:
2400 case Intrinsic::x86_avx512_mask_sub_sd_round:
Craig Topper7b788ada2016-12-26 06:33:19 +00002401 // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2402 // IR operations.
2403 if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2404 if (R->getValue() == 4) {
Craig Topper7f8540b2016-12-27 01:56:30 +00002405 // Extract the element as scalars.
2406 Value *Arg0 = II->getArgOperand(0);
2407 Value *Arg1 = II->getArgOperand(1);
2408 Value *LHS = Builder->CreateExtractElement(Arg0, (uint64_t)0);
2409 Value *RHS = Builder->CreateExtractElement(Arg1, (uint64_t)0);
Craig Topper7b788ada2016-12-26 06:33:19 +00002410
Craig Topper7f8540b2016-12-27 01:56:30 +00002411 Value *V;
2412 switch (II->getIntrinsicID()) {
2413 default: llvm_unreachable("Case stmts out of sync!");
2414 case Intrinsic::x86_avx512_mask_add_ss_round:
2415 case Intrinsic::x86_avx512_mask_add_sd_round:
2416 V = Builder->CreateFAdd(LHS, RHS);
2417 break;
2418 case Intrinsic::x86_avx512_mask_sub_ss_round:
2419 case Intrinsic::x86_avx512_mask_sub_sd_round:
2420 V = Builder->CreateFSub(LHS, RHS);
2421 break;
2422 case Intrinsic::x86_avx512_mask_mul_ss_round:
2423 case Intrinsic::x86_avx512_mask_mul_sd_round:
2424 V = Builder->CreateFMul(LHS, RHS);
2425 break;
2426 case Intrinsic::x86_avx512_mask_div_ss_round:
2427 case Intrinsic::x86_avx512_mask_div_sd_round:
2428 V = Builder->CreateFDiv(LHS, RHS);
2429 break;
Craig Topper7b788ada2016-12-26 06:33:19 +00002430 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002431
2432 // Handle the masking aspect of the intrinsic.
Craig Topper7f8540b2016-12-27 01:56:30 +00002433 Value *Mask = II->getArgOperand(3);
Craig Topper99163632016-12-30 23:06:28 +00002434 auto *C = dyn_cast<ConstantInt>(Mask);
2435 // We don't need a select if we know the mask bit is a 1.
2436 if (!C || !C->getValue()[0]) {
2437 // Cast the mask to an i1 vector and then extract the lowest element.
2438 auto *MaskTy = VectorType::get(Builder->getInt1Ty(),
Craig Topper7f8540b2016-12-27 01:56:30 +00002439 cast<IntegerType>(Mask->getType())->getBitWidth());
Craig Topper99163632016-12-30 23:06:28 +00002440 Mask = Builder->CreateBitCast(Mask, MaskTy);
2441 Mask = Builder->CreateExtractElement(Mask, (uint64_t)0);
2442 // Extract the lowest element from the passthru operand.
2443 Value *Passthru = Builder->CreateExtractElement(II->getArgOperand(2),
2444 (uint64_t)0);
2445 V = Builder->CreateSelect(Mask, V, Passthru);
2446 }
Craig Topper7f8540b2016-12-27 01:56:30 +00002447
2448 // Insert the result back into the original argument 0.
2449 V = Builder->CreateInsertElement(Arg0, V, (uint64_t)0);
2450
2451 return replaceInstUsesWith(*II, V);
Craig Topper7b788ada2016-12-26 06:33:19 +00002452 }
2453 }
2454 LLVM_FALLTHROUGH;
2455
2456 // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2457 case Intrinsic::x86_avx512_mask_max_ss_round:
2458 case Intrinsic::x86_avx512_mask_min_ss_round:
Craig Topper790d0fa2016-12-11 07:42:01 +00002459 case Intrinsic::x86_avx512_mask_max_sd_round:
Craig Topper268b3ab2016-12-14 06:06:58 +00002460 case Intrinsic::x86_avx512_mask_min_sd_round:
Craig Topperab5f3552016-12-15 03:49:45 +00002461 case Intrinsic::x86_avx512_mask_vfmadd_ss:
2462 case Intrinsic::x86_avx512_mask_vfmadd_sd:
2463 case Intrinsic::x86_avx512_maskz_vfmadd_ss:
2464 case Intrinsic::x86_avx512_maskz_vfmadd_sd:
2465 case Intrinsic::x86_avx512_mask3_vfmadd_ss:
2466 case Intrinsic::x86_avx512_mask3_vfmadd_sd:
2467 case Intrinsic::x86_avx512_mask3_vfmsub_ss:
2468 case Intrinsic::x86_avx512_mask3_vfmsub_sd:
2469 case Intrinsic::x86_avx512_mask3_vfnmsub_ss:
2470 case Intrinsic::x86_avx512_mask3_vfnmsub_sd:
Craig Topperdfd268d2016-12-14 05:43:05 +00002471 case Intrinsic::x86_fma_vfmadd_ss:
2472 case Intrinsic::x86_fma_vfmsub_ss:
2473 case Intrinsic::x86_fma_vfnmadd_ss:
2474 case Intrinsic::x86_fma_vfnmsub_ss:
2475 case Intrinsic::x86_fma_vfmadd_sd:
2476 case Intrinsic::x86_fma_vfmsub_sd:
2477 case Intrinsic::x86_fma_vfnmadd_sd:
2478 case Intrinsic::x86_fma_vfnmsub_sd:
Craig Toppera0372de2016-12-14 03:17:27 +00002479 case Intrinsic::x86_sse_cmp_ss:
2480 case Intrinsic::x86_sse_min_ss:
2481 case Intrinsic::x86_sse_max_ss:
2482 case Intrinsic::x86_sse2_cmp_sd:
2483 case Intrinsic::x86_sse2_min_sd:
2484 case Intrinsic::x86_sse2_max_sd:
Craig Toppereb6a20e2016-12-14 03:17:30 +00002485 case Intrinsic::x86_sse41_round_ss:
2486 case Intrinsic::x86_sse41_round_sd:
Craig Topperac75bca2016-12-13 07:45:45 +00002487 case Intrinsic::x86_xop_vfrcz_ss:
2488 case Intrinsic::x86_xop_vfrcz_sd: {
2489 unsigned VWidth = II->getType()->getVectorNumElements();
2490 APInt UndefElts(VWidth, 0);
2491 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2492 if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2493 if (V != II)
2494 return replaceInstUsesWith(*II, V);
2495 return II;
2496 }
2497 break;
2498 }
2499
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002500 // Constant fold ashr( <A x Bi>, Ci ).
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002501 // Constant fold lshr( <A x Bi>, Ci ).
2502 // Constant fold shl( <A x Bi>, Ci ).
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002503 case Intrinsic::x86_sse2_psrai_d:
2504 case Intrinsic::x86_sse2_psrai_w:
Simon Pilgrima3a72b42015-08-10 20:21:15 +00002505 case Intrinsic::x86_avx2_psrai_d:
2506 case Intrinsic::x86_avx2_psrai_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002507 case Intrinsic::x86_avx512_psrai_q_128:
2508 case Intrinsic::x86_avx512_psrai_q_256:
2509 case Intrinsic::x86_avx512_psrai_d_512:
2510 case Intrinsic::x86_avx512_psrai_q_512:
2511 case Intrinsic::x86_avx512_psrai_w_512:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002512 case Intrinsic::x86_sse2_psrli_d:
2513 case Intrinsic::x86_sse2_psrli_q:
2514 case Intrinsic::x86_sse2_psrli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002515 case Intrinsic::x86_avx2_psrli_d:
2516 case Intrinsic::x86_avx2_psrli_q:
2517 case Intrinsic::x86_avx2_psrli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002518 case Intrinsic::x86_avx512_psrli_d_512:
2519 case Intrinsic::x86_avx512_psrli_q_512:
2520 case Intrinsic::x86_avx512_psrli_w_512:
Michael J. Spencerdee4b2c2014-04-24 00:58:18 +00002521 case Intrinsic::x86_sse2_pslli_d:
2522 case Intrinsic::x86_sse2_pslli_q:
2523 case Intrinsic::x86_sse2_pslli_w:
Simon Pilgrim18617d12015-08-05 08:18:00 +00002524 case Intrinsic::x86_avx2_pslli_d:
2525 case Intrinsic::x86_avx2_pslli_q:
2526 case Intrinsic::x86_avx2_pslli_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002527 case Intrinsic::x86_avx512_pslli_d_512:
2528 case Intrinsic::x86_avx512_pslli_q_512:
2529 case Intrinsic::x86_avx512_pslli_w_512:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002530 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002531 return replaceInstUsesWith(*II, V);
Simon Pilgrim18617d12015-08-05 08:18:00 +00002532 break;
2533
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002534 case Intrinsic::x86_sse2_psra_d:
2535 case Intrinsic::x86_sse2_psra_w:
2536 case Intrinsic::x86_avx2_psra_d:
2537 case Intrinsic::x86_avx2_psra_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002538 case Intrinsic::x86_avx512_psra_q_128:
2539 case Intrinsic::x86_avx512_psra_q_256:
2540 case Intrinsic::x86_avx512_psra_d_512:
2541 case Intrinsic::x86_avx512_psra_q_512:
2542 case Intrinsic::x86_avx512_psra_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002543 case Intrinsic::x86_sse2_psrl_d:
2544 case Intrinsic::x86_sse2_psrl_q:
2545 case Intrinsic::x86_sse2_psrl_w:
2546 case Intrinsic::x86_avx2_psrl_d:
2547 case Intrinsic::x86_avx2_psrl_q:
2548 case Intrinsic::x86_avx2_psrl_w:
Craig Topper8b831cb2016-11-13 01:51:55 +00002549 case Intrinsic::x86_avx512_psrl_d_512:
2550 case Intrinsic::x86_avx512_psrl_q_512:
2551 case Intrinsic::x86_avx512_psrl_w_512:
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002552 case Intrinsic::x86_sse2_psll_d:
2553 case Intrinsic::x86_sse2_psll_q:
2554 case Intrinsic::x86_sse2_psll_w:
2555 case Intrinsic::x86_avx2_psll_d:
2556 case Intrinsic::x86_avx2_psll_q:
Craig Topper8b831cb2016-11-13 01:51:55 +00002557 case Intrinsic::x86_avx2_psll_w:
2558 case Intrinsic::x86_avx512_psll_d_512:
2559 case Intrinsic::x86_avx512_psll_q_512:
2560 case Intrinsic::x86_avx512_psll_w_512: {
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002561 if (Value *V = simplifyX86immShift(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002562 return replaceInstUsesWith(*II, V);
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002563
2564 // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2565 // operand to compute the shift amount.
Simon Pilgrim996725e2015-09-19 11:41:53 +00002566 Value *Arg1 = II->getArgOperand(1);
2567 assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002568 "Unexpected packed shift size");
Simon Pilgrim996725e2015-09-19 11:41:53 +00002569 unsigned VWidth = Arg1->getType()->getVectorNumElements();
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002570
Simon Pilgrim996725e2015-09-19 11:41:53 +00002571 if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
Simon Pilgrimbecd5e82015-08-13 07:39:03 +00002572 II->setArgOperand(1, V);
2573 return II;
2574 }
2575 break;
2576 }
2577
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002578 case Intrinsic::x86_avx2_psllv_d:
2579 case Intrinsic::x86_avx2_psllv_d_256:
2580 case Intrinsic::x86_avx2_psllv_q:
2581 case Intrinsic::x86_avx2_psllv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002582 case Intrinsic::x86_avx512_psllv_d_512:
2583 case Intrinsic::x86_avx512_psllv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002584 case Intrinsic::x86_avx512_psllv_w_128:
2585 case Intrinsic::x86_avx512_psllv_w_256:
2586 case Intrinsic::x86_avx512_psllv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002587 case Intrinsic::x86_avx2_psrav_d:
2588 case Intrinsic::x86_avx2_psrav_d_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002589 case Intrinsic::x86_avx512_psrav_q_128:
2590 case Intrinsic::x86_avx512_psrav_q_256:
2591 case Intrinsic::x86_avx512_psrav_d_512:
2592 case Intrinsic::x86_avx512_psrav_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002593 case Intrinsic::x86_avx512_psrav_w_128:
2594 case Intrinsic::x86_avx512_psrav_w_256:
2595 case Intrinsic::x86_avx512_psrav_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002596 case Intrinsic::x86_avx2_psrlv_d:
2597 case Intrinsic::x86_avx2_psrlv_d_256:
2598 case Intrinsic::x86_avx2_psrlv_q:
2599 case Intrinsic::x86_avx2_psrlv_q_256:
Craig Topperb4173a52016-11-13 07:26:19 +00002600 case Intrinsic::x86_avx512_psrlv_d_512:
2601 case Intrinsic::x86_avx512_psrlv_q_512:
Craig Topper1de753f2016-11-18 06:04:33 +00002602 case Intrinsic::x86_avx512_psrlv_w_128:
2603 case Intrinsic::x86_avx512_psrlv_w_256:
2604 case Intrinsic::x86_avx512_psrlv_w_512:
Simon Pilgrimdb9893f2016-06-07 10:27:15 +00002605 if (Value *V = simplifyX86varShift(*II, *Builder))
2606 return replaceInstUsesWith(*II, V);
2607 break;
2608
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002609 case Intrinsic::x86_sse2_pmulu_dq:
2610 case Intrinsic::x86_sse41_pmuldq:
2611 case Intrinsic::x86_avx2_pmul_dq:
Craig Topper72f2d4e2016-12-27 05:30:09 +00002612 case Intrinsic::x86_avx2_pmulu_dq:
2613 case Intrinsic::x86_avx512_pmul_dq_512:
2614 case Intrinsic::x86_avx512_pmulu_dq_512: {
Simon Pilgrimf6f3a3612017-01-23 15:22:59 +00002615 if (Value *V = simplifyX86muldq(*II, *Builder))
Simon Pilgrima50a93f2017-01-20 18:20:30 +00002616 return replaceInstUsesWith(*II, V);
2617
Simon Pilgrimc9cf7fc2016-12-26 23:28:17 +00002618 unsigned VWidth = II->getType()->getVectorNumElements();
2619 APInt UndefElts(VWidth, 0);
2620 APInt DemandedElts = APInt::getAllOnesValue(VWidth);
2621 if (Value *V = SimplifyDemandedVectorElts(II, DemandedElts, UndefElts)) {
2622 if (V != II)
2623 return replaceInstUsesWith(*II, V);
2624 return II;
2625 }
2626 break;
2627 }
2628
Simon Pilgrim6f6b2792017-01-25 14:37:24 +00002629 case Intrinsic::x86_sse2_packssdw_128:
2630 case Intrinsic::x86_sse2_packsswb_128:
2631 case Intrinsic::x86_avx2_packssdw:
2632 case Intrinsic::x86_avx2_packsswb:
2633 // TODO Add support for Intrinsic::x86_avx512_mask_packss*
2634 if (Value *V = simplifyX86pack(*II, *this, *Builder, true))
2635 return replaceInstUsesWith(*II, V);
2636 break;
2637
2638 case Intrinsic::x86_sse2_packuswb_128:
2639 case Intrinsic::x86_sse41_packusdw:
2640 case Intrinsic::x86_avx2_packusdw:
2641 case Intrinsic::x86_avx2_packuswb:
2642 // TODO Add support for Intrinsic::x86_avx512_mask_packus*
2643 if (Value *V = simplifyX86pack(*II, *this, *Builder, false))
2644 return replaceInstUsesWith(*II, V);
2645 break;
2646
Craig Topperb6122122017-01-26 05:17:13 +00002647 case Intrinsic::x86_pclmulqdq: {
2648 if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2649 unsigned Imm = C->getZExtValue();
2650
2651 bool MadeChange = false;
2652 Value *Arg0 = II->getArgOperand(0);
2653 Value *Arg1 = II->getArgOperand(1);
2654 unsigned VWidth = Arg0->getType()->getVectorNumElements();
2655 APInt DemandedElts(VWidth, 0);
2656
2657 APInt UndefElts1(VWidth, 0);
2658 DemandedElts = (Imm & 0x01) ? 2 : 1;
2659 if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts,
2660 UndefElts1)) {
2661 II->setArgOperand(0, V);
2662 MadeChange = true;
2663 }
2664
2665 APInt UndefElts2(VWidth, 0);
2666 DemandedElts = (Imm & 0x10) ? 2 : 1;
2667 if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts,
2668 UndefElts2)) {
2669 II->setArgOperand(1, V);
2670 MadeChange = true;
2671 }
2672
2673 // If both input elements are undef, the result is undef.
2674 if (UndefElts1[(Imm & 0x01) ? 1 : 0] ||
2675 UndefElts2[(Imm & 0x10) ? 1 : 0])
2676 return replaceInstUsesWith(*II,
2677 ConstantAggregateZero::get(II->getType()));
2678
2679 if (MadeChange)
2680 return II;
2681 }
2682 break;
2683 }
2684
Sanjay Patelc86867c2015-04-16 17:52:13 +00002685 case Intrinsic::x86_sse41_insertps:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002686 if (Value *V = simplifyX86insertps(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002687 return replaceInstUsesWith(*II, V);
Sanjay Patelc86867c2015-04-16 17:52:13 +00002688 break;
Simon Pilgrim54fcd622015-07-25 20:41:00 +00002689
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002690 case Intrinsic::x86_sse4a_extrq: {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002691 Value *Op0 = II->getArgOperand(0);
2692 Value *Op1 = II->getArgOperand(1);
2693 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2694 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002695 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2696 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2697 VWidth1 == 16 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002698
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002699 // See if we're dealing with constant values.
2700 Constant *C1 = dyn_cast<Constant>(Op1);
2701 ConstantInt *CILength =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002702 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002703 : nullptr;
2704 ConstantInt *CIIndex =
Andrea Di Biagio8df5b9c2016-09-07 12:03:03 +00002705 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002706 : nullptr;
2707
2708 // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002709 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002710 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002711
2712 // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2713 // operands and the lowest 16-bits of the second.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002714 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002715 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2716 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002717 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002718 }
2719 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2720 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002721 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002722 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002723 if (MadeChange)
2724 return II;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002725 break;
2726 }
2727
2728 case Intrinsic::x86_sse4a_extrqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002729 // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2730 // bits of the lower 64-bits. The upper 64-bits are undefined.
2731 Value *Op0 = II->getArgOperand(0);
2732 unsigned VWidth = Op0->getType()->getVectorNumElements();
2733 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2734 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002735
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002736 // See if we're dealing with constant values.
2737 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2738 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2739
2740 // Attempt to simplify to a constant or shuffle vector.
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002741 if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002742 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002743
2744 // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2745 // operand.
2746 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002747 II->setArgOperand(0, V);
2748 return II;
2749 }
2750 break;
2751 }
2752
2753 case Intrinsic::x86_sse4a_insertq: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002754 Value *Op0 = II->getArgOperand(0);
2755 Value *Op1 = II->getArgOperand(1);
2756 unsigned VWidth = Op0->getType()->getVectorNumElements();
2757 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2758 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2759 Op1->getType()->getVectorNumElements() == 2 &&
2760 "Unexpected operand size");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002761
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002762 // See if we're dealing with constant values.
2763 Constant *C1 = dyn_cast<Constant>(Op1);
2764 ConstantInt *CI11 =
Andrea Di Biagiof3fd3162016-09-07 12:47:53 +00002765 C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002766 : nullptr;
2767
2768 // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2769 if (CI11) {
Benjamin Kramer46e38f32016-06-08 10:01:20 +00002770 const APInt &V11 = CI11->getValue();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002771 APInt Len = V11.zextOrTrunc(6);
2772 APInt Idx = V11.lshr(8).zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002773 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002774 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002775 }
2776
2777 // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2778 // operand.
2779 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002780 II->setArgOperand(0, V);
2781 return II;
2782 }
2783 break;
2784 }
2785
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002786 case Intrinsic::x86_sse4a_insertqi: {
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002787 // INSERTQI: Extract lowest Length bits from lower half of second source and
2788 // insert over first source starting at Index bit. The upper 64-bits are
2789 // undefined.
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002790 Value *Op0 = II->getArgOperand(0);
2791 Value *Op1 = II->getArgOperand(1);
2792 unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2793 unsigned VWidth1 = Op1->getType()->getVectorNumElements();
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002794 assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2795 Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2796 VWidth1 == 2 && "Unexpected operand sizes");
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002797
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002798 // See if we're dealing with constant values.
2799 ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2800 ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2801
2802 // Attempt to simplify to a constant or shuffle vector.
2803 if (CILength && CIIndex) {
2804 APInt Len = CILength->getValue().zextOrTrunc(6);
2805 APInt Idx = CIIndex->getValue().zextOrTrunc(6);
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002806 if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002807 return replaceInstUsesWith(*II, V);
Simon Pilgrim216b1bf2015-10-17 11:40:05 +00002808 }
2809
2810 // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2811 // operands.
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002812 bool MadeChange = false;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002813 if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2814 II->setArgOperand(0, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002815 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002816 }
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002817 if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2818 II->setArgOperand(1, V);
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002819 MadeChange = true;
Simon Pilgrim61116dd2015-09-17 20:32:45 +00002820 }
Simon Pilgrim1c9a9f22016-04-24 17:57:27 +00002821 if (MadeChange)
2822 return II;
Filipe Cabecinhas1a805952014-04-24 00:38:14 +00002823 break;
2824 }
2825
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002826 case Intrinsic::x86_sse41_pblendvb:
2827 case Intrinsic::x86_sse41_blendvps:
2828 case Intrinsic::x86_sse41_blendvpd:
2829 case Intrinsic::x86_avx_blendv_ps_256:
2830 case Intrinsic::x86_avx_blendv_pd_256:
2831 case Intrinsic::x86_avx2_pblendvb: {
2832 // Convert blendv* to vector selects if the mask is constant.
2833 // This optimization is convoluted because the intrinsic is defined as
2834 // getting a vector of floats or doubles for the ps and pd versions.
2835 // FIXME: That should be changed.
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002836
2837 Value *Op0 = II->getArgOperand(0);
2838 Value *Op1 = II->getArgOperand(1);
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002839 Value *Mask = II->getArgOperand(2);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002840
2841 // fold (blend A, A, Mask) -> A
2842 if (Op0 == Op1)
Sanjay Patel4b198802016-02-01 22:23:39 +00002843 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002844
2845 // Zero Mask - select 1st argument.
Simon Pilgrim93f59f52015-08-12 08:23:36 +00002846 if (isa<ConstantAggregateZero>(Mask))
Sanjay Patel4b198802016-02-01 22:23:39 +00002847 return replaceInstUsesWith(CI, Op0);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002848
2849 // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
Sanjay Patel368ac5d2016-02-21 17:29:33 +00002850 if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2851 Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002852 return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002853 }
Simon Pilgrim8c049d52015-08-12 08:08:56 +00002854 break;
Filipe Cabecinhas82ac07c2014-05-27 03:42:20 +00002855 }
2856
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002857 case Intrinsic::x86_ssse3_pshuf_b_128:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002858 case Intrinsic::x86_avx2_pshuf_b:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002859 case Intrinsic::x86_avx512_pshuf_b_512:
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00002860 if (Value *V = simplifyX86pshufb(*II, *Builder))
2861 return replaceInstUsesWith(*II, V);
2862 break;
Andrea Di Biagio0594e2a2015-09-30 16:44:39 +00002863
Rafael Espindolabad3f772014-04-21 22:06:04 +00002864 case Intrinsic::x86_avx_vpermilvar_ps:
2865 case Intrinsic::x86_avx_vpermilvar_ps_256:
Craig Topper58917f32016-12-11 01:59:36 +00002866 case Intrinsic::x86_avx512_vpermilvar_ps_512:
Rafael Espindolabad3f772014-04-21 22:06:04 +00002867 case Intrinsic::x86_avx_vpermilvar_pd:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002868 case Intrinsic::x86_avx_vpermilvar_pd_256:
Simon Pilgrima22c3a12017-01-18 13:44:04 +00002869 case Intrinsic::x86_avx512_vpermilvar_pd_512:
Simon Pilgrim2f6097d2016-04-24 17:23:46 +00002870 if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2871 return replaceInstUsesWith(*II, V);
2872 break;
Rafael Espindolabad3f772014-04-21 22:06:04 +00002873
Simon Pilgrim8cddf8b2016-05-01 16:41:22 +00002874 case Intrinsic::x86_avx2_permd:
2875 case Intrinsic::x86_avx2_permps:
2876 if (Value *V = simplifyX86vpermv(*II, *Builder))
2877 return replaceInstUsesWith(*II, V);
2878 break;
2879
Craig Toppere3280452016-12-25 23:58:57 +00002880 case Intrinsic::x86_avx512_mask_permvar_df_256:
2881 case Intrinsic::x86_avx512_mask_permvar_df_512:
2882 case Intrinsic::x86_avx512_mask_permvar_di_256:
2883 case Intrinsic::x86_avx512_mask_permvar_di_512:
2884 case Intrinsic::x86_avx512_mask_permvar_hi_128:
2885 case Intrinsic::x86_avx512_mask_permvar_hi_256:
2886 case Intrinsic::x86_avx512_mask_permvar_hi_512:
2887 case Intrinsic::x86_avx512_mask_permvar_qi_128:
2888 case Intrinsic::x86_avx512_mask_permvar_qi_256:
2889 case Intrinsic::x86_avx512_mask_permvar_qi_512:
2890 case Intrinsic::x86_avx512_mask_permvar_sf_256:
2891 case Intrinsic::x86_avx512_mask_permvar_sf_512:
2892 case Intrinsic::x86_avx512_mask_permvar_si_256:
2893 case Intrinsic::x86_avx512_mask_permvar_si_512:
2894 if (Value *V = simplifyX86vpermv(*II, *Builder)) {
2895 // We simplified the permuting, now create a select for the masking.
2896 V = emitX86MaskSelect(II->getArgOperand(3), V, II->getArgOperand(2),
2897 *Builder);
2898 return replaceInstUsesWith(*II, V);
2899 }
2900 break;
2901
Sanjay Patelccf5f242015-03-20 21:47:56 +00002902 case Intrinsic::x86_avx_vperm2f128_pd_256:
2903 case Intrinsic::x86_avx_vperm2f128_ps_256:
2904 case Intrinsic::x86_avx_vperm2f128_si_256:
Sanjay Patele304bea2015-03-24 22:39:29 +00002905 case Intrinsic::x86_avx2_vperm2i128:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002906 if (Value *V = simplifyX86vperm2(*II, *Builder))
Sanjay Patel4b198802016-02-01 22:23:39 +00002907 return replaceInstUsesWith(*II, V);
Sanjay Patelccf5f242015-03-20 21:47:56 +00002908 break;
2909
Sanjay Patel98a71502016-02-29 23:16:48 +00002910 case Intrinsic::x86_avx_maskload_ps:
Sanjay Patel6f2c01f2016-02-29 23:59:00 +00002911 case Intrinsic::x86_avx_maskload_pd:
2912 case Intrinsic::x86_avx_maskload_ps_256:
2913 case Intrinsic::x86_avx_maskload_pd_256:
2914 case Intrinsic::x86_avx2_maskload_d:
2915 case Intrinsic::x86_avx2_maskload_q:
2916 case Intrinsic::x86_avx2_maskload_d_256:
2917 case Intrinsic::x86_avx2_maskload_q_256:
Sanjay Patel98a71502016-02-29 23:16:48 +00002918 if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2919 return I;
2920 break;
2921
Sanjay Patelc4acbae2016-03-12 15:16:59 +00002922 case Intrinsic::x86_sse2_maskmov_dqu:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002923 case Intrinsic::x86_avx_maskstore_ps:
2924 case Intrinsic::x86_avx_maskstore_pd:
2925 case Intrinsic::x86_avx_maskstore_ps_256:
2926 case Intrinsic::x86_avx_maskstore_pd_256:
Sanjay Patelfc7e7eb2016-02-26 21:51:44 +00002927 case Intrinsic::x86_avx2_maskstore_d:
2928 case Intrinsic::x86_avx2_maskstore_q:
2929 case Intrinsic::x86_avx2_maskstore_d_256:
2930 case Intrinsic::x86_avx2_maskstore_q_256:
Sanjay Patel1ace9932016-02-26 21:04:14 +00002931 if (simplifyX86MaskedStore(*II, *this))
2932 return nullptr;
2933 break;
2934
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002935 case Intrinsic::x86_xop_vpcomb:
2936 case Intrinsic::x86_xop_vpcomd:
2937 case Intrinsic::x86_xop_vpcomq:
2938 case Intrinsic::x86_xop_vpcomw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002939 if (Value *V = simplifyX86vpcom(*II, *Builder, true))
Sanjay Patel4b198802016-02-01 22:23:39 +00002940 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002941 break;
2942
2943 case Intrinsic::x86_xop_vpcomub:
2944 case Intrinsic::x86_xop_vpcomud:
2945 case Intrinsic::x86_xop_vpcomuq:
2946 case Intrinsic::x86_xop_vpcomuw:
Sanjay Patel6038d3e2016-01-29 23:27:03 +00002947 if (Value *V = simplifyX86vpcom(*II, *Builder, false))
Sanjay Patel4b198802016-02-01 22:23:39 +00002948 return replaceInstUsesWith(*II, V);
Simon Pilgrim1d1c56e22015-10-11 14:38:34 +00002949 break;
2950
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002951 case Intrinsic::ppc_altivec_vperm:
2952 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Bill Schmidta1184632014-06-05 19:46:04 +00002953 // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2954 // a vectorshuffle for little endian, we must undo the transformation
2955 // performed on vec_perm in altivec.h. That is, we must complement
2956 // the permutation mask with respect to 31 and reverse the order of
2957 // V1 and V2.
Chris Lattner0256be92012-01-27 03:08:05 +00002958 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2959 assert(Mask->getType()->getVectorNumElements() == 16 &&
2960 "Bad type for intrinsic!");
Jim Grosbach7815f562012-02-03 00:07:04 +00002961
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002962 // Check that all of the elements are integer constants or undefs.
2963 bool AllEltsOk = true;
2964 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002965 Constant *Elt = Mask->getAggregateElement(i);
Craig Topperf40110f2014-04-25 05:29:35 +00002966 if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002967 AllEltsOk = false;
2968 break;
2969 }
2970 }
Jim Grosbach7815f562012-02-03 00:07:04 +00002971
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002972 if (AllEltsOk) {
2973 // Cast the input vectors to byte vectors.
Gabor Greif3e44ea12010-07-22 10:37:47 +00002974 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2975 Mask->getType());
2976 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2977 Mask->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002978 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach7815f562012-02-03 00:07:04 +00002979
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002980 // Only extract each element once.
2981 Value *ExtractedElts[32];
2982 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach7815f562012-02-03 00:07:04 +00002983
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002984 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00002985 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002986 continue;
Jim Grosbach7815f562012-02-03 00:07:04 +00002987 unsigned Idx =
Chris Lattner0256be92012-01-27 03:08:05 +00002988 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002989 Idx &= 31; // Match the hardware behavior.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002990 if (DL.isLittleEndian())
Bill Schmidta1184632014-06-05 19:46:04 +00002991 Idx = 31 - Idx;
Jim Grosbach7815f562012-02-03 00:07:04 +00002992
Craig Topperf40110f2014-04-25 05:29:35 +00002993 if (!ExtractedElts[Idx]) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00002994 Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2995 Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
Jim Grosbach7815f562012-02-03 00:07:04 +00002996 ExtractedElts[Idx] =
Bill Schmidta1184632014-06-05 19:46:04 +00002997 Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
Benjamin Kramer547b6c52011-09-27 20:39:19 +00002998 Builder->getInt32(Idx&15));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00002999 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003000
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003001 // Insert this value into the result vector.
3002 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003003 Builder->getInt32(i));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003004 }
3005 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3006 }
3007 }
3008 break;
3009
Bob Wilsona4e231c2010-10-22 21:41:48 +00003010 case Intrinsic::arm_neon_vld1:
3011 case Intrinsic::arm_neon_vld2:
3012 case Intrinsic::arm_neon_vld3:
3013 case Intrinsic::arm_neon_vld4:
3014 case Intrinsic::arm_neon_vld2lane:
3015 case Intrinsic::arm_neon_vld3lane:
3016 case Intrinsic::arm_neon_vld4lane:
3017 case Intrinsic::arm_neon_vst1:
3018 case Intrinsic::arm_neon_vst2:
3019 case Intrinsic::arm_neon_vst3:
3020 case Intrinsic::arm_neon_vst4:
3021 case Intrinsic::arm_neon_vst2lane:
3022 case Intrinsic::arm_neon_vst3lane:
3023 case Intrinsic::arm_neon_vst4lane: {
Justin Bogner99798402016-08-05 01:06:44 +00003024 unsigned MemAlign =
Daniel Jasperaec2fa32016-12-19 08:22:17 +00003025 getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
Bob Wilsona4e231c2010-10-22 21:41:48 +00003026 unsigned AlignArg = II->getNumArgOperands() - 1;
3027 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3028 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3029 II->setArgOperand(AlignArg,
3030 ConstantInt::get(Type::getInt32Ty(II->getContext()),
3031 MemAlign, false));
3032 return II;
3033 }
3034 break;
3035 }
3036
Lang Hames3a90fab2012-05-01 00:20:38 +00003037 case Intrinsic::arm_neon_vmulls:
Tim Northover00ed9962014-03-29 10:18:08 +00003038 case Intrinsic::arm_neon_vmullu:
Tim Northover3b0846e2014-05-24 12:50:23 +00003039 case Intrinsic::aarch64_neon_smull:
3040 case Intrinsic::aarch64_neon_umull: {
Lang Hames3a90fab2012-05-01 00:20:38 +00003041 Value *Arg0 = II->getArgOperand(0);
3042 Value *Arg1 = II->getArgOperand(1);
3043
3044 // Handle mul by zero first:
3045 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003046 return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
Lang Hames3a90fab2012-05-01 00:20:38 +00003047 }
3048
3049 // Check for constant LHS & RHS - in this case we just simplify.
Tim Northover00ed9962014-03-29 10:18:08 +00003050 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
Tim Northover3b0846e2014-05-24 12:50:23 +00003051 II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
Lang Hames3a90fab2012-05-01 00:20:38 +00003052 VectorType *NewVT = cast<VectorType>(II->getType());
Benjamin Kramer92040952014-02-13 18:23:24 +00003053 if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3054 if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3055 CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3056 CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3057
Sanjay Patel4b198802016-02-01 22:23:39 +00003058 return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
Lang Hames3a90fab2012-05-01 00:20:38 +00003059 }
3060
Alp Tokercb402912014-01-24 17:20:08 +00003061 // Couldn't simplify - canonicalize constant to the RHS.
Lang Hames3a90fab2012-05-01 00:20:38 +00003062 std::swap(Arg0, Arg1);
3063 }
3064
3065 // Handle mul by one:
Benjamin Kramer92040952014-02-13 18:23:24 +00003066 if (Constant *CV1 = dyn_cast<Constant>(Arg1))
Lang Hames3a90fab2012-05-01 00:20:38 +00003067 if (ConstantInt *Splat =
Benjamin Kramer92040952014-02-13 18:23:24 +00003068 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3069 if (Splat->isOne())
3070 return CastInst::CreateIntegerCast(Arg0, II->getType(),
3071 /*isSigned=*/!Zext);
Lang Hames3a90fab2012-05-01 00:20:38 +00003072
3073 break;
3074 }
3075
Matt Arsenaultbef34e22016-01-22 21:30:34 +00003076 case Intrinsic::amdgcn_rcp: {
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003077 if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
3078 const APFloat &ArgVal = C->getValueAPF();
3079 APFloat Val(ArgVal.getSemantics(), 1.0);
3080 APFloat::opStatus Status = Val.divide(ArgVal,
3081 APFloat::rmNearestTiesToEven);
3082 // Only do this if it was exact and therefore not dependent on the
3083 // rounding mode.
3084 if (Status == APFloat::opOK)
Sanjay Patel4b198802016-02-01 22:23:39 +00003085 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
Matt Arsenaulta0050b02014-06-19 01:19:19 +00003086 }
3087
3088 break;
3089 }
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003090 case Intrinsic::amdgcn_frexp_mant:
3091 case Intrinsic::amdgcn_frexp_exp: {
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003092 Value *Src = II->getArgOperand(0);
3093 if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3094 int Exp;
3095 APFloat Significand = frexp(C->getValueAPF(), Exp,
3096 APFloat::rmNearestTiesToEven);
3097
Matt Arsenault2fe4fbc2016-03-30 22:28:52 +00003098 if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3099 return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3100 Significand));
3101 }
3102
3103 // Match instruction special case behavior.
3104 if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3105 Exp = 0;
3106
3107 return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3108 }
3109
3110 if (isa<UndefValue>(Src))
3111 return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
Matt Arsenault5cd4f8f2016-03-30 22:28:26 +00003112
3113 break;
3114 }
Matt Arsenault46a03822016-09-03 07:06:58 +00003115 case Intrinsic::amdgcn_class: {
3116 enum {
3117 S_NAN = 1 << 0, // Signaling NaN
3118 Q_NAN = 1 << 1, // Quiet NaN
3119 N_INFINITY = 1 << 2, // Negative infinity
3120 N_NORMAL = 1 << 3, // Negative normal
3121 N_SUBNORMAL = 1 << 4, // Negative subnormal
3122 N_ZERO = 1 << 5, // Negative zero
3123 P_ZERO = 1 << 6, // Positive zero
3124 P_SUBNORMAL = 1 << 7, // Positive subnormal
3125 P_NORMAL = 1 << 8, // Positive normal
3126 P_INFINITY = 1 << 9 // Positive infinity
3127 };
3128
3129 const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3130 N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3131
3132 Value *Src0 = II->getArgOperand(0);
3133 Value *Src1 = II->getArgOperand(1);
3134 const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3135 if (!CMask) {
3136 if (isa<UndefValue>(Src0))
3137 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3138
3139 if (isa<UndefValue>(Src1))
3140 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3141 break;
3142 }
3143
3144 uint32_t Mask = CMask->getZExtValue();
3145
3146 // If all tests are made, it doesn't matter what the value is.
3147 if ((Mask & FullMask) == FullMask)
3148 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3149
3150 if ((Mask & FullMask) == 0)
3151 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3152
3153 if (Mask == (S_NAN | Q_NAN)) {
3154 // Equivalent of isnan. Replace with standard fcmp.
3155 Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
3156 FCmp->takeName(II);
3157 return replaceInstUsesWith(*II, FCmp);
3158 }
3159
3160 const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3161 if (!CVal) {
3162 if (isa<UndefValue>(Src0))
3163 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3164
3165 // Clamp mask to used bits
3166 if ((Mask & FullMask) != Mask) {
3167 CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
3168 { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3169 );
3170
3171 NewCall->takeName(II);
3172 return replaceInstUsesWith(*II, NewCall);
3173 }
3174
3175 break;
3176 }
3177
3178 const APFloat &Val = CVal->getValueAPF();
3179
3180 bool Result =
3181 ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3182 ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3183 ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3184 ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3185 ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3186 ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3187 ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3188 ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3189 ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3190 ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3191
3192 return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3193 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003194 case Intrinsic::stackrestore: {
3195 // If the save is right next to the restore, remove the restore. This can
3196 // happen when variable allocas are DCE'd.
Gabor Greif589a0b92010-06-24 12:58:35 +00003197 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003198 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003199 if (&*++SS->getIterator() == II)
Sanjay Patel4b198802016-02-01 22:23:39 +00003200 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003201 }
3202 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003203
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003204 // Scan down this block to see if there is another stack restore in the
3205 // same block without an intervening call/alloca.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003206 BasicBlock::iterator BI(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003207 TerminatorInst *TI = II->getParent()->getTerminator();
3208 bool CannotRemove = false;
3209 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes55fff832012-06-21 15:45:28 +00003210 if (isa<AllocaInst>(BI)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003211 CannotRemove = true;
3212 break;
3213 }
3214 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3215 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3216 // If there is a stackrestore below this one, remove this one.
3217 if (II->getIntrinsicID() == Intrinsic::stackrestore)
Sanjay Patel4b198802016-02-01 22:23:39 +00003218 return eraseInstFromFunction(CI);
Reid Kleckner892ae2e2016-02-27 00:53:54 +00003219
3220 // Bail if we cross over an intrinsic with side effects, such as
3221 // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3222 if (II->mayHaveSideEffects()) {
3223 CannotRemove = true;
3224 break;
3225 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003226 } else {
3227 // If we found a non-intrinsic call, we can't remove the stack
3228 // restore.
3229 CannotRemove = true;
3230 break;
3231 }
3232 }
3233 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003234
Bill Wendlingf891bf82011-07-31 06:30:59 +00003235 // If the stack restore is in a return, resume, or unwind block and if there
3236 // are no allocas or calls between the restore and the return, nuke the
3237 // restore.
Bill Wendlingd5d95b02012-02-06 21:16:41 +00003238 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Sanjay Patel4b198802016-02-01 22:23:39 +00003239 return eraseInstFromFunction(CI);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003240 break;
3241 }
Vitaly Bukaf0500b62016-07-28 22:50:48 +00003242 case Intrinsic::lifetime_start:
Vitaly Buka0ab23cf2016-07-28 22:59:03 +00003243 // Asan needs to poison memory to detect invalid access which is possible
3244 // even for empty lifetime range.
3245 if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
3246 break;
3247
Arnaud A. de Grandmaison333ef382016-05-10 09:24:49 +00003248 if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3249 Intrinsic::lifetime_end, *this))
3250 return nullptr;
Arnaud A. de Grandmaison849f3bf2015-10-01 14:54:31 +00003251 break;
Hal Finkelf5867a72014-07-25 21:45:17 +00003252 case Intrinsic::assume: {
David Majnemerfcc58112016-04-08 16:37:12 +00003253 Value *IIOperand = II->getArgOperand(0);
3254 // Remove an assume if it is immediately followed by an identical assume.
3255 if (match(II->getNextNode(),
3256 m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3257 return eraseInstFromFunction(CI);
3258
Hal Finkelf5867a72014-07-25 21:45:17 +00003259 // Canonicalize assume(a && b) -> assume(a); assume(b);
Hal Finkel74c2f352014-09-07 12:44:26 +00003260 // Note: New assumption intrinsics created here are registered by
3261 // the InstCombineIRInserter object.
David Majnemerfcc58112016-04-08 16:37:12 +00003262 Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
Hal Finkelf5867a72014-07-25 21:45:17 +00003263 if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
3264 Builder->CreateCall(AssumeIntrinsic, A, II->getName());
3265 Builder->CreateCall(AssumeIntrinsic, B, II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003266 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003267 }
3268 // assume(!(a || b)) -> assume(!a); assume(!b);
3269 if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
Hal Finkel74c2f352014-09-07 12:44:26 +00003270 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
3271 II->getName());
3272 Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
3273 II->getName());
Sanjay Patel4b198802016-02-01 22:23:39 +00003274 return eraseInstFromFunction(*II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003275 }
Hal Finkel04a15612014-10-04 21:27:06 +00003276
Philip Reames66c6de62014-11-11 23:33:19 +00003277 // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3278 // (if assume is valid at the load)
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003279 CmpInst::Predicate Pred;
3280 Instruction *LHS;
3281 if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3282 Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3283 LHS->getType()->isPointerTy() &&
3284 isValidAssumeForContext(II, LHS, &DT)) {
3285 MDNode *MD = MDNode::get(II->getContext(), None);
3286 LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3287 return eraseInstFromFunction(*II);
3288
Chandler Carruth24969102015-02-10 08:07:32 +00003289 // TODO: apply nonnull return attributes to calls and invokes
Philip Reames66c6de62014-11-11 23:33:19 +00003290 // TODO: apply range metadata for range check patterns?
3291 }
Sanjay Patelf0d1e7732017-01-03 22:25:31 +00003292
Hal Finkel04a15612014-10-04 21:27:06 +00003293 // If there is a dominating assume with the same condition as this one,
3294 // then this one is redundant, and should be removed.
Hal Finkel45646882014-10-05 00:53:02 +00003295 APInt KnownZero(1, 0), KnownOne(1, 0);
3296 computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
3297 if (KnownOne.isAllOnesValue())
Sanjay Patel4b198802016-02-01 22:23:39 +00003298 return eraseInstFromFunction(*II);
Hal Finkel04a15612014-10-04 21:27:06 +00003299
Hal Finkel8a9a7832017-01-11 13:24:24 +00003300 // Update the cache of affected values for this assumption (we might be
3301 // here because we just simplified the condition).
3302 AC.updateAffectedValues(II);
Hal Finkelf5867a72014-07-25 21:45:17 +00003303 break;
3304 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003305 case Intrinsic::experimental_gc_relocate: {
3306 // Translate facts known about a pointer before relocating into
3307 // facts about the relocate value, while being careful to
3308 // preserve relocation semantics.
Manuel Jacob83eefa62016-01-05 04:03:00 +00003309 Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
Philip Reames9db26ff2014-12-29 23:27:30 +00003310
3311 // Remove the relocation if unused, note that this check is required
3312 // to prevent the cases below from looping forever.
3313 if (II->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003314 return eraseInstFromFunction(*II);
Philip Reames9db26ff2014-12-29 23:27:30 +00003315
3316 // Undef is undef, even after relocation.
3317 // TODO: provide a hook for this in GCStrategy. This is clearly legal for
3318 // most practical collectors, but there was discussion in the review thread
3319 // about whether it was legal for all possible collectors.
Philip Reamesea4d8e82016-02-09 21:09:22 +00003320 if (isa<UndefValue>(DerivedPtr))
3321 // Use undef of gc_relocate's type to replace it.
3322 return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
Philip Reames9db26ff2014-12-29 23:27:30 +00003323
Philip Reamesea4d8e82016-02-09 21:09:22 +00003324 if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3325 // The relocation of null will be null for most any collector.
3326 // TODO: provide a hook for this in GCStrategy. There might be some
3327 // weird collector this property does not hold for.
3328 if (isa<ConstantPointerNull>(DerivedPtr))
3329 // Use null-pointer of gc_relocate's type to replace it.
3330 return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
Simon Pilgrimc0c56e72016-04-24 17:00:34 +00003331
Philip Reamesea4d8e82016-02-09 21:09:22 +00003332 // isKnownNonNull -> nonnull attribute
Justin Bogner99798402016-08-05 01:06:44 +00003333 if (isKnownNonNullAt(DerivedPtr, II, &DT))
Philip Reamesea4d8e82016-02-09 21:09:22 +00003334 II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003335 }
Philip Reames9db26ff2014-12-29 23:27:30 +00003336
3337 // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3338 // Canonicalize on the type from the uses to the defs
Ramkumar Ramachandra8fcb4982015-02-14 19:37:54 +00003339
Philip Reames9db26ff2014-12-29 23:27:30 +00003340 // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
Philip Reamesea4d8e82016-02-09 21:09:22 +00003341 break;
Philip Reames9db26ff2014-12-29 23:27:30 +00003342 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003343
3344 case Intrinsic::experimental_guard: {
Sanjoy Dase0e57952017-02-01 16:34:55 +00003345 // Is this guard followed by another guard?
3346 Instruction *NextInst = II->getNextNode();
3347 Value *NextCond = nullptr;
3348 if (match(NextInst,
3349 m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3350 Value *CurrCond = II->getArgOperand(0);
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003351
Sanjoy Dase0e57952017-02-01 16:34:55 +00003352 // Remove a guard that it is immediately preceeded by an identical guard.
3353 if (CurrCond == NextCond)
3354 return eraseInstFromFunction(*NextInst);
3355
3356 // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3357 II->setArgOperand(0, Builder->CreateAnd(CurrCond, NextCond));
3358 return eraseInstFromFunction(*NextInst);
3359 }
Artur Pilipenkoe812ca02017-01-25 14:12:12 +00003360 break;
3361 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003362 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003363 return visitCallSite(II);
3364}
3365
Davide Italianoaec46172017-01-31 18:09:05 +00003366// Fence instruction simplification
3367Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3368 // Remove identical consecutive fences.
3369 if (auto *NFI = dyn_cast<FenceInst>(FI.getNextNode()))
3370 if (FI.isIdenticalTo(NFI))
3371 return eraseInstFromFunction(FI);
3372 return nullptr;
3373}
3374
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003375// InvokeInst simplification
3376//
3377Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3378 return visitCallSite(&II);
3379}
3380
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003381/// If this cast does not affect the value passed through the varargs area, we
3382/// can eliminate the use of the cast.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003383static bool isSafeToEliminateVarargsCast(const CallSite CS,
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003384 const DataLayout &DL,
3385 const CastInst *const CI,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003386 const int ix) {
3387 if (!CI->isLosslessCast())
3388 return false;
3389
Philip Reames1a1bdb22014-12-02 18:50:36 +00003390 // If this is a GC intrinsic, avoid munging types. We need types for
3391 // statepoint reconstruction in SelectionDAG.
3392 // TODO: This is probably something which should be expanded to all
3393 // intrinsics since the entire point of intrinsics is that
3394 // they are understandable by the optimizer.
3395 if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
3396 return false;
3397
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003398 // The size of ByVal or InAlloca arguments is derived from the type, so we
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003399 // can't change to a type with a different size. If the size were
3400 // passed explicitly we could avoid this check.
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003401 if (!CS.isByValOrInAllocaArgument(ix))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003402 return true;
3403
Jim Grosbach7815f562012-02-03 00:07:04 +00003404 Type* SrcTy =
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003405 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattner229907c2011-07-18 04:54:35 +00003406 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003407 if (!SrcTy->isSized() || !DstTy->isSized())
3408 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003409 if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003410 return false;
3411 return true;
3412}
3413
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003414Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
Craig Topperf40110f2014-04-25 05:29:35 +00003415 if (!CI->getCalledFunction()) return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003416
Chandler Carruthba4c5172015-01-21 11:23:40 +00003417 auto InstCombineRAUW = [this](Instruction *From, Value *With) {
Sanjay Patel4b198802016-02-01 22:23:39 +00003418 replaceInstUsesWith(*From, With);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003419 };
Justin Bogner99798402016-08-05 01:06:44 +00003420 LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
Chandler Carruthba4c5172015-01-21 11:23:40 +00003421 if (Value *With = Simplifier.optimizeCall(CI)) {
Meador Ingee3f2b262012-11-30 04:05:06 +00003422 ++NumSimplified;
Sanjay Patel4b198802016-02-01 22:23:39 +00003423 return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
Meador Ingee3f2b262012-11-30 04:05:06 +00003424 }
Meador Ingedf796f82012-10-13 16:45:24 +00003425
Craig Topperf40110f2014-04-25 05:29:35 +00003426 return nullptr;
Eric Christophera7fb58f2010-03-06 10:50:38 +00003427}
3428
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003429static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003430 // Strip off at most one level of pointer casts, looking for an alloca. This
3431 // is good enough in practice and simpler than handling any number of casts.
3432 Value *Underlying = TrampMem->stripPointerCasts();
3433 if (Underlying != TrampMem &&
Chandler Carruthcdf47882014-03-09 03:16:01 +00003434 (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
Craig Topperf40110f2014-04-25 05:29:35 +00003435 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003436 if (!isa<AllocaInst>(Underlying))
Craig Topperf40110f2014-04-25 05:29:35 +00003437 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003438
Craig Topperf40110f2014-04-25 05:29:35 +00003439 IntrinsicInst *InitTrampoline = nullptr;
Chandler Carruthcdf47882014-03-09 03:16:01 +00003440 for (User *U : TrampMem->users()) {
3441 IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
Duncan Sandsa0984362011-09-06 13:37:06 +00003442 if (!II)
Craig Topperf40110f2014-04-25 05:29:35 +00003443 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003444 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
3445 if (InitTrampoline)
3446 // More than one init_trampoline writes to this value. Give up.
Craig Topperf40110f2014-04-25 05:29:35 +00003447 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003448 InitTrampoline = II;
3449 continue;
3450 }
3451 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
3452 // Allow any number of calls to adjust.trampoline.
3453 continue;
Craig Topperf40110f2014-04-25 05:29:35 +00003454 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003455 }
3456
3457 // No call to init.trampoline found.
3458 if (!InitTrampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003459 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003460
3461 // Check that the alloca is being used in the expected way.
3462 if (InitTrampoline->getOperand(0) != TrampMem)
Craig Topperf40110f2014-04-25 05:29:35 +00003463 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003464
3465 return InitTrampoline;
3466}
3467
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003468static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
Duncan Sandsa0984362011-09-06 13:37:06 +00003469 Value *TrampMem) {
3470 // Visit all the previous instructions in the basic block, and try to find a
3471 // init.trampoline which has a direct path to the adjust.trampoline.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00003472 for (BasicBlock::iterator I = AdjustTramp->getIterator(),
3473 E = AdjustTramp->getParent()->begin();
3474 I != E;) {
3475 Instruction *Inst = &*--I;
Duncan Sandsa0984362011-09-06 13:37:06 +00003476 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
3477 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
3478 II->getOperand(0) == TrampMem)
3479 return II;
3480 if (Inst->mayWriteToMemory())
Craig Topperf40110f2014-04-25 05:29:35 +00003481 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003482 }
Craig Topperf40110f2014-04-25 05:29:35 +00003483 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003484}
3485
3486// Given a call to llvm.adjust.trampoline, find and return the corresponding
3487// call to llvm.init.trampoline if the call to the trampoline can be optimized
3488// to a direct call to a function. Otherwise return NULL.
3489//
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003490static IntrinsicInst *findInitTrampoline(Value *Callee) {
Duncan Sandsa0984362011-09-06 13:37:06 +00003491 Callee = Callee->stripPointerCasts();
3492 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
3493 if (!AdjustTramp ||
3494 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
Craig Topperf40110f2014-04-25 05:29:35 +00003495 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003496
3497 Value *TrampMem = AdjustTramp->getOperand(0);
3498
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003499 if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003500 return IT;
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003501 if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
Duncan Sandsa0984362011-09-06 13:37:06 +00003502 return IT;
Craig Topperf40110f2014-04-25 05:29:35 +00003503 return nullptr;
Duncan Sandsa0984362011-09-06 13:37:06 +00003504}
3505
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003506/// Improvements for call and invoke instructions.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003507Instruction *InstCombiner::visitCallSite(CallSite CS) {
Justin Bogner99798402016-08-05 01:06:44 +00003508 if (isAllocLikeFn(CS.getInstruction(), &TLI))
Nuno Lopes95cc4f32012-07-09 18:38:20 +00003509 return visitAllocSite(*CS.getInstruction());
Nuno Lopesdc6085e2012-06-21 21:25:05 +00003510
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003511 bool Changed = false;
3512
Philip Reamesc25df112015-06-16 20:24:25 +00003513 // Mark any parameters that are known to be non-null with the nonnull
3514 // attribute. This is helpful for inlining calls to functions with null
3515 // checks on their arguments.
Akira Hatanaka237916b2015-12-02 06:58:49 +00003516 SmallVector<unsigned, 4> Indices;
Philip Reamesc25df112015-06-16 20:24:25 +00003517 unsigned ArgNo = 0;
Akira Hatanaka237916b2015-12-02 06:58:49 +00003518
Philip Reamesc25df112015-06-16 20:24:25 +00003519 for (Value *V : CS.args()) {
Sanjay Patelf9f5d3c2016-01-29 23:14:58 +00003520 if (V->getType()->isPointerTy() &&
3521 !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
Justin Bogner99798402016-08-05 01:06:44 +00003522 isKnownNonNullAt(V, CS.getInstruction(), &DT))
Akira Hatanaka237916b2015-12-02 06:58:49 +00003523 Indices.push_back(ArgNo + 1);
Philip Reamesc25df112015-06-16 20:24:25 +00003524 ArgNo++;
3525 }
Akira Hatanaka237916b2015-12-02 06:58:49 +00003526
Philip Reamesc25df112015-06-16 20:24:25 +00003527 assert(ArgNo == CS.arg_size() && "sanity check");
3528
Akira Hatanaka237916b2015-12-02 06:58:49 +00003529 if (!Indices.empty()) {
3530 AttributeSet AS = CS.getAttributes();
3531 LLVMContext &Ctx = CS.getInstruction()->getContext();
3532 AS = AS.addAttribute(Ctx, Indices,
3533 Attribute::get(Ctx, Attribute::NonNull));
3534 CS.setAttributes(AS);
3535 Changed = true;
3536 }
3537
Chris Lattner73989652010-12-20 08:25:06 +00003538 // If the callee is a pointer to a function, attempt to move any casts to the
3539 // arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003540 Value *Callee = CS.getCalledValue();
Chris Lattner73989652010-12-20 08:25:06 +00003541 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
Craig Topperf40110f2014-04-25 05:29:35 +00003542 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003543
Justin Lebar9d943972016-03-14 20:18:54 +00003544 if (Function *CalleeF = dyn_cast<Function>(Callee)) {
3545 // Remove the convergent attr on calls when the callee is not convergent.
Matt Arsenault802ebcb2016-06-20 19:04:44 +00003546 if (CS.isConvergent() && !CalleeF->isConvergent() &&
3547 !CalleeF->isIntrinsic()) {
Justin Lebar9d943972016-03-14 20:18:54 +00003548 DEBUG(dbgs() << "Removing convergent attr from instr "
3549 << CS.getInstruction() << "\n");
3550 CS.setNotConvergent();
3551 return CS.getInstruction();
3552 }
3553
Chris Lattner846a52e2010-02-01 18:11:34 +00003554 // If the call and callee calling conventions don't match, this call must
3555 // be unreachable, as the call is undefined.
3556 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
3557 // Only do this for calls to a function with a body. A prototype may
3558 // not actually end up matching the implementation's calling conv for a
3559 // variety of reasons (e.g. it may be written in assembly).
3560 !CalleeF->isDeclaration()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003561 Instruction *OldCall = CS.getInstruction();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003562 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach7815f562012-02-03 00:07:04 +00003563 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003564 OldCall);
Chad Rosiere28ae302012-12-13 00:18:46 +00003565 // If OldCall does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003566 // This allows ValueHandlers and custom metadata to adjust itself.
3567 if (!OldCall->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003568 replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner2cecedf2010-02-01 18:04:58 +00003569 if (isa<CallInst>(OldCall))
Sanjay Patel4b198802016-02-01 22:23:39 +00003570 return eraseInstFromFunction(*OldCall);
Jim Grosbach7815f562012-02-03 00:07:04 +00003571
Chris Lattner2cecedf2010-02-01 18:04:58 +00003572 // We cannot remove an invoke, because it would change the CFG, just
3573 // change the callee to a null pointer.
Gabor Greiffebf6ab2010-03-20 21:00:25 +00003574 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner2cecedf2010-02-01 18:04:58 +00003575 Constant::getNullValue(CalleeF->getType()));
Craig Topperf40110f2014-04-25 05:29:35 +00003576 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003577 }
Justin Lebar9d943972016-03-14 20:18:54 +00003578 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003579
3580 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greif589a0b92010-06-24 12:58:35 +00003581 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003582 // This allows ValueHandlers and custom metadata to adjust itself.
3583 if (!CS.getInstruction()->getType()->isVoidTy())
Sanjay Patel4b198802016-02-01 22:23:39 +00003584 replaceInstUsesWith(*CS.getInstruction(),
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003585 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003586
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003587 if (isa<InvokeInst>(CS.getInstruction())) {
3588 // Can't remove an invoke because we cannot change the CFG.
Craig Topperf40110f2014-04-25 05:29:35 +00003589 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003590 }
Nuno Lopes771e7bd2012-06-21 23:52:14 +00003591
3592 // This instruction is not reachable, just remove it. We insert a store to
3593 // undef so that we know that this code is not reachable, despite the fact
3594 // that we can't modify the CFG here.
3595 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
3596 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
3597 CS.getInstruction());
3598
Sanjay Patel4b198802016-02-01 22:23:39 +00003599 return eraseInstFromFunction(*CS.getInstruction());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003600 }
3601
Sanjay Patel6038d3e2016-01-29 23:27:03 +00003602 if (IntrinsicInst *II = findInitTrampoline(Callee))
Duncan Sandsa0984362011-09-06 13:37:06 +00003603 return transformCallThroughTrampoline(CS, II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003604
Chris Lattner229907c2011-07-18 04:54:35 +00003605 PointerType *PTy = cast<PointerType>(Callee->getType());
3606 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003607 if (FTy->isVarArg()) {
Eli Friedman7534b4682011-11-29 01:18:23 +00003608 int ix = FTy->getNumParams();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003609 // See if we can optimize any arguments passed through the varargs area of
3610 // the call.
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003611 for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003612 E = CS.arg_end(); I != E; ++I, ++ix) {
3613 CastInst *CI = dyn_cast<CastInst>(*I);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003614 if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003615 *I = CI->getOperand(0);
3616 Changed = true;
3617 }
3618 }
3619 }
3620
3621 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
3622 // Inline asm calls cannot throw - mark them 'nounwind'.
3623 CS.setDoesNotThrow();
3624 Changed = true;
3625 }
3626
Micah Villmowcdfe20b2012-10-08 16:38:25 +00003627 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christophera7fb58f2010-03-06 10:50:38 +00003628 // this. None of these calls are seen as possibly dead so go ahead and
3629 // delete the instruction now.
3630 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003631 Instruction *I = tryOptimizeCall(CI);
Eric Christopher1810d772010-03-06 10:59:25 +00003632 // If we changed something return the result, etc. Otherwise let
3633 // the fallthrough check.
Sanjay Patel4b198802016-02-01 22:23:39 +00003634 if (I) return eraseInstFromFunction(*I);
Eric Christophera7fb58f2010-03-06 10:50:38 +00003635 }
3636
Craig Topperf40110f2014-04-25 05:29:35 +00003637 return Changed ? CS.getInstruction() : nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003638}
3639
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003640/// If the callee is a constexpr cast of a function, attempt to move the cast to
3641/// the arguments of the call/invoke.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003642bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Sanjay Patele3c335c2016-08-11 15:21:21 +00003643 auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
Craig Topperf40110f2014-04-25 05:29:35 +00003644 if (!Callee)
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003645 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003646
3647 // The prototype of a thunk is a lie. Don't directly call such a function.
David Majnemer4c0a6e92015-01-21 22:32:04 +00003648 if (Callee->hasFnAttribute("thunk"))
3649 return false;
Sanjay Patel38ae83d2016-08-11 15:23:56 +00003650
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003651 Instruction *Caller = CS.getInstruction();
Bill Wendlinge94d8432012-12-07 23:16:57 +00003652 const AttributeSet &CallerPAL = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003653
3654 // Okay, this is a cast from a function to a different type. Unless doing so
3655 // would cause a type conversion of one of our arguments, change this call to
3656 // be a direct call with arguments casted to the appropriate types.
3657 //
Chris Lattner229907c2011-07-18 04:54:35 +00003658 FunctionType *FT = Callee->getFunctionType();
3659 Type *OldRetTy = Caller->getType();
3660 Type *NewRetTy = FT->getReturnType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003661
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003662 // Check to see if we are changing the return type...
3663 if (OldRetTy != NewRetTy) {
Nick Lewyckya6a17d72014-01-18 22:47:12 +00003664
3665 if (NewRetTy->isStructTy())
3666 return false; // TODO: Handle multiple return values.
3667
David Majnemer9b6b8222015-01-06 08:41:31 +00003668 if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003669 if (Callee->isDeclaration())
3670 return false; // Cannot transform this return value.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003671
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003672 if (!Caller->use_empty() &&
3673 // void -> non-void is handled specially
3674 !NewRetTy->isVoidTy())
Frederic Rissc1892e22014-10-23 04:08:42 +00003675 return false; // Cannot transform this return value.
Matt Arsenaulte6952f22013-09-17 21:10:14 +00003676 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003677
3678 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling658d24d2013-01-18 21:53:16 +00003679 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Pete Cooper2777d8872015-05-06 23:19:56 +00003680 if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003681 return false; // Attribute not compatible with transformed value.
3682 }
3683
3684 // If the callsite is an invoke instruction, and the return value is used by
3685 // a PHI node in a successor, we cannot change the return type of the call
3686 // because there is no place to put the cast instruction (without breaking
3687 // the critical edge). Bail out in this case.
3688 if (!Caller->use_empty())
3689 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
Chandler Carruthcdf47882014-03-09 03:16:01 +00003690 for (User *U : II->users())
3691 if (PHINode *PN = dyn_cast<PHINode>(U))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003692 if (PN->getParent() == II->getNormalDest() ||
3693 PN->getParent() == II->getUnwindDest())
3694 return false;
3695 }
3696
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003697 unsigned NumActualArgs = CS.arg_size();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003698 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3699
David Majnemer9b6b8222015-01-06 08:41:31 +00003700 // Prevent us turning:
3701 // declare void @takes_i32_inalloca(i32* inalloca)
3702 // call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
3703 //
3704 // into:
3705 // call void @takes_i32_inalloca(i32* null)
David Majnemerd61a6fd2015-03-11 18:03:05 +00003706 //
3707 // Similarly, avoid folding away bitcasts of byval calls.
3708 if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
3709 Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
David Majnemer9b6b8222015-01-06 08:41:31 +00003710 return false;
3711
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003712 CallSite::arg_iterator AI = CS.arg_begin();
3713 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003714 Type *ParamTy = FT->getParamType(i);
3715 Type *ActTy = (*AI)->getType();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003716
David Majnemer9b6b8222015-01-06 08:41:31 +00003717 if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003718 return false; // Cannot transform this parameter value.
3719
Bill Wendling49bc76c2013-01-23 06:14:59 +00003720 if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
Pete Cooper2777d8872015-05-06 23:19:56 +00003721 overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003722 return false; // Attribute not compatible with transformed value.
Jim Grosbach7815f562012-02-03 00:07:04 +00003723
Reid Kleckner26af2ca2014-01-28 02:38:36 +00003724 if (CS.isInAllocaArgument(i))
3725 return false; // Cannot transform to and from inalloca.
3726
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003727 // If the parameter is passed as a byval argument, then we have to have a
3728 // sized type and the sized type has to have the same size as the old type.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003729 if (ParamTy != ActTy &&
3730 CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
3731 Attribute::ByVal)) {
Chris Lattner229907c2011-07-18 04:54:35 +00003732 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003733 if (!ParamPTy || !ParamPTy->getElementType()->isSized())
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003734 return false;
Jim Grosbach7815f562012-02-03 00:07:04 +00003735
Matt Arsenaultfa252722013-09-27 22:18:51 +00003736 Type *CurElTy = ActTy->getPointerElementType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +00003737 if (DL.getTypeAllocSize(CurElTy) !=
3738 DL.getTypeAllocSize(ParamPTy->getElementType()))
Chris Lattner27ca8eb2010-12-20 08:36:38 +00003739 return false;
3740 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003741 }
3742
Chris Lattneradf38b32011-02-24 05:10:56 +00003743 if (Callee->isDeclaration()) {
3744 // Do not delete arguments unless we have a function body.
3745 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
3746 return false;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003747
Chris Lattneradf38b32011-02-24 05:10:56 +00003748 // If the callee is just a declaration, don't change the varargsness of the
3749 // call. We don't want to introduce a varargs call where one doesn't
3750 // already exist.
Chris Lattner229907c2011-07-18 04:54:35 +00003751 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattneradf38b32011-02-24 05:10:56 +00003752 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
3753 return false;
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003754
3755 // If both the callee and the cast type are varargs, we still have to make
3756 // sure the number of fixed parameters are the same or we have the same
3757 // ABI issues as if we introduce a varargs call.
Jim Grosbach1df8cdc2012-02-03 00:26:07 +00003758 if (FT->isVarArg() &&
3759 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
3760 FT->getNumParams() !=
Jim Grosbache84ae7b2012-02-03 00:00:55 +00003761 cast<FunctionType>(APTy->getElementType())->getNumParams())
3762 return false;
Chris Lattneradf38b32011-02-24 05:10:56 +00003763 }
Jim Grosbach7815f562012-02-03 00:07:04 +00003764
Jim Grosbach0ab54182012-02-03 00:00:50 +00003765 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
3766 !CallerPAL.isEmpty())
3767 // In this case we have more arguments than the new function type, but we
3768 // won't be dropping them. Check that these extra arguments have attributes
3769 // that are compatible with being a vararg call argument.
3770 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
Bill Wendling57625a42013-01-25 23:09:36 +00003771 unsigned Index = CallerPAL.getSlotIndex(i - 1);
3772 if (Index <= FT->getNumParams())
Jim Grosbach0ab54182012-02-03 00:00:50 +00003773 break;
Bill Wendling57625a42013-01-25 23:09:36 +00003774
Bill Wendlingd97b75d2012-12-19 08:57:40 +00003775 // Check if it has an attribute that's incompatible with varargs.
Bill Wendling57625a42013-01-25 23:09:36 +00003776 AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
3777 if (PAttrs.hasAttribute(Index, Attribute::StructRet))
Jim Grosbach0ab54182012-02-03 00:00:50 +00003778 return false;
3779 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003780
Jim Grosbach7815f562012-02-03 00:07:04 +00003781
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003782 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattneradf38b32011-02-24 05:10:56 +00003783 // inserting cast instructions as necessary.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003784 std::vector<Value*> Args;
3785 Args.reserve(NumActualArgs);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003786 SmallVector<AttributeSet, 8> attrVec;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003787 attrVec.reserve(NumCommonArgs);
3788
3789 // Get any return attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003790 AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003791
3792 // If the return value is not being used, the type may not be compatible
3793 // with the existing attributes. Wipe out any problematic attributes.
Pete Cooper2777d8872015-05-06 23:19:56 +00003794 RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003795
3796 // Add the new return attributes.
Bill Wendling70f39172012-10-09 00:01:21 +00003797 if (RAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003798 attrVec.push_back(AttributeSet::get(Caller->getContext(),
3799 AttributeSet::ReturnIndex, RAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003800
3801 AI = CS.arg_begin();
3802 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003803 Type *ParamTy = FT->getParamType(i);
Matt Arsenaultcacbb232013-07-30 20:45:05 +00003804
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003805 if ((*AI)->getType() == ParamTy) {
3806 Args.push_back(*AI);
3807 } else {
David Majnemer9b6b8222015-01-06 08:41:31 +00003808 Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003809 }
3810
3811 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003812 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003813 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003814 attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
3815 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003816 }
3817
3818 // If the function takes more arguments than the call was taking, add them
3819 // now.
3820 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3821 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3822
3823 // If we are removing arguments to the function, emit an obnoxious warning.
3824 if (FT->getNumParams() < NumActualArgs) {
Nick Lewycky90053a12012-12-26 22:00:35 +00003825 // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3826 if (FT->isVarArg()) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003827 // Add all of the arguments in their promoted form to the arg list.
3828 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattner229907c2011-07-18 04:54:35 +00003829 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003830 if (PTy != (*AI)->getType()) {
3831 // Must promote to pass through va_arg area!
3832 Instruction::CastOps opcode =
3833 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramer547b6c52011-09-27 20:39:19 +00003834 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003835 } else {
3836 Args.push_back(*AI);
3837 }
3838
3839 // Add any parameter attributes.
Bill Wendling49bc76c2013-01-23 06:14:59 +00003840 AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
Bill Wendling76d2cd22012-10-14 08:54:26 +00003841 if (PAttrs.hasAttributes())
Bill Wendling3575c8c2013-01-27 02:08:22 +00003842 attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
3843 PAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003844 }
3845 }
3846 }
3847
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003848 AttributeSet FnAttrs = CallerPAL.getFnAttributes();
Bill Wendling77543892013-01-18 21:11:39 +00003849 if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003850 attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003851
3852 if (NewRetTy->isVoidTy())
3853 Caller->setName(""); // Void type should not have a name.
3854
Bill Wendlinge94d8432012-12-07 23:16:57 +00003855 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
Bill Wendlingbd4ea162013-01-21 21:57:28 +00003856 attrVec);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003857
Sanjoy Das76293462015-11-25 00:42:19 +00003858 SmallVector<OperandBundleDef, 1> OpBundles;
Sanjoy Dasc521c7b2015-11-25 00:42:24 +00003859 CS.getOperandBundlesAsDefs(OpBundles);
Sanjoy Das76293462015-11-25 00:42:19 +00003860
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003861 Instruction *NC;
3862 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Sanjoy Das76293462015-11-25 00:42:19 +00003863 NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
3864 Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003865 NC->takeName(II);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003866 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
3867 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
3868 } else {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003869 CallInst *CI = cast<CallInst>(Caller);
Sanjoy Das76293462015-11-25 00:42:19 +00003870 NC = Builder->CreateCall(Callee, Args, OpBundles);
Eli Friedman96254a02011-05-18 01:28:27 +00003871 NC->takeName(CI);
David Majnemerd5648c72016-11-25 22:35:09 +00003872 cast<CallInst>(NC)->setTailCallKind(CI->getTailCallKind());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003873 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
3874 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
3875 }
3876
3877 // Insert a cast of the return type as necessary.
3878 Value *NV = NC;
3879 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3880 if (!NV->getType()->isVoidTy()) {
David Majnemer9b6b8222015-01-06 08:41:31 +00003881 NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
Eli Friedman35211c62011-05-27 00:19:40 +00003882 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003883
3884 // If this is an invoke instruction, we should insert it after the first
3885 // non-phi, instruction in the normal successor block.
3886 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling07efd6f2011-08-25 01:08:34 +00003887 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003888 InsertNewInstBefore(NC, *I);
3889 } else {
Chris Lattner73989652010-12-20 08:25:06 +00003890 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003891 InsertNewInstBefore(NC, *Caller);
3892 }
3893 Worklist.AddUsersToWorkList(*Caller);
3894 } else {
3895 NV = UndefValue::get(Caller->getType());
3896 }
3897 }
3898
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003899 if (!Caller->use_empty())
Sanjay Patel4b198802016-02-01 22:23:39 +00003900 replaceInstUsesWith(*Caller, NV);
Frederic Rissc1892e22014-10-23 04:08:42 +00003901 else if (Caller->hasValueHandle()) {
3902 if (OldRetTy == NV->getType())
3903 ValueHandleBase::ValueIsRAUWd(Caller, NV);
3904 else
3905 // We cannot call ValueIsRAUWd with a different type, and the
3906 // actual tracked value will disappear.
3907 ValueHandleBase::ValueIsDeleted(Caller);
3908 }
Eli Friedmanb9ed18f2011-05-18 00:32:01 +00003909
Sanjay Patel4b198802016-02-01 22:23:39 +00003910 eraseInstFromFunction(*Caller);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003911 return true;
3912}
3913
Sanjay Patelcd4377c2016-01-20 22:24:38 +00003914/// Turn a call to a function created by init_trampoline / adjust_trampoline
3915/// intrinsic pair into a direct call to the underlying function.
Duncan Sandsa0984362011-09-06 13:37:06 +00003916Instruction *
3917InstCombiner::transformCallThroughTrampoline(CallSite CS,
3918 IntrinsicInst *Tramp) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003919 Value *Callee = CS.getCalledValue();
Chris Lattner229907c2011-07-18 04:54:35 +00003920 PointerType *PTy = cast<PointerType>(Callee->getType());
3921 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Bill Wendlinge94d8432012-12-07 23:16:57 +00003922 const AttributeSet &Attrs = CS.getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003923
3924 // If the call already has the 'nest' attribute somewhere then give up -
3925 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling6e95ae82012-12-31 00:49:59 +00003926 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Craig Topperf40110f2014-04-25 05:29:35 +00003927 return nullptr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003928
Duncan Sandsa0984362011-09-06 13:37:06 +00003929 assert(Tramp &&
3930 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003931
Gabor Greif3e44ea12010-07-22 10:37:47 +00003932 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Manuel Jacob5f6eaac2016-01-16 20:30:46 +00003933 FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003934
Bill Wendlinge94d8432012-12-07 23:16:57 +00003935 const AttributeSet &NestAttrs = NestF->getAttributes();
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003936 if (!NestAttrs.isEmpty()) {
3937 unsigned NestIdx = 1;
Craig Topperf40110f2014-04-25 05:29:35 +00003938 Type *NestTy = nullptr;
Bill Wendling49bc76c2013-01-23 06:14:59 +00003939 AttributeSet NestAttr;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003940
3941 // Look for a parameter marked with the 'nest' attribute.
3942 for (FunctionType::param_iterator I = NestFTy->param_begin(),
3943 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling49bc76c2013-01-23 06:14:59 +00003944 if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003945 // Record the parameter type and any other attributes.
3946 NestTy = *I;
3947 NestAttr = NestAttrs.getParamAttributes(NestIdx);
3948 break;
3949 }
3950
3951 if (NestTy) {
3952 Instruction *Caller = CS.getInstruction();
3953 std::vector<Value*> NewArgs;
Matt Arsenault5d2e85f2013-06-28 00:25:40 +00003954 NewArgs.reserve(CS.arg_size() + 1);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003955
Bill Wendling3575c8c2013-01-27 02:08:22 +00003956 SmallVector<AttributeSet, 8> NewAttrs;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003957 NewAttrs.reserve(Attrs.getNumSlots() + 1);
3958
3959 // Insert the nest argument into the call argument list, which may
3960 // mean appending it. Likewise for attributes.
3961
3962 // Add any result attributes.
Bill Wendling658d24d2013-01-18 21:53:16 +00003963 if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00003964 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3965 Attrs.getRetAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003966
3967 {
3968 unsigned Idx = 1;
3969 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3970 do {
3971 if (Idx == NestIdx) {
3972 // Add the chain argument and attributes.
Gabor Greif589a0b92010-06-24 12:58:35 +00003973 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003974 if (NestVal->getType() != NestTy)
Eli Friedman41e509a2011-05-18 23:58:37 +00003975 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003976 NewArgs.push_back(NestVal);
Bill Wendling3575c8c2013-01-27 02:08:22 +00003977 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3978 NestAttr));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003979 }
3980
3981 if (I == E)
3982 break;
3983
3984 // Add the original argument and attributes.
3985 NewArgs.push_back(*I);
Bill Wendling49bc76c2013-01-23 06:14:59 +00003986 AttributeSet Attr = Attrs.getParamAttributes(Idx);
3987 if (Attr.hasAttributes(Idx)) {
Bill Wendling3575c8c2013-01-27 02:08:22 +00003988 AttrBuilder B(Attr, Idx);
3989 NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3990 Idx + (Idx >= NestIdx), B));
Bill Wendling49bc76c2013-01-23 06:14:59 +00003991 }
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003992
Richard Trieu7a083812016-02-18 22:09:30 +00003993 ++Idx;
3994 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00003995 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00003996 }
3997
3998 // Add any function attributes.
Bill Wendling77543892013-01-18 21:11:39 +00003999 if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
Bill Wendling3575c8c2013-01-27 02:08:22 +00004000 NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
4001 Attrs.getFnAttributes()));
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004002
4003 // The trampoline may have been bitcast to a bogus type (FTy).
4004 // Handle this by synthesizing a new function type, equal to FTy
4005 // with the chain parameter inserted.
4006
Jay Foadb804a2b2011-07-12 14:06:48 +00004007 std::vector<Type*> NewTypes;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004008 NewTypes.reserve(FTy->getNumParams()+1);
4009
4010 // Insert the chain's type into the list of parameter types, which may
4011 // mean appending it.
4012 {
4013 unsigned Idx = 1;
4014 FunctionType::param_iterator I = FTy->param_begin(),
4015 E = FTy->param_end();
4016
4017 do {
4018 if (Idx == NestIdx)
4019 // Add the chain's type.
4020 NewTypes.push_back(NestTy);
4021
4022 if (I == E)
4023 break;
4024
4025 // Add the original type.
4026 NewTypes.push_back(*I);
4027
Richard Trieu7a083812016-02-18 22:09:30 +00004028 ++Idx;
4029 ++I;
Eugene Zelenkocdc71612016-08-11 17:20:18 +00004030 } while (true);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004031 }
4032
4033 // Replace the trampoline call with a direct call. Let the generic
4034 // code sort out any function type mismatches.
Jim Grosbach7815f562012-02-03 00:07:04 +00004035 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004036 FTy->isVarArg());
4037 Constant *NewCallee =
4038 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach7815f562012-02-03 00:07:04 +00004039 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004040 PointerType::getUnqual(NewFTy));
Jim Grosbachbdbd7342013-04-05 21:20:12 +00004041 const AttributeSet &NewPAL =
4042 AttributeSet::get(FTy->getContext(), NewAttrs);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004043
David Majnemer231a68c2016-04-29 08:07:20 +00004044 SmallVector<OperandBundleDef, 1> OpBundles;
4045 CS.getOperandBundlesAsDefs(OpBundles);
4046
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004047 Instruction *NewCaller;
4048 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4049 NewCaller = InvokeInst::Create(NewCallee,
4050 II->getNormalDest(), II->getUnwindDest(),
David Majnemer231a68c2016-04-29 08:07:20 +00004051 NewArgs, OpBundles);
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004052 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4053 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4054 } else {
David Majnemer231a68c2016-04-29 08:07:20 +00004055 NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
David Majnemerd5648c72016-11-25 22:35:09 +00004056 cast<CallInst>(NewCaller)->setTailCallKind(
4057 cast<CallInst>(Caller)->getTailCallKind());
4058 cast<CallInst>(NewCaller)->setCallingConv(
4059 cast<CallInst>(Caller)->getCallingConv());
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004060 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4061 }
Eli Friedman49346012011-05-18 19:57:14 +00004062
4063 return NewCaller;
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004064 }
4065 }
4066
4067 // Replace the trampoline call with a direct call. Since there is no 'nest'
4068 // parameter, there is no need to adjust the argument list. Let the generic
4069 // code sort out any function type mismatches.
4070 Constant *NewCallee =
Jim Grosbach7815f562012-02-03 00:07:04 +00004071 NestF->getType() == PTy ? NestF :
Chris Lattner7a9e47a2010-01-05 07:32:13 +00004072 ConstantExpr::getBitCast(NestF, PTy);
4073 CS.setCalledFunction(NewCallee);
4074 return CS.getInstruction();
4075}