1 //===- InstCombineCalls.cpp -----------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the visitCall and visitInvoke functions.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "InstCombineInternal.h"
14 #include "llvm/ADT/APFloat.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/None.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/ADT/STLExtras.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/Twine.h"
23 #include "llvm/Analysis/AssumptionCache.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/MemoryBuiltins.h"
26 #include "llvm/Transforms/Utils/Local.h"
27 #include "llvm/Analysis/ValueTracking.h"
28 #include "llvm/IR/Attributes.h"
29 #include "llvm/IR/BasicBlock.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/Constant.h"
32 #include "llvm/IR/Constants.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/Function.h"
36 #include "llvm/IR/GlobalVariable.h"
37 #include "llvm/IR/InstrTypes.h"
38 #include "llvm/IR/Instruction.h"
39 #include "llvm/IR/Instructions.h"
40 #include "llvm/IR/IntrinsicInst.h"
41 #include "llvm/IR/Intrinsics.h"
42 #include "llvm/IR/LLVMContext.h"
43 #include "llvm/IR/Metadata.h"
44 #include "llvm/IR/PatternMatch.h"
45 #include "llvm/IR/Statepoint.h"
46 #include "llvm/IR/Type.h"
47 #include "llvm/IR/User.h"
48 #include "llvm/IR/Value.h"
49 #include "llvm/IR/ValueHandle.h"
50 #include "llvm/Support/AtomicOrdering.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CommandLine.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/Support/Debug.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/KnownBits.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
60 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
61 #include <algorithm>
62 #include <cassert>
63 #include <cstdint>
64 #include <cstring>
65 #include <utility>
66 #include <vector>
67 
68 using namespace llvm;
69 using namespace PatternMatch;
70 
71 #define DEBUG_TYPE "instcombine"
72 
73 STATISTIC(NumSimplified, "Number of library calls simplified");
74 
75 static cl::opt<unsigned> GuardWideningWindow(
76     "instcombine-guard-widening-window",
77     cl::init(3),
78     cl::desc("How wide an instruction window to bypass looking for "
79              "another guard"));
80 
81 /// Return the specified type promoted as it would be to pass though a va_arg
82 /// area.
83 static Type *getPromotedType(Type *Ty) {
84   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
85     if (ITy->getBitWidth() < 32)
86       return Type::getInt32Ty(Ty->getContext());
87   }
88   return Ty;
89 }
90 
91 /// Return a constant boolean vector that has true elements in all positions
92 /// where the input constant data vector has an element with the sign bit set.
93 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
94   SmallVector<Constant *, 32> BoolVec;
95   IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
96   for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
97     Constant *Elt = V->getElementAsConstant(I);
98     assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
99            "Unexpected constant data vector element type");
100     bool Sign = V->getElementType()->isIntegerTy()
101                     ? cast<ConstantInt>(Elt)->isNegative()
102                     : cast<ConstantFP>(Elt)->isNegative();
103     BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
104   }
105   return ConstantVector::get(BoolVec);
106 }
107 
108 Instruction *InstCombiner::SimplifyAnyMemTransfer(AnyMemTransferInst *MI) {
109   unsigned DstAlign = getKnownAlignment(MI->getRawDest(), DL, MI, &AC, &DT);
110   unsigned CopyDstAlign = MI->getDestAlignment();
111   if (CopyDstAlign < DstAlign){
112     MI->setDestAlignment(DstAlign);
113     return MI;
114   }
115 
116   unsigned SrcAlign = getKnownAlignment(MI->getRawSource(), DL, MI, &AC, &DT);
117   unsigned CopySrcAlign = MI->getSourceAlignment();
118   if (CopySrcAlign < SrcAlign) {
119     MI->setSourceAlignment(SrcAlign);
120     return MI;
121   }
122 
123   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
124   // load/store.
125   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getLength());
126   if (!MemOpLength) return nullptr;
127 
128   // Source and destination pointer types are always "i8*" for intrinsic.  See
129   // if the size is something we can handle with a single primitive load/store.
130   // A single load+store correctly handles overlapping memory in the memmove
131   // case.
132   uint64_t Size = MemOpLength->getLimitedValue();
133   assert(Size && "0-sized memory transferring should be removed already.");
134 
135   if (Size > 8 || (Size&(Size-1)))
136     return nullptr;  // If not 1/2/4/8 bytes, exit.
137 
138   // If it is an atomic and alignment is less than the size then we will
139   // introduce the unaligned memory access which will be later transformed
140   // into libcall in CodeGen. This is not evident performance gain so disable
141   // it now.
142   if (isa<AtomicMemTransferInst>(MI))
143     if (CopyDstAlign < Size || CopySrcAlign < Size)
144       return nullptr;
145 
146   // Use an integer load+store unless we can find something better.
147   unsigned SrcAddrSp =
148     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
149   unsigned DstAddrSp =
150     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
151 
152   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
153   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
154   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
155 
156   // If the memcpy has metadata describing the members, see if we can get the
157   // TBAA tag describing our copy.
158   MDNode *CopyMD = nullptr;
159   if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa)) {
160     CopyMD = M;
161   } else if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
162     if (M->getNumOperands() == 3 && M->getOperand(0) &&
163         mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
164         mdconst::extract<ConstantInt>(M->getOperand(0))->isZero() &&
165         M->getOperand(1) &&
166         mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
167         mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
168         Size &&
169         M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
170       CopyMD = cast<MDNode>(M->getOperand(2));
171   }
172 
173   Value *Src = Builder.CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
174   Value *Dest = Builder.CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
175   LoadInst *L = Builder.CreateLoad(Src);
176   // Alignment from the mem intrinsic will be better, so use it.
177   L->setAlignment(CopySrcAlign);
178   if (CopyMD)
179     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
180   MDNode *LoopMemParallelMD =
181     MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
182   if (LoopMemParallelMD)
183     L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
184   MDNode *AccessGroupMD = MI->getMetadata(LLVMContext::MD_access_group);
185   if (AccessGroupMD)
186     L->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
187 
188   StoreInst *S = Builder.CreateStore(L, Dest);
189   // Alignment from the mem intrinsic will be better, so use it.
190   S->setAlignment(CopyDstAlign);
191   if (CopyMD)
192     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
193   if (LoopMemParallelMD)
194     S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
195   if (AccessGroupMD)
196     S->setMetadata(LLVMContext::MD_access_group, AccessGroupMD);
197 
198   if (auto *MT = dyn_cast<MemTransferInst>(MI)) {
199     // non-atomics can be volatile
200     L->setVolatile(MT->isVolatile());
201     S->setVolatile(MT->isVolatile());
202   }
203   if (isa<AtomicMemTransferInst>(MI)) {
204     // atomics have to be unordered
205     L->setOrdering(AtomicOrdering::Unordered);
206     S->setOrdering(AtomicOrdering::Unordered);
207   }
208 
209   // Set the size of the copy to 0, it will be deleted on the next iteration.
210   MI->setLength(Constant::getNullValue(MemOpLength->getType()));
211   return MI;
212 }
213 
214 Instruction *InstCombiner::SimplifyAnyMemSet(AnyMemSetInst *MI) {
215   unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
216   if (MI->getDestAlignment() < Alignment) {
217     MI->setDestAlignment(Alignment);
218     return MI;
219   }
220 
221   // Extract the length and alignment and fill if they are constant.
222   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
223   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
224   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
225     return nullptr;
226   uint64_t Len = LenC->getLimitedValue();
227   Alignment = MI->getDestAlignment();
228   assert(Len && "0-sized memory setting should be removed already.");
229 
230   // Alignment 0 is identity for alignment 1 for memset, but not store.
231   if (Alignment == 0)
232     Alignment = 1;
233 
234   // If it is an atomic and alignment is less than the size then we will
235   // introduce the unaligned memory access which will be later transformed
236   // into libcall in CodeGen. This is not evident performance gain so disable
237   // it now.
238   if (isa<AtomicMemSetInst>(MI))
239     if (Alignment < Len)
240       return nullptr;
241 
242   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
243   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
244     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
245 
246     Value *Dest = MI->getDest();
247     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
248     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
249     Dest = Builder.CreateBitCast(Dest, NewDstPtrTy);
250 
251     // Extract the fill value and store.
252     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
253     StoreInst *S = Builder.CreateStore(ConstantInt::get(ITy, Fill), Dest,
254                                        MI->isVolatile());
255     S->setAlignment(Alignment);
256     if (isa<AtomicMemSetInst>(MI))
257       S->setOrdering(AtomicOrdering::Unordered);
258 
259     // Set the size of the copy to 0, it will be deleted on the next iteration.
260     MI->setLength(Constant::getNullValue(LenC->getType()));
261     return MI;
262   }
263 
264   return nullptr;
265 }
266 
267 static Value *simplifyX86immShift(const IntrinsicInst &II,
268                                   InstCombiner::BuilderTy &Builder) {
269   bool LogicalShift = false;
270   bool ShiftLeft = false;
271 
272   switch (II.getIntrinsicID()) {
273   default: llvm_unreachable("Unexpected intrinsic!");
274   case Intrinsic::x86_sse2_psra_d:
275   case Intrinsic::x86_sse2_psra_w:
276   case Intrinsic::x86_sse2_psrai_d:
277   case Intrinsic::x86_sse2_psrai_w:
278   case Intrinsic::x86_avx2_psra_d:
279   case Intrinsic::x86_avx2_psra_w:
280   case Intrinsic::x86_avx2_psrai_d:
281   case Intrinsic::x86_avx2_psrai_w:
282   case Intrinsic::x86_avx512_psra_q_128:
283   case Intrinsic::x86_avx512_psrai_q_128:
284   case Intrinsic::x86_avx512_psra_q_256:
285   case Intrinsic::x86_avx512_psrai_q_256:
286   case Intrinsic::x86_avx512_psra_d_512:
287   case Intrinsic::x86_avx512_psra_q_512:
288   case Intrinsic::x86_avx512_psra_w_512:
289   case Intrinsic::x86_avx512_psrai_d_512:
290   case Intrinsic::x86_avx512_psrai_q_512:
291   case Intrinsic::x86_avx512_psrai_w_512:
292     LogicalShift = false; ShiftLeft = false;
293     break;
294   case Intrinsic::x86_sse2_psrl_d:
295   case Intrinsic::x86_sse2_psrl_q:
296   case Intrinsic::x86_sse2_psrl_w:
297   case Intrinsic::x86_sse2_psrli_d:
298   case Intrinsic::x86_sse2_psrli_q:
299   case Intrinsic::x86_sse2_psrli_w:
300   case Intrinsic::x86_avx2_psrl_d:
301   case Intrinsic::x86_avx2_psrl_q:
302   case Intrinsic::x86_avx2_psrl_w:
303   case Intrinsic::x86_avx2_psrli_d:
304   case Intrinsic::x86_avx2_psrli_q:
305   case Intrinsic::x86_avx2_psrli_w:
306   case Intrinsic::x86_avx512_psrl_d_512:
307   case Intrinsic::x86_avx512_psrl_q_512:
308   case Intrinsic::x86_avx512_psrl_w_512:
309   case Intrinsic::x86_avx512_psrli_d_512:
310   case Intrinsic::x86_avx512_psrli_q_512:
311   case Intrinsic::x86_avx512_psrli_w_512:
312     LogicalShift = true; ShiftLeft = false;
313     break;
314   case Intrinsic::x86_sse2_psll_d:
315   case Intrinsic::x86_sse2_psll_q:
316   case Intrinsic::x86_sse2_psll_w:
317   case Intrinsic::x86_sse2_pslli_d:
318   case Intrinsic::x86_sse2_pslli_q:
319   case Intrinsic::x86_sse2_pslli_w:
320   case Intrinsic::x86_avx2_psll_d:
321   case Intrinsic::x86_avx2_psll_q:
322   case Intrinsic::x86_avx2_psll_w:
323   case Intrinsic::x86_avx2_pslli_d:
324   case Intrinsic::x86_avx2_pslli_q:
325   case Intrinsic::x86_avx2_pslli_w:
326   case Intrinsic::x86_avx512_psll_d_512:
327   case Intrinsic::x86_avx512_psll_q_512:
328   case Intrinsic::x86_avx512_psll_w_512:
329   case Intrinsic::x86_avx512_pslli_d_512:
330   case Intrinsic::x86_avx512_pslli_q_512:
331   case Intrinsic::x86_avx512_pslli_w_512:
332     LogicalShift = true; ShiftLeft = true;
333     break;
334   }
335   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
336 
337   // Simplify if count is constant.
338   auto Arg1 = II.getArgOperand(1);
339   auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
340   auto CDV = dyn_cast<ConstantDataVector>(Arg1);
341   auto CInt = dyn_cast<ConstantInt>(Arg1);
342   if (!CAZ && !CDV && !CInt)
343     return nullptr;
344 
345   APInt Count(64, 0);
346   if (CDV) {
347     // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
348     // operand to compute the shift amount.
349     auto VT = cast<VectorType>(CDV->getType());
350     unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
351     assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
352     unsigned NumSubElts = 64 / BitWidth;
353 
354     // Concatenate the sub-elements to create the 64-bit value.
355     for (unsigned i = 0; i != NumSubElts; ++i) {
356       unsigned SubEltIdx = (NumSubElts - 1) - i;
357       auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
358       Count <<= BitWidth;
359       Count |= SubElt->getValue().zextOrTrunc(64);
360     }
361   }
362   else if (CInt)
363     Count = CInt->getValue();
364 
365   auto Vec = II.getArgOperand(0);
366   auto VT = cast<VectorType>(Vec->getType());
367   auto SVT = VT->getElementType();
368   unsigned VWidth = VT->getNumElements();
369   unsigned BitWidth = SVT->getPrimitiveSizeInBits();
370 
371   // If shift-by-zero then just return the original value.
372   if (Count.isNullValue())
373     return Vec;
374 
375   // Handle cases when Shift >= BitWidth.
376   if (Count.uge(BitWidth)) {
377     // If LogicalShift - just return zero.
378     if (LogicalShift)
379       return ConstantAggregateZero::get(VT);
380 
381     // If ArithmeticShift - clamp Shift to (BitWidth - 1).
382     Count = APInt(64, BitWidth - 1);
383   }
384 
385   // Get a constant vector of the same type as the first operand.
386   auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
387   auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
388 
389   if (ShiftLeft)
390     return Builder.CreateShl(Vec, ShiftVec);
391 
392   if (LogicalShift)
393     return Builder.CreateLShr(Vec, ShiftVec);
394 
395   return Builder.CreateAShr(Vec, ShiftVec);
396 }
397 
398 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
399 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out
400 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
401 static Value *simplifyX86varShift(const IntrinsicInst &II,
402                                   InstCombiner::BuilderTy &Builder) {
403   bool LogicalShift = false;
404   bool ShiftLeft = false;
405 
406   switch (II.getIntrinsicID()) {
407   default: llvm_unreachable("Unexpected intrinsic!");
408   case Intrinsic::x86_avx2_psrav_d:
409   case Intrinsic::x86_avx2_psrav_d_256:
410   case Intrinsic::x86_avx512_psrav_q_128:
411   case Intrinsic::x86_avx512_psrav_q_256:
412   case Intrinsic::x86_avx512_psrav_d_512:
413   case Intrinsic::x86_avx512_psrav_q_512:
414   case Intrinsic::x86_avx512_psrav_w_128:
415   case Intrinsic::x86_avx512_psrav_w_256:
416   case Intrinsic::x86_avx512_psrav_w_512:
417     LogicalShift = false;
418     ShiftLeft = false;
419     break;
420   case Intrinsic::x86_avx2_psrlv_d:
421   case Intrinsic::x86_avx2_psrlv_d_256:
422   case Intrinsic::x86_avx2_psrlv_q:
423   case Intrinsic::x86_avx2_psrlv_q_256:
424   case Intrinsic::x86_avx512_psrlv_d_512:
425   case Intrinsic::x86_avx512_psrlv_q_512:
426   case Intrinsic::x86_avx512_psrlv_w_128:
427   case Intrinsic::x86_avx512_psrlv_w_256:
428   case Intrinsic::x86_avx512_psrlv_w_512:
429     LogicalShift = true;
430     ShiftLeft = false;
431     break;
432   case Intrinsic::x86_avx2_psllv_d:
433   case Intrinsic::x86_avx2_psllv_d_256:
434   case Intrinsic::x86_avx2_psllv_q:
435   case Intrinsic::x86_avx2_psllv_q_256:
436   case Intrinsic::x86_avx512_psllv_d_512:
437   case Intrinsic::x86_avx512_psllv_q_512:
438   case Intrinsic::x86_avx512_psllv_w_128:
439   case Intrinsic::x86_avx512_psllv_w_256:
440   case Intrinsic::x86_avx512_psllv_w_512:
441     LogicalShift = true;
442     ShiftLeft = true;
443     break;
444   }
445   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
446 
447   // Simplify if all shift amounts are constant/undef.
448   auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
449   if (!CShift)
450     return nullptr;
451 
452   auto Vec = II.getArgOperand(0);
453   auto VT = cast<VectorType>(II.getType());
454   auto SVT = VT->getVectorElementType();
455   int NumElts = VT->getNumElements();
456   int BitWidth = SVT->getIntegerBitWidth();
457 
458   // Collect each element's shift amount.
459   // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
460   bool AnyOutOfRange = false;
461   SmallVector<int, 8> ShiftAmts;
462   for (int I = 0; I < NumElts; ++I) {
463     auto *CElt = CShift->getAggregateElement(I);
464     if (CElt && isa<UndefValue>(CElt)) {
465       ShiftAmts.push_back(-1);
466       continue;
467     }
468 
469     auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
470     if (!COp)
471       return nullptr;
472 
473     // Handle out of range shifts.
474     // If LogicalShift - set to BitWidth (special case).
475     // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
476     APInt ShiftVal = COp->getValue();
477     if (ShiftVal.uge(BitWidth)) {
478       AnyOutOfRange = LogicalShift;
479       ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
480       continue;
481     }
482 
483     ShiftAmts.push_back((int)ShiftVal.getZExtValue());
484   }
485 
486   // If all elements out of range or UNDEF, return vector of zeros/undefs.
487   // ArithmeticShift should only hit this if they are all UNDEF.
488   auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
489   if (llvm::all_of(ShiftAmts, OutOfRange)) {
490     SmallVector<Constant *, 8> ConstantVec;
491     for (int Idx : ShiftAmts) {
492       if (Idx < 0) {
493         ConstantVec.push_back(UndefValue::get(SVT));
494       } else {
495         assert(LogicalShift && "Logical shift expected");
496         ConstantVec.push_back(ConstantInt::getNullValue(SVT));
497       }
498     }
499     return ConstantVector::get(ConstantVec);
500   }
501 
502   // We can't handle only some out of range values with generic logical shifts.
503   if (AnyOutOfRange)
504     return nullptr;
505 
506   // Build the shift amount constant vector.
507   SmallVector<Constant *, 8> ShiftVecAmts;
508   for (int Idx : ShiftAmts) {
509     if (Idx < 0)
510       ShiftVecAmts.push_back(UndefValue::get(SVT));
511     else
512       ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
513   }
514   auto ShiftVec = ConstantVector::get(ShiftVecAmts);
515 
516   if (ShiftLeft)
517     return Builder.CreateShl(Vec, ShiftVec);
518 
519   if (LogicalShift)
520     return Builder.CreateLShr(Vec, ShiftVec);
521 
522   return Builder.CreateAShr(Vec, ShiftVec);
523 }
524 
525 static Value *simplifyX86pack(IntrinsicInst &II, bool IsSigned) {
526   Value *Arg0 = II.getArgOperand(0);
527   Value *Arg1 = II.getArgOperand(1);
528   Type *ResTy = II.getType();
529 
530   // Fast all undef handling.
531   if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
532     return UndefValue::get(ResTy);
533 
534   Type *ArgTy = Arg0->getType();
535   unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
536   unsigned NumDstElts = ResTy->getVectorNumElements();
537   unsigned NumSrcElts = ArgTy->getVectorNumElements();
538   assert(NumDstElts == (2 * NumSrcElts) && "Unexpected packing types");
539 
540   unsigned NumDstEltsPerLane = NumDstElts / NumLanes;
541   unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
542   unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
543   assert(ArgTy->getScalarSizeInBits() == (2 * DstScalarSizeInBits) &&
544          "Unexpected packing types");
545 
546   // Constant folding.
547   auto *Cst0 = dyn_cast<Constant>(Arg0);
548   auto *Cst1 = dyn_cast<Constant>(Arg1);
549   if (!Cst0 || !Cst1)
550     return nullptr;
551 
552   SmallVector<Constant *, 32> Vals;
553   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
554     for (unsigned Elt = 0; Elt != NumDstEltsPerLane; ++Elt) {
555       unsigned SrcIdx = Lane * NumSrcEltsPerLane + Elt % NumSrcEltsPerLane;
556       auto *Cst = (Elt >= NumSrcEltsPerLane) ? Cst1 : Cst0;
557       auto *COp = Cst->getAggregateElement(SrcIdx);
558       if (COp && isa<UndefValue>(COp)) {
559         Vals.push_back(UndefValue::get(ResTy->getScalarType()));
560         continue;
561       }
562 
563       auto *CInt = dyn_cast_or_null<ConstantInt>(COp);
564       if (!CInt)
565         return nullptr;
566 
567       APInt Val = CInt->getValue();
568       assert(Val.getBitWidth() == ArgTy->getScalarSizeInBits() &&
569              "Unexpected constant bitwidth");
570 
571       if (IsSigned) {
572         // PACKSS: Truncate signed value with signed saturation.
573         // Source values less than dst minint are saturated to minint.
574         // Source values greater than dst maxint are saturated to maxint.
575         if (Val.isSignedIntN(DstScalarSizeInBits))
576           Val = Val.trunc(DstScalarSizeInBits);
577         else if (Val.isNegative())
578           Val = APInt::getSignedMinValue(DstScalarSizeInBits);
579         else
580           Val = APInt::getSignedMaxValue(DstScalarSizeInBits);
581       } else {
582         // PACKUS: Truncate signed value with unsigned saturation.
583         // Source values less than zero are saturated to zero.
584         // Source values greater than dst maxuint are saturated to maxuint.
585         if (Val.isIntN(DstScalarSizeInBits))
586           Val = Val.trunc(DstScalarSizeInBits);
587         else if (Val.isNegative())
588           Val = APInt::getNullValue(DstScalarSizeInBits);
589         else
590           Val = APInt::getAllOnesValue(DstScalarSizeInBits);
591       }
592 
593       Vals.push_back(ConstantInt::get(ResTy->getScalarType(), Val));
594     }
595   }
596 
597   return ConstantVector::get(Vals);
598 }
599 
600 // Replace X86-specific intrinsics with generic floor-ceil where applicable.
601 static Value *simplifyX86round(IntrinsicInst &II,
602                                InstCombiner::BuilderTy &Builder) {
603   ConstantInt *Arg = nullptr;
604   Intrinsic::ID IntrinsicID = II.getIntrinsicID();
605 
606   if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
607       IntrinsicID == Intrinsic::x86_sse41_round_sd)
608     Arg = dyn_cast<ConstantInt>(II.getArgOperand(2));
609   else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
610            IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
611     Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
612   else
613     Arg = dyn_cast<ConstantInt>(II.getArgOperand(1));
614   if (!Arg)
615     return nullptr;
616   unsigned RoundControl = Arg->getZExtValue();
617 
618   Arg = nullptr;
619   unsigned SAE = 0;
620   if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
621       IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512)
622     Arg = dyn_cast<ConstantInt>(II.getArgOperand(4));
623   else if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
624            IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd)
625     Arg = dyn_cast<ConstantInt>(II.getArgOperand(5));
626   else
627     SAE = 4;
628   if (!SAE) {
629     if (!Arg)
630       return nullptr;
631     SAE = Arg->getZExtValue();
632   }
633 
634   if (SAE != 4 || (RoundControl != 2 /*ceil*/ && RoundControl != 1 /*floor*/))
635     return nullptr;
636 
637   Value *Src, *Dst, *Mask;
638   bool IsScalar = false;
639   if (IntrinsicID == Intrinsic::x86_sse41_round_ss ||
640       IntrinsicID == Intrinsic::x86_sse41_round_sd ||
641       IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
642       IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
643     IsScalar = true;
644     if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
645         IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
646       Mask = II.getArgOperand(3);
647       Value *Zero = Constant::getNullValue(Mask->getType());
648       Mask = Builder.CreateAnd(Mask, 1);
649       Mask = Builder.CreateICmp(ICmpInst::ICMP_NE, Mask, Zero);
650       Dst = II.getArgOperand(2);
651     } else
652       Dst = II.getArgOperand(0);
653     Src = Builder.CreateExtractElement(II.getArgOperand(1), (uint64_t)0);
654   } else {
655     Src = II.getArgOperand(0);
656     if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_128 ||
657         IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_256 ||
658         IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ps_512 ||
659         IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_128 ||
660         IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_256 ||
661         IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_pd_512) {
662       Dst = II.getArgOperand(2);
663       Mask = II.getArgOperand(3);
664     } else {
665       Dst = Src;
666       Mask = ConstantInt::getAllOnesValue(
667           Builder.getIntNTy(Src->getType()->getVectorNumElements()));
668     }
669   }
670 
671   Intrinsic::ID ID = (RoundControl == 2) ? Intrinsic::ceil : Intrinsic::floor;
672   Value *Res = Builder.CreateUnaryIntrinsic(ID, Src, &II);
673   if (!IsScalar) {
674     if (auto *C = dyn_cast<Constant>(Mask))
675       if (C->isAllOnesValue())
676         return Res;
677     auto *MaskTy = VectorType::get(
678         Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
679     Mask = Builder.CreateBitCast(Mask, MaskTy);
680     unsigned Width = Src->getType()->getVectorNumElements();
681     if (MaskTy->getVectorNumElements() > Width) {
682       uint32_t Indices[4];
683       for (unsigned i = 0; i != Width; ++i)
684         Indices[i] = i;
685       Mask = Builder.CreateShuffleVector(Mask, Mask,
686                                          makeArrayRef(Indices, Width));
687     }
688     return Builder.CreateSelect(Mask, Res, Dst);
689   }
690   if (IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_ss ||
691       IntrinsicID == Intrinsic::x86_avx512_mask_rndscale_sd) {
692     Dst = Builder.CreateExtractElement(Dst, (uint64_t)0);
693     Res = Builder.CreateSelect(Mask, Res, Dst);
694     Dst = II.getArgOperand(0);
695   }
696   return Builder.CreateInsertElement(Dst, Res, (uint64_t)0);
697 }
698 
699 static Value *simplifyX86movmsk(const IntrinsicInst &II,
700                                 InstCombiner::BuilderTy &Builder) {
701   Value *Arg = II.getArgOperand(0);
702   Type *ResTy = II.getType();
703   Type *ArgTy = Arg->getType();
704 
705   // movmsk(undef) -> zero as we must ensure the upper bits are zero.
706   if (isa<UndefValue>(Arg))
707     return Constant::getNullValue(ResTy);
708 
709   // We can't easily peek through x86_mmx types.
710   if (!ArgTy->isVectorTy())
711     return nullptr;
712 
713   if (auto *C = dyn_cast<Constant>(Arg)) {
714     // Extract signbits of the vector input and pack into integer result.
715     APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
716     for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
717       auto *COp = C->getAggregateElement(I);
718       if (!COp)
719         return nullptr;
720       if (isa<UndefValue>(COp))
721         continue;
722 
723       auto *CInt = dyn_cast<ConstantInt>(COp);
724       auto *CFp = dyn_cast<ConstantFP>(COp);
725       if (!CInt && !CFp)
726         return nullptr;
727 
728       if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
729         Result.setBit(I);
730     }
731     return Constant::getIntegerValue(ResTy, Result);
732   }
733 
734   // Look for a sign-extended boolean source vector as the argument to this
735   // movmsk. If the argument is bitcast, look through that, but make sure the
736   // source of that bitcast is still a vector with the same number of elements.
737   // TODO: We can also convert a bitcast with wider elements, but that requires
738   // duplicating the bool source sign bits to match the number of elements
739   // expected by the movmsk call.
740   Arg = peekThroughBitcast(Arg);
741   Value *X;
742   if (Arg->getType()->isVectorTy() &&
743       Arg->getType()->getVectorNumElements() == ArgTy->getVectorNumElements() &&
744       match(Arg, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)) {
745     // call iM movmsk(sext <N x i1> X) --> zext (bitcast <N x i1> X to iN) to iM
746     unsigned NumElts = X->getType()->getVectorNumElements();
747     Type *ScalarTy = Type::getIntNTy(Arg->getContext(), NumElts);
748     Value *BC = Builder.CreateBitCast(X, ScalarTy);
749     return Builder.CreateZExtOrTrunc(BC, ResTy);
750   }
751 
752   return nullptr;
753 }
754 
755 static Value *simplifyX86insertps(const IntrinsicInst &II,
756                                   InstCombiner::BuilderTy &Builder) {
757   auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
758   if (!CInt)
759     return nullptr;
760 
761   VectorType *VecTy = cast<VectorType>(II.getType());
762   assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
763 
764   // 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
768 
769   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;
773 
774   ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
775 
776   // 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;
780 
781   // Initialize by passing all of the first source bits through.
782   uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
783 
784   // 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;
800     } else {
801       // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
802       return nullptr;
803     }
804   } else {
805     // Replace the selected destination lane with the selected source lane.
806     ShuffleMask[DestLane] = SourceLane + 4;
807   }
808 
809   return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
810 }
811 
812 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
813 /// or conversion to a shuffle vector.
814 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
815                                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 =
827       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
828          : 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.lshrInPlace(Index);
886       Elt = Elt.zextOrTrunc(Length);
887       return LowConstantHighUndef(Elt.getZExtValue());
888     }
889 
890     // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
891     if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
892       Value *Args[] = {Op0, CILength, CIIndex};
893       Module *M = II.getModule();
894       Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
895       return Builder.CreateCall(F, Args);
896     }
897   }
898 
899   // Constant Fold - extraction from zero is always {zero, undef}.
900   if (CI0 && CI0->isZero())
901     return LowConstantHighUndef(0);
902 
903   return nullptr;
904 }
905 
906 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
907 /// folding or conversion to a shuffle vector.
908 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
909                                  APInt APLength, APInt APIndex,
910                                  InstCombiner::BuilderTy &Builder) {
911   // From AMD documentation: "The bit index and field length are each six bits
912   // in length other bits of the field are ignored."
913   APIndex = APIndex.zextOrTrunc(6);
914   APLength = APLength.zextOrTrunc(6);
915 
916   // Attempt to constant fold.
917   unsigned Index = APIndex.getZExtValue();
918 
919   // From AMD documentation: "a value of zero in the field length is
920   // defined as length of 64".
921   unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
922 
923   // From AMD documentation: "If the sum of the bit index + length field
924   // is greater than 64, the results are undefined".
925   unsigned End = Index + Length;
926 
927   // Note that both field index and field length are 8-bit quantities.
928   // Since variables 'Index' and 'Length' are unsigned values
929   // obtained from zero-extending field index and field length
930   // respectively, their sum should never wrap around.
931   if (End > 64)
932     return UndefValue::get(II.getType());
933 
934   // If we are inserting whole bytes, we can convert this to a shuffle.
935   // Lowering can recognize INSERTQI shuffle masks.
936   if ((Length % 8) == 0 && (Index % 8) == 0) {
937     // Convert bit indices to byte indices.
938     Length /= 8;
939     Index /= 8;
940 
941     Type *IntTy8 = Type::getInt8Ty(II.getContext());
942     Type *IntTy32 = Type::getInt32Ty(II.getContext());
943     VectorType *ShufTy = VectorType::get(IntTy8, 16);
944 
945     SmallVector<Constant *, 16> ShuffleMask;
946     for (int i = 0; i != (int)Index; ++i)
947       ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
948     for (int i = 0; i != (int)Length; ++i)
949       ShuffleMask.push_back(
950           Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
951     for (int i = Index + Length; i != 8; ++i)
952       ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
953     for (int i = 8; i != 16; ++i)
954       ShuffleMask.push_back(UndefValue::get(IntTy32));
955 
956     Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
957                                             Builder.CreateBitCast(Op1, ShufTy),
958                                             ConstantVector::get(ShuffleMask));
959     return Builder.CreateBitCast(SV, II.getType());
960   }
961 
962   // See if we're dealing with constant values.
963   Constant *C0 = dyn_cast<Constant>(Op0);
964   Constant *C1 = dyn_cast<Constant>(Op1);
965   ConstantInt *CI00 =
966       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
967          : nullptr;
968   ConstantInt *CI10 =
969       C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
970          : nullptr;
971 
972   // Constant Fold - insert bottom Length bits starting at the Index'th bit.
973   if (CI00 && CI10) {
974     APInt V00 = CI00->getValue();
975     APInt V10 = CI10->getValue();
976     APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
977     V00 = V00 & ~Mask;
978     V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
979     APInt Val = V00 | V10;
980     Type *IntTy64 = Type::getInt64Ty(II.getContext());
981     Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
982                         UndefValue::get(IntTy64)};
983     return ConstantVector::get(Args);
984   }
985 
986   // If we were an INSERTQ call, we'll save demanded elements if we convert to
987   // INSERTQI.
988   if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
989     Type *IntTy8 = Type::getInt8Ty(II.getContext());
990     Constant *CILength = ConstantInt::get(IntTy8, Length, false);
991     Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
992 
993     Value *Args[] = {Op0, Op1, CILength, CIIndex};
994     Module *M = II.getModule();
995     Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
996     return Builder.CreateCall(F, Args);
997   }
998 
999   return nullptr;
1000 }
1001 
1002 /// Attempt to convert pshufb* to shufflevector if the mask is constant.
1003 static Value *simplifyX86pshufb(const IntrinsicInst &II,
1004                                 InstCombiner::BuilderTy &Builder) {
1005   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1006   if (!V)
1007     return nullptr;
1008 
1009   auto *VecTy = cast<VectorType>(II.getType());
1010   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1011   unsigned NumElts = VecTy->getNumElements();
1012   assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
1013          "Unexpected number of elements in shuffle mask!");
1014 
1015   // Construct a shuffle mask from constant integers or UNDEFs.
1016   Constant *Indexes[64] = {nullptr};
1017 
1018   // Each byte in the shuffle control mask forms an index to permute the
1019   // corresponding byte in the destination operand.
1020   for (unsigned I = 0; I < NumElts; ++I) {
1021     Constant *COp = V->getAggregateElement(I);
1022     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
1023       return nullptr;
1024 
1025     if (isa<UndefValue>(COp)) {
1026       Indexes[I] = UndefValue::get(MaskEltTy);
1027       continue;
1028     }
1029 
1030     int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
1031 
1032     // If the most significant bit (bit[7]) of each byte of the shuffle
1033     // control mask is set, then zero is written in the result byte.
1034     // The zero vector is in the right-hand side of the resulting
1035     // shufflevector.
1036 
1037     // The value of each index for the high 128-bit lane is the least
1038     // significant 4 bits of the respective shuffle control byte.
1039     Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
1040     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
1041   }
1042 
1043   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
1044   auto V1 = II.getArgOperand(0);
1045   auto V2 = Constant::getNullValue(VecTy);
1046   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1047 }
1048 
1049 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
1050 static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
1051                                     InstCombiner::BuilderTy &Builder) {
1052   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
1053   if (!V)
1054     return nullptr;
1055 
1056   auto *VecTy = cast<VectorType>(II.getType());
1057   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1058   unsigned NumElts = VecTy->getVectorNumElements();
1059   bool IsPD = VecTy->getScalarType()->isDoubleTy();
1060   unsigned NumLaneElts = IsPD ? 2 : 4;
1061   assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
1062 
1063   // Construct a shuffle mask from constant integers or UNDEFs.
1064   Constant *Indexes[16] = {nullptr};
1065 
1066   // The intrinsics only read one or two bits, clear the rest.
1067   for (unsigned I = 0; I < NumElts; ++I) {
1068     Constant *COp = V->getAggregateElement(I);
1069     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
1070       return nullptr;
1071 
1072     if (isa<UndefValue>(COp)) {
1073       Indexes[I] = UndefValue::get(MaskEltTy);
1074       continue;
1075     }
1076 
1077     APInt Index = cast<ConstantInt>(COp)->getValue();
1078     Index = Index.zextOrTrunc(32).getLoBits(2);
1079 
1080     // The PD variants uses bit 1 to select per-lane element index, so
1081     // shift down to convert to generic shuffle mask index.
1082     if (IsPD)
1083       Index.lshrInPlace(1);
1084 
1085     // The _256 variants are a bit trickier since the mask bits always index
1086     // into the corresponding 128 half. In order to convert to a generic
1087     // shuffle, we have to make that explicit.
1088     Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
1089 
1090     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
1091   }
1092 
1093   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
1094   auto V1 = II.getArgOperand(0);
1095   auto V2 = UndefValue::get(V1->getType());
1096   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1097 }
1098 
1099 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
1100 static Value *simplifyX86vpermv(const IntrinsicInst &II,
1101                                 InstCombiner::BuilderTy &Builder) {
1102   auto *V = dyn_cast<Constant>(II.getArgOperand(1));
1103   if (!V)
1104     return nullptr;
1105 
1106   auto *VecTy = cast<VectorType>(II.getType());
1107   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
1108   unsigned Size = VecTy->getNumElements();
1109   assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
1110          "Unexpected shuffle mask size");
1111 
1112   // Construct a shuffle mask from constant integers or UNDEFs.
1113   Constant *Indexes[64] = {nullptr};
1114 
1115   for (unsigned I = 0; I < Size; ++I) {
1116     Constant *COp = V->getAggregateElement(I);
1117     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
1118       return nullptr;
1119 
1120     if (isa<UndefValue>(COp)) {
1121       Indexes[I] = UndefValue::get(MaskEltTy);
1122       continue;
1123     }
1124 
1125     uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
1126     Index &= Size - 1;
1127     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
1128   }
1129 
1130   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
1131   auto V1 = II.getArgOperand(0);
1132   auto V2 = UndefValue::get(VecTy);
1133   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1134 }
1135 
1136 static bool maskIsAllOneOrUndef(Value *Mask) {
1137   auto *ConstMask = dyn_cast<Constant>(Mask);
1138   if (!ConstMask)
1139     return false;
1140   if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1141     return true;
1142   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1143        ++I) {
1144     if (auto *MaskElt = ConstMask->getAggregateElement(I))
1145       if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1146         continue;
1147     return false;
1148   }
1149   return true;
1150 }
1151 
1152 static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1153                                  InstCombiner::BuilderTy &Builder) {
1154   // If the mask is all ones or undefs, this is a plain vector load of the 1st
1155   // argument.
1156   if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
1157     Value *LoadPtr = II.getArgOperand(0);
1158     unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1159     return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1160   }
1161 
1162   return nullptr;
1163 }
1164 
1165 static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1166   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1167   if (!ConstMask)
1168     return nullptr;
1169 
1170   // If the mask is all zeros, this instruction does nothing.
1171   if (ConstMask->isNullValue())
1172     return IC.eraseInstFromFunction(II);
1173 
1174   // If the mask is all ones, this is a plain vector store of the 1st argument.
1175   if (ConstMask->isAllOnesValue()) {
1176     Value *StorePtr = II.getArgOperand(1);
1177     unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1178     return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1179   }
1180 
1181   return nullptr;
1182 }
1183 
1184 static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1185   // If the mask is all zeros, return the "passthru" argument of the gather.
1186   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1187   if (ConstMask && ConstMask->isNullValue())
1188     return IC.replaceInstUsesWith(II, II.getArgOperand(3));
1189 
1190   return nullptr;
1191 }
1192 
1193 /// This function transforms launder.invariant.group and strip.invariant.group
1194 /// like:
1195 /// launder(launder(%x)) -> launder(%x)       (the result is not the argument)
1196 /// launder(strip(%x)) -> launder(%x)
1197 /// strip(strip(%x)) -> strip(%x)             (the result is not the argument)
1198 /// strip(launder(%x)) -> strip(%x)
1199 /// This is legal because it preserves the most recent information about
1200 /// the presence or absence of invariant.group.
1201 static Instruction *simplifyInvariantGroupIntrinsic(IntrinsicInst &II,
1202                                                     InstCombiner &IC) {
1203   auto *Arg = II.getArgOperand(0);
1204   auto *StrippedArg = Arg->stripPointerCasts();
1205   auto *StrippedInvariantGroupsArg = Arg->stripPointerCastsAndInvariantGroups();
1206   if (StrippedArg == StrippedInvariantGroupsArg)
1207     return nullptr; // No launders/strips to remove.
1208 
1209   Value *Result = nullptr;
1210 
1211   if (II.getIntrinsicID() == Intrinsic::launder_invariant_group)
1212     Result = IC.Builder.CreateLaunderInvariantGroup(StrippedInvariantGroupsArg);
1213   else if (II.getIntrinsicID() == Intrinsic::strip_invariant_group)
1214     Result = IC.Builder.CreateStripInvariantGroup(StrippedInvariantGroupsArg);
1215   else
1216     llvm_unreachable(
1217         "simplifyInvariantGroupIntrinsic only handles launder and strip");
1218   if (Result->getType()->getPointerAddressSpace() !=
1219       II.getType()->getPointerAddressSpace())
1220     Result = IC.Builder.CreateAddrSpaceCast(Result, II.getType());
1221   if (Result->getType() != II.getType())
1222     Result = IC.Builder.CreateBitCast(Result, II.getType());
1223 
1224   return cast<Instruction>(Result);
1225 }
1226 
1227 static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1228   // If the mask is all zeros, a scatter does nothing.
1229   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1230   if (ConstMask && ConstMask->isNullValue())
1231     return IC.eraseInstFromFunction(II);
1232 
1233   return nullptr;
1234 }
1235 
1236 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1237   assert((II.getIntrinsicID() == Intrinsic::cttz ||
1238           II.getIntrinsicID() == Intrinsic::ctlz) &&
1239          "Expected cttz or ctlz intrinsic");
1240   Value *Op0 = II.getArgOperand(0);
1241 
1242   KnownBits Known = IC.computeKnownBits(Op0, 0, &II);
1243 
1244   // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1245   bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1246   unsigned PossibleZeros = IsTZ ? Known.countMaxTrailingZeros()
1247                                 : Known.countMaxLeadingZeros();
1248   unsigned DefiniteZeros = IsTZ ? Known.countMinTrailingZeros()
1249                                 : Known.countMinLeadingZeros();
1250 
1251   // If all bits above (ctlz) or below (cttz) the first known one are known
1252   // zero, this value is constant.
1253   // FIXME: This should be in InstSimplify because we're replacing an
1254   // instruction with a constant.
1255   if (PossibleZeros == DefiniteZeros) {
1256     auto *C = ConstantInt::get(Op0->getType(), DefiniteZeros);
1257     return IC.replaceInstUsesWith(II, C);
1258   }
1259 
1260   // If the input to cttz/ctlz is known to be non-zero,
1261   // then change the 'ZeroIsUndef' parameter to 'true'
1262   // because we know the zero behavior can't affect the result.
1263   if (!Known.One.isNullValue() ||
1264       isKnownNonZero(Op0, IC.getDataLayout(), 0, &IC.getAssumptionCache(), &II,
1265                      &IC.getDominatorTree())) {
1266     if (!match(II.getArgOperand(1), m_One())) {
1267       II.setOperand(1, IC.Builder.getTrue());
1268       return &II;
1269     }
1270   }
1271 
1272   // Add range metadata since known bits can't completely reflect what we know.
1273   // TODO: Handle splat vectors.
1274   auto *IT = dyn_cast<IntegerType>(Op0->getType());
1275   if (IT && IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1276     Metadata *LowAndHigh[] = {
1277         ConstantAsMetadata::get(ConstantInt::get(IT, DefiniteZeros)),
1278         ConstantAsMetadata::get(ConstantInt::get(IT, PossibleZeros + 1))};
1279     II.setMetadata(LLVMContext::MD_range,
1280                    MDNode::get(II.getContext(), LowAndHigh));
1281     return &II;
1282   }
1283 
1284   return nullptr;
1285 }
1286 
1287 static Instruction *foldCtpop(IntrinsicInst &II, InstCombiner &IC) {
1288   assert(II.getIntrinsicID() == Intrinsic::ctpop &&
1289          "Expected ctpop intrinsic");
1290   Value *Op0 = II.getArgOperand(0);
1291   // FIXME: Try to simplify vectors of integers.
1292   auto *IT = dyn_cast<IntegerType>(Op0->getType());
1293   if (!IT)
1294     return nullptr;
1295 
1296   unsigned BitWidth = IT->getBitWidth();
1297   KnownBits Known(BitWidth);
1298   IC.computeKnownBits(Op0, Known, 0, &II);
1299 
1300   unsigned MinCount = Known.countMinPopulation();
1301   unsigned MaxCount = Known.countMaxPopulation();
1302 
1303   // Add range metadata since known bits can't completely reflect what we know.
1304   if (IT->getBitWidth() != 1 && !II.getMetadata(LLVMContext::MD_range)) {
1305     Metadata *LowAndHigh[] = {
1306         ConstantAsMetadata::get(ConstantInt::get(IT, MinCount)),
1307         ConstantAsMetadata::get(ConstantInt::get(IT, MaxCount + 1))};
1308     II.setMetadata(LLVMContext::MD_range,
1309                    MDNode::get(II.getContext(), LowAndHigh));
1310     return &II;
1311   }
1312 
1313   return nullptr;
1314 }
1315 
1316 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1317 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1318 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1319 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1320   Value *Ptr = II.getOperand(0);
1321   Value *Mask = II.getOperand(1);
1322   Constant *ZeroVec = Constant::getNullValue(II.getType());
1323 
1324   // Special case a zero mask since that's not a ConstantDataVector.
1325   // This masked load instruction creates a zero vector.
1326   if (isa<ConstantAggregateZero>(Mask))
1327     return IC.replaceInstUsesWith(II, ZeroVec);
1328 
1329   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1330   if (!ConstMask)
1331     return nullptr;
1332 
1333   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1334   // to allow target-independent optimizations.
1335 
1336   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1337   // the LLVM intrinsic definition for the pointer argument.
1338   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1339   PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1340   Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
1341 
1342   // Second, convert the x86 XMM integer vector mask to a vector of bools based
1343   // on each element's most significant bit (the sign bit).
1344   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1345 
1346   // The pass-through vector for an x86 masked load is a zero vector.
1347   CallInst *NewMaskedLoad =
1348       IC.Builder.CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
1349   return IC.replaceInstUsesWith(II, NewMaskedLoad);
1350 }
1351 
1352 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1353 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1354 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1355 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1356   Value *Ptr = II.getOperand(0);
1357   Value *Mask = II.getOperand(1);
1358   Value *Vec = II.getOperand(2);
1359 
1360   // Special case a zero mask since that's not a ConstantDataVector:
1361   // this masked store instruction does nothing.
1362   if (isa<ConstantAggregateZero>(Mask)) {
1363     IC.eraseInstFromFunction(II);
1364     return true;
1365   }
1366 
1367   // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1368   // anything else at this level.
1369   if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1370     return false;
1371 
1372   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1373   if (!ConstMask)
1374     return false;
1375 
1376   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1377   // to allow target-independent optimizations.
1378 
1379   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1380   // the LLVM intrinsic definition for the pointer argument.
1381   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1382   PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
1383   Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
1384 
1385   // Second, convert the x86 XMM integer vector mask to a vector of bools based
1386   // on each element's most significant bit (the sign bit).
1387   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1388 
1389   IC.Builder.CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1390 
1391   // 'Replace uses' doesn't work for stores. Erase the original masked store.
1392   IC.eraseInstFromFunction(II);
1393   return true;
1394 }
1395 
1396 // Constant fold llvm.amdgcn.fmed3 intrinsics for standard inputs.
1397 //
1398 // A single NaN input is folded to minnum, so we rely on that folding for
1399 // handling NaNs.
1400 static APFloat fmed3AMDGCN(const APFloat &Src0, const APFloat &Src1,
1401                            const APFloat &Src2) {
1402   APFloat Max3 = maxnum(maxnum(Src0, Src1), Src2);
1403 
1404   APFloat::cmpResult Cmp0 = Max3.compare(Src0);
1405   assert(Cmp0 != APFloat::cmpUnordered && "nans handled separately");
1406   if (Cmp0 == APFloat::cmpEqual)
1407     return maxnum(Src1, Src2);
1408 
1409   APFloat::cmpResult Cmp1 = Max3.compare(Src1);
1410   assert(Cmp1 != APFloat::cmpUnordered && "nans handled separately");
1411   if (Cmp1 == APFloat::cmpEqual)
1412     return maxnum(Src0, Src2);
1413 
1414   return maxnum(Src0, Src1);
1415 }
1416 
1417 /// Convert a table lookup to shufflevector if the mask is constant.
1418 /// This could benefit tbl1 if the mask is { 7,6,5,4,3,2,1,0 }, in
1419 /// which case we could lower the shufflevector with rev64 instructions
1420 /// as it's actually a byte reverse.
1421 static Value *simplifyNeonTbl1(const IntrinsicInst &II,
1422                                InstCombiner::BuilderTy &Builder) {
1423   // Bail out if the mask is not a constant.
1424   auto *C = dyn_cast<Constant>(II.getArgOperand(1));
1425   if (!C)
1426     return nullptr;
1427 
1428   auto *VecTy = cast<VectorType>(II.getType());
1429   unsigned NumElts = VecTy->getNumElements();
1430 
1431   // Only perform this transformation for <8 x i8> vector types.
1432   if (!VecTy->getElementType()->isIntegerTy(8) || NumElts != 8)
1433     return nullptr;
1434 
1435   uint32_t Indexes[8];
1436 
1437   for (unsigned I = 0; I < NumElts; ++I) {
1438     Constant *COp = C->getAggregateElement(I);
1439 
1440     if (!COp || !isa<ConstantInt>(COp))
1441       return nullptr;
1442 
1443     Indexes[I] = cast<ConstantInt>(COp)->getLimitedValue();
1444 
1445     // Make sure the mask indices are in range.
1446     if (Indexes[I] >= NumElts)
1447       return nullptr;
1448   }
1449 
1450   auto *ShuffleMask = ConstantDataVector::get(II.getContext(),
1451                                               makeArrayRef(Indexes));
1452   auto *V1 = II.getArgOperand(0);
1453   auto *V2 = Constant::getNullValue(V1->getType());
1454   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
1455 }
1456 
1457 /// Convert a vector load intrinsic into a simple llvm load instruction.
1458 /// This is beneficial when the underlying object being addressed comes
1459 /// from a constant, since we get constant-folding for free.
1460 static Value *simplifyNeonVld1(const IntrinsicInst &II,
1461                                unsigned MemAlign,
1462                                InstCombiner::BuilderTy &Builder) {
1463   auto *IntrAlign = dyn_cast<ConstantInt>(II.getArgOperand(1));
1464 
1465   if (!IntrAlign)
1466     return nullptr;
1467 
1468   unsigned Alignment = IntrAlign->getLimitedValue() < MemAlign ?
1469                        MemAlign : IntrAlign->getLimitedValue();
1470 
1471   if (!isPowerOf2_32(Alignment))
1472     return nullptr;
1473 
1474   auto *BCastInst = Builder.CreateBitCast(II.getArgOperand(0),
1475                                           PointerType::get(II.getType(), 0));
1476   return Builder.CreateAlignedLoad(BCastInst, Alignment);
1477 }
1478 
1479 // Returns true iff the 2 intrinsics have the same operands, limiting the
1480 // comparison to the first NumOperands.
1481 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1482                              unsigned NumOperands) {
1483   assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1484   assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1485   for (unsigned i = 0; i < NumOperands; i++)
1486     if (I.getArgOperand(i) != E.getArgOperand(i))
1487       return false;
1488   return true;
1489 }
1490 
1491 // Remove trivially empty start/end intrinsic ranges, i.e. a start
1492 // immediately followed by an end (ignoring debuginfo or other
1493 // start/end intrinsics in between). As this handles only the most trivial
1494 // cases, tracking the nesting level is not needed:
1495 //
1496 //   call @llvm.foo.start(i1 0) ; &I
1497 //   call @llvm.foo.start(i1 0)
1498 //   call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1499 //   call @llvm.foo.end(i1 0)
1500 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1501                                       unsigned EndID, InstCombiner &IC) {
1502   assert(I.getIntrinsicID() == StartID &&
1503          "Start intrinsic does not have expected ID");
1504   BasicBlock::iterator BI(I), BE(I.getParent()->end());
1505   for (++BI; BI != BE; ++BI) {
1506     if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1507       if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1508         continue;
1509       if (E->getIntrinsicID() == EndID &&
1510           haveSameOperands(I, *E, E->getNumArgOperands())) {
1511         IC.eraseInstFromFunction(*E);
1512         IC.eraseInstFromFunction(I);
1513         return true;
1514       }
1515     }
1516     break;
1517   }
1518 
1519   return false;
1520 }
1521 
1522 // Convert NVVM intrinsics to target-generic LLVM code where possible.
1523 static Instruction *SimplifyNVVMIntrinsic(IntrinsicInst *II, InstCombiner &IC) {
1524   // Each NVVM intrinsic we can simplify can be replaced with one of:
1525   //
1526   //  * an LLVM intrinsic,
1527   //  * an LLVM cast operation,
1528   //  * an LLVM binary operation, or
1529   //  * ad-hoc LLVM IR for the particular operation.
1530 
1531   // Some transformations are only valid when the module's
1532   // flush-denormals-to-zero (ftz) setting is true/false, whereas other
1533   // transformations are valid regardless of the module's ftz setting.
1534   enum FtzRequirementTy {
1535     FTZ_Any,       // Any ftz setting is ok.
1536     FTZ_MustBeOn,  // Transformation is valid only if ftz is on.
1537     FTZ_MustBeOff, // Transformation is valid only if ftz is off.
1538   };
1539   // Classes of NVVM intrinsics that can't be replaced one-to-one with a
1540   // target-generic intrinsic, cast op, or binary op but that we can nonetheless
1541   // simplify.
1542   enum SpecialCase {
1543     SPC_Reciprocal,
1544   };
1545 
1546   // SimplifyAction is a poor-man's variant (plus an additional flag) that
1547   // represents how to replace an NVVM intrinsic with target-generic LLVM IR.
1548   struct SimplifyAction {
1549     // Invariant: At most one of these Optionals has a value.
1550     Optional<Intrinsic::ID> IID;
1551     Optional<Instruction::CastOps> CastOp;
1552     Optional<Instruction::BinaryOps> BinaryOp;
1553     Optional<SpecialCase> Special;
1554 
1555     FtzRequirementTy FtzRequirement = FTZ_Any;
1556 
1557     SimplifyAction() = default;
1558 
1559     SimplifyAction(Intrinsic::ID IID, FtzRequirementTy FtzReq)
1560         : IID(IID), FtzRequirement(FtzReq) {}
1561 
1562     // Cast operations don't have anything to do with FTZ, so we skip that
1563     // argument.
1564     SimplifyAction(Instruction::CastOps CastOp) : CastOp(CastOp) {}
1565 
1566     SimplifyAction(Instruction::BinaryOps BinaryOp, FtzRequirementTy FtzReq)
1567         : BinaryOp(BinaryOp), FtzRequirement(FtzReq) {}
1568 
1569     SimplifyAction(SpecialCase Special, FtzRequirementTy FtzReq)
1570         : Special(Special), FtzRequirement(FtzReq) {}
1571   };
1572 
1573   // Try to generate a SimplifyAction describing how to replace our
1574   // IntrinsicInstr with target-generic LLVM IR.
1575   const SimplifyAction Action = [II]() -> SimplifyAction {
1576     switch (II->getIntrinsicID()) {
1577     // NVVM intrinsics that map directly to LLVM intrinsics.
1578     case Intrinsic::nvvm_ceil_d:
1579       return {Intrinsic::ceil, FTZ_Any};
1580     case Intrinsic::nvvm_ceil_f:
1581       return {Intrinsic::ceil, FTZ_MustBeOff};
1582     case Intrinsic::nvvm_ceil_ftz_f:
1583       return {Intrinsic::ceil, FTZ_MustBeOn};
1584     case Intrinsic::nvvm_fabs_d:
1585       return {Intrinsic::fabs, FTZ_Any};
1586     case Intrinsic::nvvm_fabs_f:
1587       return {Intrinsic::fabs, FTZ_MustBeOff};
1588     case Intrinsic::nvvm_fabs_ftz_f:
1589       return {Intrinsic::fabs, FTZ_MustBeOn};
1590     case Intrinsic::nvvm_floor_d:
1591       return {Intrinsic::floor, FTZ_Any};
1592     case Intrinsic::nvvm_floor_f:
1593       return {Intrinsic::floor, FTZ_MustBeOff};
1594     case Intrinsic::nvvm_floor_ftz_f:
1595       return {Intrinsic::floor, FTZ_MustBeOn};
1596     case Intrinsic::nvvm_fma_rn_d:
1597       return {Intrinsic::fma, FTZ_Any};
1598     case Intrinsic::nvvm_fma_rn_f:
1599       return {Intrinsic::fma, FTZ_MustBeOff};
1600     case Intrinsic::nvvm_fma_rn_ftz_f:
1601       return {Intrinsic::fma, FTZ_MustBeOn};
1602     case Intrinsic::nvvm_fmax_d:
1603       return {Intrinsic::maxnum, FTZ_Any};
1604     case Intrinsic::nvvm_fmax_f:
1605       return {Intrinsic::maxnum, FTZ_MustBeOff};
1606     case Intrinsic::nvvm_fmax_ftz_f:
1607       return {Intrinsic::maxnum, FTZ_MustBeOn};
1608     case Intrinsic::nvvm_fmin_d:
1609       return {Intrinsic::minnum, FTZ_Any};
1610     case Intrinsic::nvvm_fmin_f:
1611       return {Intrinsic::minnum, FTZ_MustBeOff};
1612     case Intrinsic::nvvm_fmin_ftz_f:
1613       return {Intrinsic::minnum, FTZ_MustBeOn};
1614     case Intrinsic::nvvm_round_d:
1615       return {Intrinsic::round, FTZ_Any};
1616     case Intrinsic::nvvm_round_f:
1617       return {Intrinsic::round, FTZ_MustBeOff};
1618     case Intrinsic::nvvm_round_ftz_f:
1619       return {Intrinsic::round, FTZ_MustBeOn};
1620     case Intrinsic::nvvm_sqrt_rn_d:
1621       return {Intrinsic::sqrt, FTZ_Any};
1622     case Intrinsic::nvvm_sqrt_f:
1623       // nvvm_sqrt_f is a special case.  For  most intrinsics, foo_ftz_f is the
1624       // ftz version, and foo_f is the non-ftz version.  But nvvm_sqrt_f adopts
1625       // the ftz-ness of the surrounding code.  sqrt_rn_f and sqrt_rn_ftz_f are
1626       // the versions with explicit ftz-ness.
1627       return {Intrinsic::sqrt, FTZ_Any};
1628     case Intrinsic::nvvm_sqrt_rn_f:
1629       return {Intrinsic::sqrt, FTZ_MustBeOff};
1630     case Intrinsic::nvvm_sqrt_rn_ftz_f:
1631       return {Intrinsic::sqrt, FTZ_MustBeOn};
1632     case Intrinsic::nvvm_trunc_d:
1633       return {Intrinsic::trunc, FTZ_Any};
1634     case Intrinsic::nvvm_trunc_f:
1635       return {Intrinsic::trunc, FTZ_MustBeOff};
1636     case Intrinsic::nvvm_trunc_ftz_f:
1637       return {Intrinsic::trunc, FTZ_MustBeOn};
1638 
1639     // NVVM intrinsics that map to LLVM cast operations.
1640     //
1641     // Note that llvm's target-generic conversion operators correspond to the rz
1642     // (round to zero) versions of the nvvm conversion intrinsics, even though
1643     // most everything else here uses the rn (round to nearest even) nvvm ops.
1644     case Intrinsic::nvvm_d2i_rz:
1645     case Intrinsic::nvvm_f2i_rz:
1646     case Intrinsic::nvvm_d2ll_rz:
1647     case Intrinsic::nvvm_f2ll_rz:
1648       return {Instruction::FPToSI};
1649     case Intrinsic::nvvm_d2ui_rz:
1650     case Intrinsic::nvvm_f2ui_rz:
1651     case Intrinsic::nvvm_d2ull_rz:
1652     case Intrinsic::nvvm_f2ull_rz:
1653       return {Instruction::FPToUI};
1654     case Intrinsic::nvvm_i2d_rz:
1655     case Intrinsic::nvvm_i2f_rz:
1656     case Intrinsic::nvvm_ll2d_rz:
1657     case Intrinsic::nvvm_ll2f_rz:
1658       return {Instruction::SIToFP};
1659     case Intrinsic::nvvm_ui2d_rz:
1660     case Intrinsic::nvvm_ui2f_rz:
1661     case Intrinsic::nvvm_ull2d_rz:
1662     case Intrinsic::nvvm_ull2f_rz:
1663       return {Instruction::UIToFP};
1664 
1665     // NVVM intrinsics that map to LLVM binary ops.
1666     case Intrinsic::nvvm_add_rn_d:
1667       return {Instruction::FAdd, FTZ_Any};
1668     case Intrinsic::nvvm_add_rn_f:
1669       return {Instruction::FAdd, FTZ_MustBeOff};
1670     case Intrinsic::nvvm_add_rn_ftz_f:
1671       return {Instruction::FAdd, FTZ_MustBeOn};
1672     case Intrinsic::nvvm_mul_rn_d:
1673       return {Instruction::FMul, FTZ_Any};
1674     case Intrinsic::nvvm_mul_rn_f:
1675       return {Instruction::FMul, FTZ_MustBeOff};
1676     case Intrinsic::nvvm_mul_rn_ftz_f:
1677       return {Instruction::FMul, FTZ_MustBeOn};
1678     case Intrinsic::nvvm_div_rn_d:
1679       return {Instruction::FDiv, FTZ_Any};
1680     case Intrinsic::nvvm_div_rn_f:
1681       return {Instruction::FDiv, FTZ_MustBeOff};
1682     case Intrinsic::nvvm_div_rn_ftz_f:
1683       return {Instruction::FDiv, FTZ_MustBeOn};
1684 
1685     // The remainder of cases are NVVM intrinsics that map to LLVM idioms, but
1686     // need special handling.
1687     //
1688     // We seem to be missing intrinsics for rcp.approx.{ftz.}f32, which is just
1689     // as well.
1690     case Intrinsic::nvvm_rcp_rn_d:
1691       return {SPC_Reciprocal, FTZ_Any};
1692     case Intrinsic::nvvm_rcp_rn_f:
1693       return {SPC_Reciprocal, FTZ_MustBeOff};
1694     case Intrinsic::nvvm_rcp_rn_ftz_f:
1695       return {SPC_Reciprocal, FTZ_MustBeOn};
1696 
1697     // We do not currently simplify intrinsics that give an approximate answer.
1698     // These include:
1699     //
1700     //   - nvvm_cos_approx_{f,ftz_f}
1701     //   - nvvm_ex2_approx_{d,f,ftz_f}
1702     //   - nvvm_lg2_approx_{d,f,ftz_f}
1703     //   - nvvm_sin_approx_{f,ftz_f}
1704     //   - nvvm_sqrt_approx_{f,ftz_f}
1705     //   - nvvm_rsqrt_approx_{d,f,ftz_f}
1706     //   - nvvm_div_approx_{ftz_d,ftz_f,f}
1707     //   - nvvm_rcp_approx_ftz_d
1708     //
1709     // Ideally we'd encode them as e.g. "fast call @llvm.cos", where "fast"
1710     // means that fastmath is enabled in the intrinsic.  Unfortunately only
1711     // binary operators (currently) have a fastmath bit in SelectionDAG, so this
1712     // information gets lost and we can't select on it.
1713     //
1714     // TODO: div and rcp are lowered to a binary op, so these we could in theory
1715     // lower them to "fast fdiv".
1716 
1717     default:
1718       return {};
1719     }
1720   }();
1721 
1722   // If Action.FtzRequirementTy is not satisfied by the module's ftz state, we
1723   // can bail out now.  (Notice that in the case that IID is not an NVVM
1724   // intrinsic, we don't have to look up any module metadata, as
1725   // FtzRequirementTy will be FTZ_Any.)
1726   if (Action.FtzRequirement != FTZ_Any) {
1727     bool FtzEnabled =
1728         II->getFunction()->getFnAttribute("nvptx-f32ftz").getValueAsString() ==
1729         "true";
1730 
1731     if (FtzEnabled != (Action.FtzRequirement == FTZ_MustBeOn))
1732       return nullptr;
1733   }
1734 
1735   // Simplify to target-generic intrinsic.
1736   if (Action.IID) {
1737     SmallVector<Value *, 4> Args(II->arg_operands());
1738     // All the target-generic intrinsics currently of interest to us have one
1739     // type argument, equal to that of the nvvm intrinsic's argument.
1740     Type *Tys[] = {II->getArgOperand(0)->getType()};
1741     return CallInst::Create(
1742         Intrinsic::getDeclaration(II->getModule(), *Action.IID, Tys), Args);
1743   }
1744 
1745   // Simplify to target-generic binary op.
1746   if (Action.BinaryOp)
1747     return BinaryOperator::Create(*Action.BinaryOp, II->getArgOperand(0),
1748                                   II->getArgOperand(1), II->getName());
1749 
1750   // Simplify to target-generic cast op.
1751   if (Action.CastOp)
1752     return CastInst::Create(*Action.CastOp, II->getArgOperand(0), II->getType(),
1753                             II->getName());
1754 
1755   // All that's left are the special cases.
1756   if (!Action.Special)
1757     return nullptr;
1758 
1759   switch (*Action.Special) {
1760   case SPC_Reciprocal:
1761     // Simplify reciprocal.
1762     return BinaryOperator::Create(
1763         Instruction::FDiv, ConstantFP::get(II->getArgOperand(0)->getType(), 1),
1764         II->getArgOperand(0), II->getName());
1765   }
1766   llvm_unreachable("All SpecialCase enumerators should be handled in switch.");
1767 }
1768 
1769 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1770   removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1771   return nullptr;
1772 }
1773 
1774 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1775   removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1776   return nullptr;
1777 }
1778 
1779 static Instruction *canonicalizeConstantArg0ToArg1(CallInst &Call) {
1780   assert(Call.getNumArgOperands() > 1 && "Need at least 2 args to swap");
1781   Value *Arg0 = Call.getArgOperand(0), *Arg1 = Call.getArgOperand(1);
1782   if (isa<Constant>(Arg0) && !isa<Constant>(Arg1)) {
1783     Call.setArgOperand(0, Arg1);
1784     Call.setArgOperand(1, Arg0);
1785     return &Call;
1786   }
1787   return nullptr;
1788 }
1789 
1790 /// CallInst simplification. This mostly only handles folding of intrinsic
1791 /// instructions. For normal calls, it allows visitCallSite to do the heavy
1792 /// lifting.
1793 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1794   if (Value *V = SimplifyCall(&CI, SQ.getWithInstruction(&CI)))
1795     return replaceInstUsesWith(CI, V);
1796 
1797   if (isFreeCall(&CI, &TLI))
1798     return visitFree(CI);
1799 
1800   // If the caller function is nounwind, mark the call as nounwind, even if the
1801   // callee isn't.
1802   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1803     CI.setDoesNotThrow();
1804     return &CI;
1805   }
1806 
1807   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1808   if (!II) return visitCallSite(&CI);
1809 
1810   // Intrinsics cannot occur in an invoke, so handle them here instead of in
1811   // visitCallSite.
1812   if (auto *MI = dyn_cast<AnyMemIntrinsic>(II)) {
1813     bool Changed = false;
1814 
1815     // memmove/cpy/set of zero bytes is a noop.
1816     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1817       if (NumBytes->isNullValue())
1818         return eraseInstFromFunction(CI);
1819 
1820       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1821         if (CI->getZExtValue() == 1) {
1822           // Replace the instruction with just byte operations.  We would
1823           // transform other cases to loads/stores, but we don't know if
1824           // alignment is sufficient.
1825         }
1826     }
1827 
1828     // No other transformations apply to volatile transfers.
1829     if (auto *M = dyn_cast<MemIntrinsic>(MI))
1830       if (M->isVolatile())
1831         return nullptr;
1832 
1833     // If we have a memmove and the source operation is a constant global,
1834     // then the source and dest pointers can't alias, so we can change this
1835     // into a call to memcpy.
1836     if (auto *MMI = dyn_cast<AnyMemMoveInst>(MI)) {
1837       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1838         if (GVSrc->isConstant()) {
1839           Module *M = CI.getModule();
1840           Intrinsic::ID MemCpyID =
1841               isa<AtomicMemMoveInst>(MMI)
1842                   ? Intrinsic::memcpy_element_unordered_atomic
1843                   : Intrinsic::memcpy;
1844           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1845                            CI.getArgOperand(1)->getType(),
1846                            CI.getArgOperand(2)->getType() };
1847           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1848           Changed = true;
1849         }
1850     }
1851 
1852     if (AnyMemTransferInst *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1853       // memmove(x,x,size) -> noop.
1854       if (MTI->getSource() == MTI->getDest())
1855         return eraseInstFromFunction(CI);
1856     }
1857 
1858     // If we can determine a pointer alignment that is bigger than currently
1859     // set, update the alignment.
1860     if (auto *MTI = dyn_cast<AnyMemTransferInst>(MI)) {
1861       if (Instruction *I = SimplifyAnyMemTransfer(MTI))
1862         return I;
1863     } else if (auto *MSI = dyn_cast<AnyMemSetInst>(MI)) {
1864       if (Instruction *I = SimplifyAnyMemSet(MSI))
1865         return I;
1866     }
1867 
1868     if (Changed) return II;
1869   }
1870 
1871   if (Instruction *I = SimplifyNVVMIntrinsic(II, *this))
1872     return I;
1873 
1874   auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1875                                               unsigned DemandedWidth) {
1876     APInt UndefElts(Width, 0);
1877     APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1878     return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1879   };
1880 
1881   switch (II->getIntrinsicID()) {
1882   default: break;
1883   case Intrinsic::objectsize:
1884     if (ConstantInt *N =
1885             lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
1886       return replaceInstUsesWith(CI, N);
1887     return nullptr;
1888   case Intrinsic::bswap: {
1889     Value *IIOperand = II->getArgOperand(0);
1890     Value *X = nullptr;
1891 
1892     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1893     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1894       unsigned C = X->getType()->getPrimitiveSizeInBits() -
1895         IIOperand->getType()->getPrimitiveSizeInBits();
1896       Value *CV = ConstantInt::get(X->getType(), C);
1897       Value *V = Builder.CreateLShr(X, CV);
1898       return new TruncInst(V, IIOperand->getType());
1899     }
1900     break;
1901   }
1902   case Intrinsic::masked_load:
1903     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, Builder))
1904       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1905     break;
1906   case Intrinsic::masked_store:
1907     return simplifyMaskedStore(*II, *this);
1908   case Intrinsic::masked_gather:
1909     return simplifyMaskedGather(*II, *this);
1910   case Intrinsic::masked_scatter:
1911     return simplifyMaskedScatter(*II, *this);
1912   case Intrinsic::launder_invariant_group:
1913   case Intrinsic::strip_invariant_group:
1914     if (auto *SkippedBarrier = simplifyInvariantGroupIntrinsic(*II, *this))
1915       return replaceInstUsesWith(*II, SkippedBarrier);
1916     break;
1917   case Intrinsic::powi:
1918     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1919       // 0 and 1 are handled in instsimplify
1920 
1921       // powi(x, -1) -> 1/x
1922       if (Power->isMinusOne())
1923         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
1924                                           II->getArgOperand(0));
1925       // powi(x, 2) -> x*x
1926       if (Power->equalsInt(2))
1927         return BinaryOperator::CreateFMul(II->getArgOperand(0),
1928                                           II->getArgOperand(0));
1929     }
1930     break;
1931 
1932   case Intrinsic::cttz:
1933   case Intrinsic::ctlz:
1934     if (auto *I = foldCttzCtlz(*II, *this))
1935       return I;
1936     break;
1937 
1938   case Intrinsic::ctpop:
1939     if (auto *I = foldCtpop(*II, *this))
1940       return I;
1941     break;
1942 
1943   case Intrinsic::fshl:
1944   case Intrinsic::fshr: {
1945     const APInt *SA;
1946     if (match(II->getArgOperand(2), m_APInt(SA))) {
1947       Value *Op0 = II->getArgOperand(0), *Op1 = II->getArgOperand(1);
1948       unsigned BitWidth = SA->getBitWidth();
1949       uint64_t ShiftAmt = SA->urem(BitWidth);
1950       assert(ShiftAmt != 0 && "SimplifyCall should have handled zero shift");
1951       // Normalize to funnel shift left.
1952       if (II->getIntrinsicID() == Intrinsic::fshr)
1953         ShiftAmt = BitWidth - ShiftAmt;
1954 
1955       // fshl(X, 0, C) -> shl X, C
1956       // fshl(X, undef, C) -> shl X, C
1957       if (match(Op1, m_Zero()) || match(Op1, m_Undef()))
1958         return BinaryOperator::CreateShl(
1959             Op0, ConstantInt::get(II->getType(), ShiftAmt));
1960 
1961       // fshl(0, X, C) -> lshr X, (BW-C)
1962       // fshl(undef, X, C) -> lshr X, (BW-C)
1963       if (match(Op0, m_Zero()) || match(Op0, m_Undef()))
1964         return BinaryOperator::CreateLShr(
1965             Op1, ConstantInt::get(II->getType(), BitWidth - ShiftAmt));
1966     }
1967 
1968     // The shift amount (operand 2) of a funnel shift is modulo the bitwidth,
1969     // so only the low bits of the shift amount are demanded if the bitwidth is
1970     // a power-of-2.
1971     unsigned BitWidth = II->getType()->getScalarSizeInBits();
1972     if (!isPowerOf2_32(BitWidth))
1973       break;
1974     APInt Op2Demanded = APInt::getLowBitsSet(BitWidth, Log2_32_Ceil(BitWidth));
1975     KnownBits Op2Known(BitWidth);
1976     if (SimplifyDemandedBits(II, 2, Op2Demanded, Op2Known))
1977       return &CI;
1978     break;
1979   }
1980   case Intrinsic::uadd_with_overflow:
1981   case Intrinsic::sadd_with_overflow:
1982   case Intrinsic::umul_with_overflow:
1983   case Intrinsic::smul_with_overflow:
1984     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
1985       return I;
1986     LLVM_FALLTHROUGH;
1987 
1988   case Intrinsic::usub_with_overflow:
1989   case Intrinsic::ssub_with_overflow: {
1990     OverflowCheckFlavor OCF =
1991         IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1992     assert(OCF != OCF_INVALID && "unexpected!");
1993 
1994     Value *OperationResult = nullptr;
1995     Constant *OverflowResult = nullptr;
1996     if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1997                               *II, OperationResult, OverflowResult))
1998       return CreateOverflowTuple(II, OperationResult, OverflowResult);
1999 
2000     break;
2001   }
2002 
2003   case Intrinsic::uadd_sat:
2004   case Intrinsic::sadd_sat:
2005     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2006       return I;
2007     LLVM_FALLTHROUGH;
2008   case Intrinsic::usub_sat:
2009   case Intrinsic::ssub_sat: {
2010     Value *Arg0 = II->getArgOperand(0);
2011     Value *Arg1 = II->getArgOperand(1);
2012     Intrinsic::ID IID = II->getIntrinsicID();
2013 
2014     // Make use of known overflow information.
2015     OverflowResult OR;
2016     switch (IID) {
2017     default:
2018       llvm_unreachable("Unexpected intrinsic!");
2019     case Intrinsic::uadd_sat:
2020       OR = computeOverflowForUnsignedAdd(Arg0, Arg1, II);
2021       if (OR == OverflowResult::NeverOverflows)
2022         return BinaryOperator::CreateNUWAdd(Arg0, Arg1);
2023       if (OR == OverflowResult::AlwaysOverflows)
2024         return replaceInstUsesWith(*II,
2025                                    ConstantInt::getAllOnesValue(II->getType()));
2026       break;
2027     case Intrinsic::usub_sat:
2028       OR = computeOverflowForUnsignedSub(Arg0, Arg1, II);
2029       if (OR == OverflowResult::NeverOverflows)
2030         return BinaryOperator::CreateNUWSub(Arg0, Arg1);
2031       if (OR == OverflowResult::AlwaysOverflows)
2032         return replaceInstUsesWith(*II,
2033                                    ConstantInt::getNullValue(II->getType()));
2034       break;
2035     case Intrinsic::sadd_sat:
2036       if (willNotOverflowSignedAdd(Arg0, Arg1, *II))
2037         return BinaryOperator::CreateNSWAdd(Arg0, Arg1);
2038       break;
2039     case Intrinsic::ssub_sat:
2040       if (willNotOverflowSignedSub(Arg0, Arg1, *II))
2041         return BinaryOperator::CreateNSWSub(Arg0, Arg1);
2042       break;
2043     }
2044 
2045     // ssub.sat(X, C) -> sadd.sat(X, -C) if C != MIN
2046     Constant *C;
2047     if (IID == Intrinsic::ssub_sat && match(Arg1, m_Constant(C)) &&
2048         C->isNotMinSignedValue()) {
2049       Value *NegVal = ConstantExpr::getNeg(C);
2050       return replaceInstUsesWith(
2051           *II, Builder.CreateBinaryIntrinsic(
2052               Intrinsic::sadd_sat, Arg0, NegVal));
2053     }
2054 
2055     // sat(sat(X + Val2) + Val) -> sat(X + (Val+Val2))
2056     // sat(sat(X - Val2) - Val) -> sat(X - (Val+Val2))
2057     // if Val and Val2 have the same sign
2058     if (auto *Other = dyn_cast<IntrinsicInst>(Arg0)) {
2059       Value *X;
2060       const APInt *Val, *Val2;
2061       APInt NewVal;
2062       bool IsUnsigned =
2063           IID == Intrinsic::uadd_sat || IID == Intrinsic::usub_sat;
2064       if (Other->getIntrinsicID() == II->getIntrinsicID() &&
2065           match(Arg1, m_APInt(Val)) &&
2066           match(Other->getArgOperand(0), m_Value(X)) &&
2067           match(Other->getArgOperand(1), m_APInt(Val2))) {
2068         if (IsUnsigned)
2069           NewVal = Val->uadd_sat(*Val2);
2070         else if (Val->isNonNegative() == Val2->isNonNegative()) {
2071           bool Overflow;
2072           NewVal = Val->sadd_ov(*Val2, Overflow);
2073           if (Overflow) {
2074             // Both adds together may add more than SignedMaxValue
2075             // without saturating the final result.
2076             break;
2077           }
2078         } else {
2079           // Cannot fold saturated addition with different signs.
2080           break;
2081         }
2082 
2083         return replaceInstUsesWith(
2084             *II, Builder.CreateBinaryIntrinsic(
2085                      IID, X, ConstantInt::get(II->getType(), NewVal)));
2086       }
2087     }
2088     break;
2089   }
2090 
2091   case Intrinsic::minnum:
2092   case Intrinsic::maxnum:
2093   case Intrinsic::minimum:
2094   case Intrinsic::maximum: {
2095     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2096       return I;
2097     Value *Arg0 = II->getArgOperand(0);
2098     Value *Arg1 = II->getArgOperand(1);
2099     Intrinsic::ID IID = II->getIntrinsicID();
2100     Value *X, *Y;
2101     if (match(Arg0, m_FNeg(m_Value(X))) && match(Arg1, m_FNeg(m_Value(Y))) &&
2102         (Arg0->hasOneUse() || Arg1->hasOneUse())) {
2103       // If both operands are negated, invert the call and negate the result:
2104       // min(-X, -Y) --> -(max(X, Y))
2105       // max(-X, -Y) --> -(min(X, Y))
2106       Intrinsic::ID NewIID;
2107       switch (IID) {
2108       case Intrinsic::maxnum:
2109         NewIID = Intrinsic::minnum;
2110         break;
2111       case Intrinsic::minnum:
2112         NewIID = Intrinsic::maxnum;
2113         break;
2114       case Intrinsic::maximum:
2115         NewIID = Intrinsic::minimum;
2116         break;
2117       case Intrinsic::minimum:
2118         NewIID = Intrinsic::maximum;
2119         break;
2120       default:
2121         llvm_unreachable("unexpected intrinsic ID");
2122       }
2123       Value *NewCall = Builder.CreateBinaryIntrinsic(NewIID, X, Y, II);
2124       Instruction *FNeg = BinaryOperator::CreateFNeg(NewCall);
2125       FNeg->copyIRFlags(II);
2126       return FNeg;
2127     }
2128 
2129     // m(m(X, C2), C1) -> m(X, C)
2130     const APFloat *C1, *C2;
2131     if (auto *M = dyn_cast<IntrinsicInst>(Arg0)) {
2132       if (M->getIntrinsicID() == IID && match(Arg1, m_APFloat(C1)) &&
2133           ((match(M->getArgOperand(0), m_Value(X)) &&
2134             match(M->getArgOperand(1), m_APFloat(C2))) ||
2135            (match(M->getArgOperand(1), m_Value(X)) &&
2136             match(M->getArgOperand(0), m_APFloat(C2))))) {
2137         APFloat Res(0.0);
2138         switch (IID) {
2139         case Intrinsic::maxnum:
2140           Res = maxnum(*C1, *C2);
2141           break;
2142         case Intrinsic::minnum:
2143           Res = minnum(*C1, *C2);
2144           break;
2145         case Intrinsic::maximum:
2146           Res = maximum(*C1, *C2);
2147           break;
2148         case Intrinsic::minimum:
2149           Res = minimum(*C1, *C2);
2150           break;
2151         default:
2152           llvm_unreachable("unexpected intrinsic ID");
2153         }
2154         Instruction *NewCall = Builder.CreateBinaryIntrinsic(
2155             IID, X, ConstantFP::get(Arg0->getType(), Res));
2156         NewCall->copyIRFlags(II);
2157         return replaceInstUsesWith(*II, NewCall);
2158       }
2159     }
2160 
2161     break;
2162   }
2163   case Intrinsic::fmuladd: {
2164     // Canonicalize fast fmuladd to the separate fmul + fadd.
2165     if (II->isFast()) {
2166       BuilderTy::FastMathFlagGuard Guard(Builder);
2167       Builder.setFastMathFlags(II->getFastMathFlags());
2168       Value *Mul = Builder.CreateFMul(II->getArgOperand(0),
2169                                       II->getArgOperand(1));
2170       Value *Add = Builder.CreateFAdd(Mul, II->getArgOperand(2));
2171       Add->takeName(II);
2172       return replaceInstUsesWith(*II, Add);
2173     }
2174 
2175     LLVM_FALLTHROUGH;
2176   }
2177   case Intrinsic::fma: {
2178     if (Instruction *I = canonicalizeConstantArg0ToArg1(CI))
2179       return I;
2180 
2181     // fma fneg(x), fneg(y), z -> fma x, y, z
2182     Value *Src0 = II->getArgOperand(0);
2183     Value *Src1 = II->getArgOperand(1);
2184     Value *X, *Y;
2185     if (match(Src0, m_FNeg(m_Value(X))) && match(Src1, m_FNeg(m_Value(Y)))) {
2186       II->setArgOperand(0, X);
2187       II->setArgOperand(1, Y);
2188       return II;
2189     }
2190 
2191     // fma fabs(x), fabs(x), z -> fma x, x, z
2192     if (match(Src0, m_FAbs(m_Value(X))) &&
2193         match(Src1, m_FAbs(m_Specific(X)))) {
2194       II->setArgOperand(0, X);
2195       II->setArgOperand(1, X);
2196       return II;
2197     }
2198 
2199     // fma x, 1, z -> fadd x, z
2200     if (match(Src1, m_FPOne())) {
2201       auto *FAdd = BinaryOperator::CreateFAdd(Src0, II->getArgOperand(2));
2202       FAdd->copyFastMathFlags(II);
2203       return FAdd;
2204     }
2205 
2206     break;
2207   }
2208   case Intrinsic::fabs: {
2209     Value *Cond;
2210     Constant *LHS, *RHS;
2211     if (match(II->getArgOperand(0),
2212               m_Select(m_Value(Cond), m_Constant(LHS), m_Constant(RHS)))) {
2213       CallInst *Call0 = Builder.CreateCall(II->getCalledFunction(), {LHS});
2214       CallInst *Call1 = Builder.CreateCall(II->getCalledFunction(), {RHS});
2215       return SelectInst::Create(Cond, Call0, Call1);
2216     }
2217 
2218     LLVM_FALLTHROUGH;
2219   }
2220   case Intrinsic::ceil:
2221   case Intrinsic::floor:
2222   case Intrinsic::round:
2223   case Intrinsic::nearbyint:
2224   case Intrinsic::rint:
2225   case Intrinsic::trunc: {
2226     Value *ExtSrc;
2227     if (match(II->getArgOperand(0), m_OneUse(m_FPExt(m_Value(ExtSrc))))) {
2228       // Narrow the call: intrinsic (fpext x) -> fpext (intrinsic x)
2229       Value *NarrowII =
2230           Builder.CreateUnaryIntrinsic(II->getIntrinsicID(), ExtSrc, II);
2231       return new FPExtInst(NarrowII, II->getType());
2232     }
2233     break;
2234   }
2235   case Intrinsic::cos:
2236   case Intrinsic::amdgcn_cos: {
2237     Value *X;
2238     Value *Src = II->getArgOperand(0);
2239     if (match(Src, m_FNeg(m_Value(X))) || match(Src, m_FAbs(m_Value(X)))) {
2240       // cos(-x) -> cos(x)
2241       // cos(fabs(x)) -> cos(x)
2242       II->setArgOperand(0, X);
2243       return II;
2244     }
2245     break;
2246   }
2247   case Intrinsic::sin: {
2248     Value *X;
2249     if (match(II->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X))))) {
2250       // sin(-x) --> -sin(x)
2251       Value *NewSin = Builder.CreateUnaryIntrinsic(Intrinsic::sin, X, II);
2252       Instruction *FNeg = BinaryOperator::CreateFNeg(NewSin);
2253       FNeg->copyFastMathFlags(II);
2254       return FNeg;
2255     }
2256     break;
2257   }
2258   case Intrinsic::ppc_altivec_lvx:
2259   case Intrinsic::ppc_altivec_lvxl:
2260     // Turn PPC lvx -> load if the pointer is known aligned.
2261     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2262                                    &DT) >= 16) {
2263       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2264                                          PointerType::getUnqual(II->getType()));
2265       return new LoadInst(Ptr);
2266     }
2267     break;
2268   case Intrinsic::ppc_vsx_lxvw4x:
2269   case Intrinsic::ppc_vsx_lxvd2x: {
2270     // Turn PPC VSX loads into normal loads.
2271     Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2272                                        PointerType::getUnqual(II->getType()));
2273     return new LoadInst(Ptr, Twine(""), false, 1);
2274   }
2275   case Intrinsic::ppc_altivec_stvx:
2276   case Intrinsic::ppc_altivec_stvxl:
2277     // Turn stvx -> store if the pointer is known aligned.
2278     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2279                                    &DT) >= 16) {
2280       Type *OpPtrTy =
2281         PointerType::getUnqual(II->getArgOperand(0)->getType());
2282       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2283       return new StoreInst(II->getArgOperand(0), Ptr);
2284     }
2285     break;
2286   case Intrinsic::ppc_vsx_stxvw4x:
2287   case Intrinsic::ppc_vsx_stxvd2x: {
2288     // Turn PPC VSX stores into normal stores.
2289     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
2290     Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2291     return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
2292   }
2293   case Intrinsic::ppc_qpx_qvlfs:
2294     // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
2295     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
2296                                    &DT) >= 16) {
2297       Type *VTy = VectorType::get(Builder.getFloatTy(),
2298                                   II->getType()->getVectorNumElements());
2299       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2300                                          PointerType::getUnqual(VTy));
2301       Value *Load = Builder.CreateLoad(Ptr);
2302       return new FPExtInst(Load, II->getType());
2303     }
2304     break;
2305   case Intrinsic::ppc_qpx_qvlfd:
2306     // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
2307     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
2308                                    &DT) >= 32) {
2309       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(0),
2310                                          PointerType::getUnqual(II->getType()));
2311       return new LoadInst(Ptr);
2312     }
2313     break;
2314   case Intrinsic::ppc_qpx_qvstfs:
2315     // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
2316     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
2317                                    &DT) >= 16) {
2318       Type *VTy = VectorType::get(Builder.getFloatTy(),
2319           II->getArgOperand(0)->getType()->getVectorNumElements());
2320       Value *TOp = Builder.CreateFPTrunc(II->getArgOperand(0), VTy);
2321       Type *OpPtrTy = PointerType::getUnqual(VTy);
2322       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2323       return new StoreInst(TOp, Ptr);
2324     }
2325     break;
2326   case Intrinsic::ppc_qpx_qvstfd:
2327     // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
2328     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
2329                                    &DT) >= 32) {
2330       Type *OpPtrTy =
2331         PointerType::getUnqual(II->getArgOperand(0)->getType());
2332       Value *Ptr = Builder.CreateBitCast(II->getArgOperand(1), OpPtrTy);
2333       return new StoreInst(II->getArgOperand(0), Ptr);
2334     }
2335     break;
2336 
2337   case Intrinsic::x86_bmi_bextr_32:
2338   case Intrinsic::x86_bmi_bextr_64:
2339   case Intrinsic::x86_tbm_bextri_u32:
2340   case Intrinsic::x86_tbm_bextri_u64:
2341     // If the RHS is a constant we can try some simplifications.
2342     if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2343       uint64_t Shift = C->getZExtValue();
2344       uint64_t Length = (Shift >> 8) & 0xff;
2345       Shift &= 0xff;
2346       unsigned BitWidth = II->getType()->getIntegerBitWidth();
2347       // If the length is 0 or the shift is out of range, replace with zero.
2348       if (Length == 0 || Shift >= BitWidth)
2349         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2350       // If the LHS is also a constant, we can completely constant fold this.
2351       if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2352         uint64_t Result = InC->getZExtValue() >> Shift;
2353         if (Length > BitWidth)
2354           Length = BitWidth;
2355         Result &= maskTrailingOnes<uint64_t>(Length);
2356         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2357       }
2358       // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
2359       // are only masking bits that a shift already cleared?
2360     }
2361     break;
2362 
2363   case Intrinsic::x86_bmi_bzhi_32:
2364   case Intrinsic::x86_bmi_bzhi_64:
2365     // If the RHS is a constant we can try some simplifications.
2366     if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
2367       uint64_t Index = C->getZExtValue() & 0xff;
2368       unsigned BitWidth = II->getType()->getIntegerBitWidth();
2369       if (Index >= BitWidth)
2370         return replaceInstUsesWith(CI, II->getArgOperand(0));
2371       if (Index == 0)
2372         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), 0));
2373       // If the LHS is also a constant, we can completely constant fold this.
2374       if (auto *InC = dyn_cast<ConstantInt>(II->getArgOperand(0))) {
2375         uint64_t Result = InC->getZExtValue();
2376         Result &= maskTrailingOnes<uint64_t>(Index);
2377         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Result));
2378       }
2379       // TODO should we convert this to an AND if the RHS is constant?
2380     }
2381     break;
2382 
2383   case Intrinsic::x86_vcvtph2ps_128:
2384   case Intrinsic::x86_vcvtph2ps_256: {
2385     auto Arg = II->getArgOperand(0);
2386     auto ArgType = cast<VectorType>(Arg->getType());
2387     auto RetType = cast<VectorType>(II->getType());
2388     unsigned ArgWidth = ArgType->getNumElements();
2389     unsigned RetWidth = RetType->getNumElements();
2390     assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
2391     assert(ArgType->isIntOrIntVectorTy() &&
2392            ArgType->getScalarSizeInBits() == 16 &&
2393            "CVTPH2PS input type should be 16-bit integer vector");
2394     assert(RetType->getScalarType()->isFloatTy() &&
2395            "CVTPH2PS output type should be 32-bit float vector");
2396 
2397     // Constant folding: Convert to generic half to single conversion.
2398     if (isa<ConstantAggregateZero>(Arg))
2399       return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
2400 
2401     if (isa<ConstantDataVector>(Arg)) {
2402       auto VectorHalfAsShorts = Arg;
2403       if (RetWidth < ArgWidth) {
2404         SmallVector<uint32_t, 8> SubVecMask;
2405         for (unsigned i = 0; i != RetWidth; ++i)
2406           SubVecMask.push_back((int)i);
2407         VectorHalfAsShorts = Builder.CreateShuffleVector(
2408             Arg, UndefValue::get(ArgType), SubVecMask);
2409       }
2410 
2411       auto VectorHalfType =
2412           VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
2413       auto VectorHalfs =
2414           Builder.CreateBitCast(VectorHalfAsShorts, VectorHalfType);
2415       auto VectorFloats = Builder.CreateFPExt(VectorHalfs, RetType);
2416       return replaceInstUsesWith(*II, VectorFloats);
2417     }
2418 
2419     // We only use the lowest lanes of the argument.
2420     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
2421       II->setArgOperand(0, V);
2422       return II;
2423     }
2424     break;
2425   }
2426 
2427   case Intrinsic::x86_sse_cvtss2si:
2428   case Intrinsic::x86_sse_cvtss2si64:
2429   case Intrinsic::x86_sse_cvttss2si:
2430   case Intrinsic::x86_sse_cvttss2si64:
2431   case Intrinsic::x86_sse2_cvtsd2si:
2432   case Intrinsic::x86_sse2_cvtsd2si64:
2433   case Intrinsic::x86_sse2_cvttsd2si:
2434   case Intrinsic::x86_sse2_cvttsd2si64:
2435   case Intrinsic::x86_avx512_vcvtss2si32:
2436   case Intrinsic::x86_avx512_vcvtss2si64:
2437   case Intrinsic::x86_avx512_vcvtss2usi32:
2438   case Intrinsic::x86_avx512_vcvtss2usi64:
2439   case Intrinsic::x86_avx512_vcvtsd2si32:
2440   case Intrinsic::x86_avx512_vcvtsd2si64:
2441   case Intrinsic::x86_avx512_vcvtsd2usi32:
2442   case Intrinsic::x86_avx512_vcvtsd2usi64:
2443   case Intrinsic::x86_avx512_cvttss2si:
2444   case Intrinsic::x86_avx512_cvttss2si64:
2445   case Intrinsic::x86_avx512_cvttss2usi:
2446   case Intrinsic::x86_avx512_cvttss2usi64:
2447   case Intrinsic::x86_avx512_cvttsd2si:
2448   case Intrinsic::x86_avx512_cvttsd2si64:
2449   case Intrinsic::x86_avx512_cvttsd2usi:
2450   case Intrinsic::x86_avx512_cvttsd2usi64: {
2451     // These intrinsics only demand the 0th element of their input vectors. If
2452     // we can simplify the input based on that, do so now.
2453     Value *Arg = II->getArgOperand(0);
2454     unsigned VWidth = Arg->getType()->getVectorNumElements();
2455     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
2456       II->setArgOperand(0, V);
2457       return II;
2458     }
2459     break;
2460   }
2461 
2462   case Intrinsic::x86_sse41_round_ps:
2463   case Intrinsic::x86_sse41_round_pd:
2464   case Intrinsic::x86_avx_round_ps_256:
2465   case Intrinsic::x86_avx_round_pd_256:
2466   case Intrinsic::x86_avx512_mask_rndscale_ps_128:
2467   case Intrinsic::x86_avx512_mask_rndscale_ps_256:
2468   case Intrinsic::x86_avx512_mask_rndscale_ps_512:
2469   case Intrinsic::x86_avx512_mask_rndscale_pd_128:
2470   case Intrinsic::x86_avx512_mask_rndscale_pd_256:
2471   case Intrinsic::x86_avx512_mask_rndscale_pd_512:
2472   case Intrinsic::x86_avx512_mask_rndscale_ss:
2473   case Intrinsic::x86_avx512_mask_rndscale_sd:
2474     if (Value *V = simplifyX86round(*II, Builder))
2475       return replaceInstUsesWith(*II, V);
2476     break;
2477 
2478   case Intrinsic::x86_mmx_pmovmskb:
2479   case Intrinsic::x86_sse_movmsk_ps:
2480   case Intrinsic::x86_sse2_movmsk_pd:
2481   case Intrinsic::x86_sse2_pmovmskb_128:
2482   case Intrinsic::x86_avx_movmsk_pd_256:
2483   case Intrinsic::x86_avx_movmsk_ps_256:
2484   case Intrinsic::x86_avx2_pmovmskb:
2485     if (Value *V = simplifyX86movmsk(*II, Builder))
2486       return replaceInstUsesWith(*II, V);
2487     break;
2488 
2489   case Intrinsic::x86_sse_comieq_ss:
2490   case Intrinsic::x86_sse_comige_ss:
2491   case Intrinsic::x86_sse_comigt_ss:
2492   case Intrinsic::x86_sse_comile_ss:
2493   case Intrinsic::x86_sse_comilt_ss:
2494   case Intrinsic::x86_sse_comineq_ss:
2495   case Intrinsic::x86_sse_ucomieq_ss:
2496   case Intrinsic::x86_sse_ucomige_ss:
2497   case Intrinsic::x86_sse_ucomigt_ss:
2498   case Intrinsic::x86_sse_ucomile_ss:
2499   case Intrinsic::x86_sse_ucomilt_ss:
2500   case Intrinsic::x86_sse_ucomineq_ss:
2501   case Intrinsic::x86_sse2_comieq_sd:
2502   case Intrinsic::x86_sse2_comige_sd:
2503   case Intrinsic::x86_sse2_comigt_sd:
2504   case Intrinsic::x86_sse2_comile_sd:
2505   case Intrinsic::x86_sse2_comilt_sd:
2506   case Intrinsic::x86_sse2_comineq_sd:
2507   case Intrinsic::x86_sse2_ucomieq_sd:
2508   case Intrinsic::x86_sse2_ucomige_sd:
2509   case Intrinsic::x86_sse2_ucomigt_sd:
2510   case Intrinsic::x86_sse2_ucomile_sd:
2511   case Intrinsic::x86_sse2_ucomilt_sd:
2512   case Intrinsic::x86_sse2_ucomineq_sd:
2513   case Intrinsic::x86_avx512_vcomi_ss:
2514   case Intrinsic::x86_avx512_vcomi_sd:
2515   case Intrinsic::x86_avx512_mask_cmp_ss:
2516   case Intrinsic::x86_avx512_mask_cmp_sd: {
2517     // These intrinsics only demand the 0th element of their input vectors. If
2518     // we can simplify the input based on that, do so now.
2519     bool MadeChange = false;
2520     Value *Arg0 = II->getArgOperand(0);
2521     Value *Arg1 = II->getArgOperand(1);
2522     unsigned VWidth = Arg0->getType()->getVectorNumElements();
2523     if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
2524       II->setArgOperand(0, V);
2525       MadeChange = true;
2526     }
2527     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
2528       II->setArgOperand(1, V);
2529       MadeChange = true;
2530     }
2531     if (MadeChange)
2532       return II;
2533     break;
2534   }
2535   case Intrinsic::x86_avx512_cmp_pd_128:
2536   case Intrinsic::x86_avx512_cmp_pd_256:
2537   case Intrinsic::x86_avx512_cmp_pd_512:
2538   case Intrinsic::x86_avx512_cmp_ps_128:
2539   case Intrinsic::x86_avx512_cmp_ps_256:
2540   case Intrinsic::x86_avx512_cmp_ps_512: {
2541     // Folding cmp(sub(a,b),0) -> cmp(a,b) and cmp(0,sub(a,b)) -> cmp(b,a)
2542     Value *Arg0 = II->getArgOperand(0);
2543     Value *Arg1 = II->getArgOperand(1);
2544     bool Arg0IsZero = match(Arg0, m_PosZeroFP());
2545     if (Arg0IsZero)
2546       std::swap(Arg0, Arg1);
2547     Value *A, *B;
2548     // This fold requires only the NINF(not +/- inf) since inf minus
2549     // inf is nan.
2550     // NSZ(No Signed Zeros) is not needed because zeros of any sign are
2551     // equal for both compares.
2552     // NNAN is not needed because nans compare the same for both compares.
2553     // The compare intrinsic uses the above assumptions and therefore
2554     // doesn't require additional flags.
2555     if ((match(Arg0, m_OneUse(m_FSub(m_Value(A), m_Value(B)))) &&
2556          match(Arg1, m_PosZeroFP()) && isa<Instruction>(Arg0) &&
2557          cast<Instruction>(Arg0)->getFastMathFlags().noInfs())) {
2558       if (Arg0IsZero)
2559         std::swap(A, B);
2560       II->setArgOperand(0, A);
2561       II->setArgOperand(1, B);
2562       return II;
2563     }
2564     break;
2565   }
2566 
2567   case Intrinsic::x86_avx512_add_ps_512:
2568   case Intrinsic::x86_avx512_div_ps_512:
2569   case Intrinsic::x86_avx512_mul_ps_512:
2570   case Intrinsic::x86_avx512_sub_ps_512:
2571   case Intrinsic::x86_avx512_add_pd_512:
2572   case Intrinsic::x86_avx512_div_pd_512:
2573   case Intrinsic::x86_avx512_mul_pd_512:
2574   case Intrinsic::x86_avx512_sub_pd_512:
2575     // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2576     // IR operations.
2577     if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2578       if (R->getValue() == 4) {
2579         Value *Arg0 = II->getArgOperand(0);
2580         Value *Arg1 = II->getArgOperand(1);
2581 
2582         Value *V;
2583         switch (II->getIntrinsicID()) {
2584         default: llvm_unreachable("Case stmts out of sync!");
2585         case Intrinsic::x86_avx512_add_ps_512:
2586         case Intrinsic::x86_avx512_add_pd_512:
2587           V = Builder.CreateFAdd(Arg0, Arg1);
2588           break;
2589         case Intrinsic::x86_avx512_sub_ps_512:
2590         case Intrinsic::x86_avx512_sub_pd_512:
2591           V = Builder.CreateFSub(Arg0, Arg1);
2592           break;
2593         case Intrinsic::x86_avx512_mul_ps_512:
2594         case Intrinsic::x86_avx512_mul_pd_512:
2595           V = Builder.CreateFMul(Arg0, Arg1);
2596           break;
2597         case Intrinsic::x86_avx512_div_ps_512:
2598         case Intrinsic::x86_avx512_div_pd_512:
2599           V = Builder.CreateFDiv(Arg0, Arg1);
2600           break;
2601         }
2602 
2603         return replaceInstUsesWith(*II, V);
2604       }
2605     }
2606     break;
2607 
2608   case Intrinsic::x86_avx512_mask_add_ss_round:
2609   case Intrinsic::x86_avx512_mask_div_ss_round:
2610   case Intrinsic::x86_avx512_mask_mul_ss_round:
2611   case Intrinsic::x86_avx512_mask_sub_ss_round:
2612   case Intrinsic::x86_avx512_mask_add_sd_round:
2613   case Intrinsic::x86_avx512_mask_div_sd_round:
2614   case Intrinsic::x86_avx512_mask_mul_sd_round:
2615   case Intrinsic::x86_avx512_mask_sub_sd_round:
2616     // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
2617     // IR operations.
2618     if (auto *R = dyn_cast<ConstantInt>(II->getArgOperand(4))) {
2619       if (R->getValue() == 4) {
2620         // Extract the element as scalars.
2621         Value *Arg0 = II->getArgOperand(0);
2622         Value *Arg1 = II->getArgOperand(1);
2623         Value *LHS = Builder.CreateExtractElement(Arg0, (uint64_t)0);
2624         Value *RHS = Builder.CreateExtractElement(Arg1, (uint64_t)0);
2625 
2626         Value *V;
2627         switch (II->getIntrinsicID()) {
2628         default: llvm_unreachable("Case stmts out of sync!");
2629         case Intrinsic::x86_avx512_mask_add_ss_round:
2630         case Intrinsic::x86_avx512_mask_add_sd_round:
2631           V = Builder.CreateFAdd(LHS, RHS);
2632           break;
2633         case Intrinsic::x86_avx512_mask_sub_ss_round:
2634         case Intrinsic::x86_avx512_mask_sub_sd_round:
2635           V = Builder.CreateFSub(LHS, RHS);
2636           break;
2637         case Intrinsic::x86_avx512_mask_mul_ss_round:
2638         case Intrinsic::x86_avx512_mask_mul_sd_round:
2639           V = Builder.CreateFMul(LHS, RHS);
2640           break;
2641         case Intrinsic::x86_avx512_mask_div_ss_round:
2642         case Intrinsic::x86_avx512_mask_div_sd_round:
2643           V = Builder.CreateFDiv(LHS, RHS);
2644           break;
2645         }
2646 
2647         // Handle the masking aspect of the intrinsic.
2648         Value *Mask = II->getArgOperand(3);
2649         auto *C = dyn_cast<ConstantInt>(Mask);
2650         // We don't need a select if we know the mask bit is a 1.
2651         if (!C || !C->getValue()[0]) {
2652           // Cast the mask to an i1 vector and then extract the lowest element.
2653           auto *MaskTy = VectorType::get(Builder.getInt1Ty(),
2654                              cast<IntegerType>(Mask->getType())->getBitWidth());
2655           Mask = Builder.CreateBitCast(Mask, MaskTy);
2656           Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
2657           // Extract the lowest element from the passthru operand.
2658           Value *Passthru = Builder.CreateExtractElement(II->getArgOperand(2),
2659                                                           (uint64_t)0);
2660           V = Builder.CreateSelect(Mask, V, Passthru);
2661         }
2662 
2663         // Insert the result back into the original argument 0.
2664         V = Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
2665 
2666         return replaceInstUsesWith(*II, V);
2667       }
2668     }
2669     LLVM_FALLTHROUGH;
2670 
2671   // X86 scalar intrinsics simplified with SimplifyDemandedVectorElts.
2672   case Intrinsic::x86_avx512_mask_max_ss_round:
2673   case Intrinsic::x86_avx512_mask_min_ss_round:
2674   case Intrinsic::x86_avx512_mask_max_sd_round:
2675   case Intrinsic::x86_avx512_mask_min_sd_round:
2676   case Intrinsic::x86_sse_cmp_ss:
2677   case Intrinsic::x86_sse_min_ss:
2678   case Intrinsic::x86_sse_max_ss:
2679   case Intrinsic::x86_sse2_cmp_sd:
2680   case Intrinsic::x86_sse2_min_sd:
2681   case Intrinsic::x86_sse2_max_sd:
2682   case Intrinsic::x86_xop_vfrcz_ss:
2683   case Intrinsic::x86_xop_vfrcz_sd: {
2684    unsigned VWidth = II->getType()->getVectorNumElements();
2685    APInt UndefElts(VWidth, 0);
2686    APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2687    if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2688      if (V != II)
2689        return replaceInstUsesWith(*II, V);
2690      return II;
2691    }
2692    break;
2693   }
2694   case Intrinsic::x86_sse41_round_ss:
2695   case Intrinsic::x86_sse41_round_sd: {
2696     unsigned VWidth = II->getType()->getVectorNumElements();
2697     APInt UndefElts(VWidth, 0);
2698     APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
2699     if (Value *V = SimplifyDemandedVectorElts(II, AllOnesEltMask, UndefElts)) {
2700       if (V != II)
2701         return replaceInstUsesWith(*II, V);
2702       return II;
2703     } else if (Value *V = simplifyX86round(*II, Builder))
2704       return replaceInstUsesWith(*II, V);
2705     break;
2706   }
2707 
2708   // Constant fold ashr( <A x Bi>, Ci ).
2709   // Constant fold lshr( <A x Bi>, Ci ).
2710   // Constant fold shl( <A x Bi>, Ci ).
2711   case Intrinsic::x86_sse2_psrai_d:
2712   case Intrinsic::x86_sse2_psrai_w:
2713   case Intrinsic::x86_avx2_psrai_d:
2714   case Intrinsic::x86_avx2_psrai_w:
2715   case Intrinsic::x86_avx512_psrai_q_128:
2716   case Intrinsic::x86_avx512_psrai_q_256:
2717   case Intrinsic::x86_avx512_psrai_d_512:
2718   case Intrinsic::x86_avx512_psrai_q_512:
2719   case Intrinsic::x86_avx512_psrai_w_512:
2720   case Intrinsic::x86_sse2_psrli_d:
2721   case Intrinsic::x86_sse2_psrli_q:
2722   case Intrinsic::x86_sse2_psrli_w:
2723   case Intrinsic::x86_avx2_psrli_d:
2724   case Intrinsic::x86_avx2_psrli_q:
2725   case Intrinsic::x86_avx2_psrli_w:
2726   case Intrinsic::x86_avx512_psrli_d_512:
2727   case Intrinsic::x86_avx512_psrli_q_512:
2728   case Intrinsic::x86_avx512_psrli_w_512:
2729   case Intrinsic::x86_sse2_pslli_d:
2730   case Intrinsic::x86_sse2_pslli_q:
2731   case Intrinsic::x86_sse2_pslli_w:
2732   case Intrinsic::x86_avx2_pslli_d:
2733   case Intrinsic::x86_avx2_pslli_q:
2734   case Intrinsic::x86_avx2_pslli_w:
2735   case Intrinsic::x86_avx512_pslli_d_512:
2736   case Intrinsic::x86_avx512_pslli_q_512:
2737   case Intrinsic::x86_avx512_pslli_w_512:
2738     if (Value *V = simplifyX86immShift(*II, Builder))
2739       return replaceInstUsesWith(*II, V);
2740     break;
2741 
2742   case Intrinsic::x86_sse2_psra_d:
2743   case Intrinsic::x86_sse2_psra_w:
2744   case Intrinsic::x86_avx2_psra_d:
2745   case Intrinsic::x86_avx2_psra_w:
2746   case Intrinsic::x86_avx512_psra_q_128:
2747   case Intrinsic::x86_avx512_psra_q_256:
2748   case Intrinsic::x86_avx512_psra_d_512:
2749   case Intrinsic::x86_avx512_psra_q_512:
2750   case Intrinsic::x86_avx512_psra_w_512:
2751   case Intrinsic::x86_sse2_psrl_d:
2752   case Intrinsic::x86_sse2_psrl_q:
2753   case Intrinsic::x86_sse2_psrl_w:
2754   case Intrinsic::x86_avx2_psrl_d:
2755   case Intrinsic::x86_avx2_psrl_q:
2756   case Intrinsic::x86_avx2_psrl_w:
2757   case Intrinsic::x86_avx512_psrl_d_512:
2758   case Intrinsic::x86_avx512_psrl_q_512:
2759   case Intrinsic::x86_avx512_psrl_w_512:
2760   case Intrinsic::x86_sse2_psll_d:
2761   case Intrinsic::x86_sse2_psll_q:
2762   case Intrinsic::x86_sse2_psll_w:
2763   case Intrinsic::x86_avx2_psll_d:
2764   case Intrinsic::x86_avx2_psll_q:
2765   case Intrinsic::x86_avx2_psll_w:
2766   case Intrinsic::x86_avx512_psll_d_512:
2767   case Intrinsic::x86_avx512_psll_q_512:
2768   case Intrinsic::x86_avx512_psll_w_512: {
2769     if (Value *V = simplifyX86immShift(*II, Builder))
2770       return replaceInstUsesWith(*II, V);
2771 
2772     // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
2773     // operand to compute the shift amount.
2774     Value *Arg1 = II->getArgOperand(1);
2775     assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
2776            "Unexpected packed shift size");
2777     unsigned VWidth = Arg1->getType()->getVectorNumElements();
2778 
2779     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
2780       II->setArgOperand(1, V);
2781       return II;
2782     }
2783     break;
2784   }
2785 
2786   case Intrinsic::x86_avx2_psllv_d:
2787   case Intrinsic::x86_avx2_psllv_d_256:
2788   case Intrinsic::x86_avx2_psllv_q:
2789   case Intrinsic::x86_avx2_psllv_q_256:
2790   case Intrinsic::x86_avx512_psllv_d_512:
2791   case Intrinsic::x86_avx512_psllv_q_512:
2792   case Intrinsic::x86_avx512_psllv_w_128:
2793   case Intrinsic::x86_avx512_psllv_w_256:
2794   case Intrinsic::x86_avx512_psllv_w_512:
2795   case Intrinsic::x86_avx2_psrav_d:
2796   case Intrinsic::x86_avx2_psrav_d_256:
2797   case Intrinsic::x86_avx512_psrav_q_128:
2798   case Intrinsic::x86_avx512_psrav_q_256:
2799   case Intrinsic::x86_avx512_psrav_d_512:
2800   case Intrinsic::x86_avx512_psrav_q_512:
2801   case Intrinsic::x86_avx512_psrav_w_128:
2802   case Intrinsic::x86_avx512_psrav_w_256:
2803   case Intrinsic::x86_avx512_psrav_w_512:
2804   case Intrinsic::x86_avx2_psrlv_d:
2805   case Intrinsic::x86_avx2_psrlv_d_256:
2806   case Intrinsic::x86_avx2_psrlv_q:
2807   case Intrinsic::x86_avx2_psrlv_q_256:
2808   case Intrinsic::x86_avx512_psrlv_d_512:
2809   case Intrinsic::x86_avx512_psrlv_q_512:
2810   case Intrinsic::x86_avx512_psrlv_w_128:
2811   case Intrinsic::x86_avx512_psrlv_w_256:
2812   case Intrinsic::x86_avx512_psrlv_w_512:
2813     if (Value *V = simplifyX86varShift(*II, Builder))
2814       return replaceInstUsesWith(*II, V);
2815     break;
2816 
2817   case Intrinsic::x86_sse2_packssdw_128:
2818   case Intrinsic::x86_sse2_packsswb_128:
2819   case Intrinsic::x86_avx2_packssdw:
2820   case Intrinsic::x86_avx2_packsswb:
2821   case Intrinsic::x86_avx512_packssdw_512:
2822   case Intrinsic::x86_avx512_packsswb_512:
2823     if (Value *V = simplifyX86pack(*II, true))
2824       return replaceInstUsesWith(*II, V);
2825     break;
2826 
2827   case Intrinsic::x86_sse2_packuswb_128:
2828   case Intrinsic::x86_sse41_packusdw:
2829   case Intrinsic::x86_avx2_packusdw:
2830   case Intrinsic::x86_avx2_packuswb:
2831   case Intrinsic::x86_avx512_packusdw_512:
2832   case Intrinsic::x86_avx512_packuswb_512:
2833     if (Value *V = simplifyX86pack(*II, false))
2834       return replaceInstUsesWith(*II, V);
2835     break;
2836 
2837   case Intrinsic::x86_pclmulqdq:
2838   case Intrinsic::x86_pclmulqdq_256:
2839   case Intrinsic::x86_pclmulqdq_512: {
2840     if (auto *C = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
2841       unsigned Imm = C->getZExtValue();
2842 
2843       bool MadeChange = false;
2844       Value *Arg0 = II->getArgOperand(0);
2845       Value *Arg1 = II->getArgOperand(1);
2846       unsigned VWidth = Arg0->getType()->getVectorNumElements();
2847 
2848       APInt UndefElts1(VWidth, 0);
2849       APInt DemandedElts1 = APInt::getSplat(VWidth,
2850                                             APInt(2, (Imm & 0x01) ? 2 : 1));
2851       if (Value *V = SimplifyDemandedVectorElts(Arg0, DemandedElts1,
2852                                                 UndefElts1)) {
2853         II->setArgOperand(0, V);
2854         MadeChange = true;
2855       }
2856 
2857       APInt UndefElts2(VWidth, 0);
2858       APInt DemandedElts2 = APInt::getSplat(VWidth,
2859                                             APInt(2, (Imm & 0x10) ? 2 : 1));
2860       if (Value *V = SimplifyDemandedVectorElts(Arg1, DemandedElts2,
2861                                                 UndefElts2)) {
2862         II->setArgOperand(1, V);
2863         MadeChange = true;
2864       }
2865 
2866       // If either input elements are undef, the result is zero.
2867       if (DemandedElts1.isSubsetOf(UndefElts1) ||
2868           DemandedElts2.isSubsetOf(UndefElts2))
2869         return replaceInstUsesWith(*II,
2870                                    ConstantAggregateZero::get(II->getType()));
2871 
2872       if (MadeChange)
2873         return II;
2874     }
2875     break;
2876   }
2877 
2878   case Intrinsic::x86_sse41_insertps:
2879     if (Value *V = simplifyX86insertps(*II, Builder))
2880       return replaceInstUsesWith(*II, V);
2881     break;
2882 
2883   case Intrinsic::x86_sse4a_extrq: {
2884     Value *Op0 = II->getArgOperand(0);
2885     Value *Op1 = II->getArgOperand(1);
2886     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2887     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2888     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2889            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2890            VWidth1 == 16 && "Unexpected operand sizes");
2891 
2892     // See if we're dealing with constant values.
2893     Constant *C1 = dyn_cast<Constant>(Op1);
2894     ConstantInt *CILength =
2895         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
2896            : nullptr;
2897     ConstantInt *CIIndex =
2898         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
2899            : nullptr;
2900 
2901     // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
2902     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
2903       return replaceInstUsesWith(*II, V);
2904 
2905     // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
2906     // operands and the lowest 16-bits of the second.
2907     bool MadeChange = false;
2908     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2909       II->setArgOperand(0, V);
2910       MadeChange = true;
2911     }
2912     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
2913       II->setArgOperand(1, V);
2914       MadeChange = true;
2915     }
2916     if (MadeChange)
2917       return II;
2918     break;
2919   }
2920 
2921   case Intrinsic::x86_sse4a_extrqi: {
2922     // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
2923     // bits of the lower 64-bits. The upper 64-bits are undefined.
2924     Value *Op0 = II->getArgOperand(0);
2925     unsigned VWidth = Op0->getType()->getVectorNumElements();
2926     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2927            "Unexpected operand size");
2928 
2929     // See if we're dealing with constant values.
2930     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
2931     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
2932 
2933     // Attempt to simplify to a constant or shuffle vector.
2934     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, Builder))
2935       return replaceInstUsesWith(*II, V);
2936 
2937     // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
2938     // operand.
2939     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2940       II->setArgOperand(0, V);
2941       return II;
2942     }
2943     break;
2944   }
2945 
2946   case Intrinsic::x86_sse4a_insertq: {
2947     Value *Op0 = II->getArgOperand(0);
2948     Value *Op1 = II->getArgOperand(1);
2949     unsigned VWidth = Op0->getType()->getVectorNumElements();
2950     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2951            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
2952            Op1->getType()->getVectorNumElements() == 2 &&
2953            "Unexpected operand size");
2954 
2955     // See if we're dealing with constant values.
2956     Constant *C1 = dyn_cast<Constant>(Op1);
2957     ConstantInt *CI11 =
2958         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
2959            : nullptr;
2960 
2961     // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
2962     if (CI11) {
2963       const APInt &V11 = CI11->getValue();
2964       APInt Len = V11.zextOrTrunc(6);
2965       APInt Idx = V11.lshr(8).zextOrTrunc(6);
2966       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
2967         return replaceInstUsesWith(*II, V);
2968     }
2969 
2970     // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2971     // operand.
2972     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2973       II->setArgOperand(0, V);
2974       return II;
2975     }
2976     break;
2977   }
2978 
2979   case Intrinsic::x86_sse4a_insertqi: {
2980     // INSERTQI: Extract lowest Length bits from lower half of second source and
2981     // insert over first source starting at Index bit. The upper 64-bits are
2982     // undefined.
2983     Value *Op0 = II->getArgOperand(0);
2984     Value *Op1 = II->getArgOperand(1);
2985     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2986     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2987     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2988            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2989            VWidth1 == 2 && "Unexpected operand sizes");
2990 
2991     // See if we're dealing with constant values.
2992     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2993     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2994 
2995     // Attempt to simplify to a constant or shuffle vector.
2996     if (CILength && CIIndex) {
2997       APInt Len = CILength->getValue().zextOrTrunc(6);
2998       APInt Idx = CIIndex->getValue().zextOrTrunc(6);
2999       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, Builder))
3000         return replaceInstUsesWith(*II, V);
3001     }
3002 
3003     // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
3004     // operands.
3005     bool MadeChange = false;
3006     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
3007       II->setArgOperand(0, V);
3008       MadeChange = true;
3009     }
3010     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
3011       II->setArgOperand(1, V);
3012       MadeChange = true;
3013     }
3014     if (MadeChange)
3015       return II;
3016     break;
3017   }
3018 
3019   case Intrinsic::x86_sse41_pblendvb:
3020   case Intrinsic::x86_sse41_blendvps:
3021   case Intrinsic::x86_sse41_blendvpd:
3022   case Intrinsic::x86_avx_blendv_ps_256:
3023   case Intrinsic::x86_avx_blendv_pd_256:
3024   case Intrinsic::x86_avx2_pblendvb: {
3025     // fold (blend A, A, Mask) -> A
3026     Value *Op0 = II->getArgOperand(0);
3027     Value *Op1 = II->getArgOperand(1);
3028     Value *Mask = II->getArgOperand(2);
3029     if (Op0 == Op1)
3030       return replaceInstUsesWith(CI, Op0);
3031 
3032     // Zero Mask - select 1st argument.
3033     if (isa<ConstantAggregateZero>(Mask))
3034       return replaceInstUsesWith(CI, Op0);
3035 
3036     // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
3037     if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
3038       Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
3039       return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
3040     }
3041 
3042     // Convert to a vector select if we can bypass casts and find a boolean
3043     // vector condition value.
3044     Value *BoolVec;
3045     Mask = peekThroughBitcast(Mask);
3046     if (match(Mask, m_SExt(m_Value(BoolVec))) &&
3047         BoolVec->getType()->isVectorTy() &&
3048         BoolVec->getType()->getScalarSizeInBits() == 1) {
3049       assert(Mask->getType()->getPrimitiveSizeInBits() ==
3050              II->getType()->getPrimitiveSizeInBits() &&
3051              "Not expecting mask and operands with different sizes");
3052 
3053       unsigned NumMaskElts = Mask->getType()->getVectorNumElements();
3054       unsigned NumOperandElts = II->getType()->getVectorNumElements();
3055       if (NumMaskElts == NumOperandElts)
3056         return SelectInst::Create(BoolVec, Op1, Op0);
3057 
3058       // If the mask has less elements than the operands, each mask bit maps to
3059       // multiple elements of the operands. Bitcast back and forth.
3060       if (NumMaskElts < NumOperandElts) {
3061         Value *CastOp0 = Builder.CreateBitCast(Op0, Mask->getType());
3062         Value *CastOp1 = Builder.CreateBitCast(Op1, Mask->getType());
3063         Value *Sel = Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
3064         return new BitCastInst(Sel, II->getType());
3065       }
3066     }
3067 
3068     break;
3069   }
3070 
3071   case Intrinsic::x86_ssse3_pshuf_b_128:
3072   case Intrinsic::x86_avx2_pshuf_b:
3073   case Intrinsic::x86_avx512_pshuf_b_512:
3074     if (Value *V = simplifyX86pshufb(*II, Builder))
3075       return replaceInstUsesWith(*II, V);
3076     break;
3077 
3078   case Intrinsic::x86_avx_vpermilvar_ps:
3079   case Intrinsic::x86_avx_vpermilvar_ps_256:
3080   case Intrinsic::x86_avx512_vpermilvar_ps_512:
3081   case Intrinsic::x86_avx_vpermilvar_pd:
3082   case Intrinsic::x86_avx_vpermilvar_pd_256:
3083   case Intrinsic::x86_avx512_vpermilvar_pd_512:
3084     if (Value *V = simplifyX86vpermilvar(*II, Builder))
3085       return replaceInstUsesWith(*II, V);
3086     break;
3087 
3088   case Intrinsic::x86_avx2_permd:
3089   case Intrinsic::x86_avx2_permps:
3090   case Intrinsic::x86_avx512_permvar_df_256:
3091   case Intrinsic::x86_avx512_permvar_df_512:
3092   case Intrinsic::x86_avx512_permvar_di_256:
3093   case Intrinsic::x86_avx512_permvar_di_512:
3094   case Intrinsic::x86_avx512_permvar_hi_128:
3095   case Intrinsic::x86_avx512_permvar_hi_256:
3096   case Intrinsic::x86_avx512_permvar_hi_512:
3097   case Intrinsic::x86_avx512_permvar_qi_128:
3098   case Intrinsic::x86_avx512_permvar_qi_256:
3099   case Intrinsic::x86_avx512_permvar_qi_512:
3100   case Intrinsic::x86_avx512_permvar_sf_512:
3101   case Intrinsic::x86_avx512_permvar_si_512:
3102     if (Value *V = simplifyX86vpermv(*II, Builder))
3103       return replaceInstUsesWith(*II, V);
3104     break;
3105 
3106   case Intrinsic::x86_avx_maskload_ps:
3107   case Intrinsic::x86_avx_maskload_pd:
3108   case Intrinsic::x86_avx_maskload_ps_256:
3109   case Intrinsic::x86_avx_maskload_pd_256:
3110   case Intrinsic::x86_avx2_maskload_d:
3111   case Intrinsic::x86_avx2_maskload_q:
3112   case Intrinsic::x86_avx2_maskload_d_256:
3113   case Intrinsic::x86_avx2_maskload_q_256:
3114     if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
3115       return I;
3116     break;
3117 
3118   case Intrinsic::x86_sse2_maskmov_dqu:
3119   case Intrinsic::x86_avx_maskstore_ps:
3120   case Intrinsic::x86_avx_maskstore_pd:
3121   case Intrinsic::x86_avx_maskstore_ps_256:
3122   case Intrinsic::x86_avx_maskstore_pd_256:
3123   case Intrinsic::x86_avx2_maskstore_d:
3124   case Intrinsic::x86_avx2_maskstore_q:
3125   case Intrinsic::x86_avx2_maskstore_d_256:
3126   case Intrinsic::x86_avx2_maskstore_q_256:
3127     if (simplifyX86MaskedStore(*II, *this))
3128       return nullptr;
3129     break;
3130 
3131   case Intrinsic::ppc_altivec_vperm:
3132     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
3133     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
3134     // a vectorshuffle for little endian, we must undo the transformation
3135     // performed on vec_perm in altivec.h.  That is, we must complement
3136     // the permutation mask with respect to 31 and reverse the order of
3137     // V1 and V2.
3138     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
3139       assert(Mask->getType()->getVectorNumElements() == 16 &&
3140              "Bad type for intrinsic!");
3141 
3142       // Check that all of the elements are integer constants or undefs.
3143       bool AllEltsOk = true;
3144       for (unsigned i = 0; i != 16; ++i) {
3145         Constant *Elt = Mask->getAggregateElement(i);
3146         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
3147           AllEltsOk = false;
3148           break;
3149         }
3150       }
3151 
3152       if (AllEltsOk) {
3153         // Cast the input vectors to byte vectors.
3154         Value *Op0 = Builder.CreateBitCast(II->getArgOperand(0),
3155                                            Mask->getType());
3156         Value *Op1 = Builder.CreateBitCast(II->getArgOperand(1),
3157                                            Mask->getType());
3158         Value *Result = UndefValue::get(Op0->getType());
3159 
3160         // Only extract each element once.
3161         Value *ExtractedElts[32];
3162         memset(ExtractedElts, 0, sizeof(ExtractedElts));
3163 
3164         for (unsigned i = 0; i != 16; ++i) {
3165           if (isa<UndefValue>(Mask->getAggregateElement(i)))
3166             continue;
3167           unsigned Idx =
3168             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
3169           Idx &= 31;  // Match the hardware behavior.
3170           if (DL.isLittleEndian())
3171             Idx = 31 - Idx;
3172 
3173           if (!ExtractedElts[Idx]) {
3174             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
3175             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
3176             ExtractedElts[Idx] =
3177               Builder.CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
3178                                            Builder.getInt32(Idx&15));
3179           }
3180 
3181           // Insert this value into the result vector.
3182           Result = Builder.CreateInsertElement(Result, ExtractedElts[Idx],
3183                                                Builder.getInt32(i));
3184         }
3185         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
3186       }
3187     }
3188     break;
3189 
3190   case Intrinsic::arm_neon_vld1: {
3191     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0),
3192                                           DL, II, &AC, &DT);
3193     if (Value *V = simplifyNeonVld1(*II, MemAlign, Builder))
3194       return replaceInstUsesWith(*II, V);
3195     break;
3196   }
3197 
3198   case Intrinsic::arm_neon_vld2:
3199   case Intrinsic::arm_neon_vld3:
3200   case Intrinsic::arm_neon_vld4:
3201   case Intrinsic::arm_neon_vld2lane:
3202   case Intrinsic::arm_neon_vld3lane:
3203   case Intrinsic::arm_neon_vld4lane:
3204   case Intrinsic::arm_neon_vst1:
3205   case Intrinsic::arm_neon_vst2:
3206   case Intrinsic::arm_neon_vst3:
3207   case Intrinsic::arm_neon_vst4:
3208   case Intrinsic::arm_neon_vst2lane:
3209   case Intrinsic::arm_neon_vst3lane:
3210   case Intrinsic::arm_neon_vst4lane: {
3211     unsigned MemAlign =
3212         getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
3213     unsigned AlignArg = II->getNumArgOperands() - 1;
3214     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
3215     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
3216       II->setArgOperand(AlignArg,
3217                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
3218                                          MemAlign, false));
3219       return II;
3220     }
3221     break;
3222   }
3223 
3224   case Intrinsic::arm_neon_vtbl1:
3225   case Intrinsic::aarch64_neon_tbl1:
3226     if (Value *V = simplifyNeonTbl1(*II, Builder))
3227       return replaceInstUsesWith(*II, V);
3228     break;
3229 
3230   case Intrinsic::arm_neon_vmulls:
3231   case Intrinsic::arm_neon_vmullu:
3232   case Intrinsic::aarch64_neon_smull:
3233   case Intrinsic::aarch64_neon_umull: {
3234     Value *Arg0 = II->getArgOperand(0);
3235     Value *Arg1 = II->getArgOperand(1);
3236 
3237     // Handle mul by zero first:
3238     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
3239       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
3240     }
3241 
3242     // Check for constant LHS & RHS - in this case we just simplify.
3243     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
3244                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
3245     VectorType *NewVT = cast<VectorType>(II->getType());
3246     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
3247       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
3248         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
3249         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
3250 
3251         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
3252       }
3253 
3254       // Couldn't simplify - canonicalize constant to the RHS.
3255       std::swap(Arg0, Arg1);
3256     }
3257 
3258     // Handle mul by one:
3259     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
3260       if (ConstantInt *Splat =
3261               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
3262         if (Splat->isOne())
3263           return CastInst::CreateIntegerCast(Arg0, II->getType(),
3264                                              /*isSigned=*/!Zext);
3265 
3266     break;
3267   }
3268   case Intrinsic::arm_neon_aesd:
3269   case Intrinsic::arm_neon_aese:
3270   case Intrinsic::aarch64_crypto_aesd:
3271   case Intrinsic::aarch64_crypto_aese: {
3272     Value *DataArg = II->getArgOperand(0);
3273     Value *KeyArg  = II->getArgOperand(1);
3274 
3275     // Try to use the builtin XOR in AESE and AESD to eliminate a prior XOR
3276     Value *Data, *Key;
3277     if (match(KeyArg, m_ZeroInt()) &&
3278         match(DataArg, m_Xor(m_Value(Data), m_Value(Key)))) {
3279       II->setArgOperand(0, Data);
3280       II->setArgOperand(1, Key);
3281       return II;
3282     }
3283     break;
3284   }
3285   case Intrinsic::amdgcn_rcp: {
3286     Value *Src = II->getArgOperand(0);
3287 
3288     // TODO: Move to ConstantFolding/InstSimplify?
3289     if (isa<UndefValue>(Src))
3290       return replaceInstUsesWith(CI, Src);
3291 
3292     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3293       const APFloat &ArgVal = C->getValueAPF();
3294       APFloat Val(ArgVal.getSemantics(), 1.0);
3295       APFloat::opStatus Status = Val.divide(ArgVal,
3296                                             APFloat::rmNearestTiesToEven);
3297       // Only do this if it was exact and therefore not dependent on the
3298       // rounding mode.
3299       if (Status == APFloat::opOK)
3300         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
3301     }
3302 
3303     break;
3304   }
3305   case Intrinsic::amdgcn_rsq: {
3306     Value *Src = II->getArgOperand(0);
3307 
3308     // TODO: Move to ConstantFolding/InstSimplify?
3309     if (isa<UndefValue>(Src))
3310       return replaceInstUsesWith(CI, Src);
3311     break;
3312   }
3313   case Intrinsic::amdgcn_frexp_mant:
3314   case Intrinsic::amdgcn_frexp_exp: {
3315     Value *Src = II->getArgOperand(0);
3316     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
3317       int Exp;
3318       APFloat Significand = frexp(C->getValueAPF(), Exp,
3319                                   APFloat::rmNearestTiesToEven);
3320 
3321       if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
3322         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
3323                                                        Significand));
3324       }
3325 
3326       // Match instruction special case behavior.
3327       if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
3328         Exp = 0;
3329 
3330       return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
3331     }
3332 
3333     if (isa<UndefValue>(Src))
3334       return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
3335 
3336     break;
3337   }
3338   case Intrinsic::amdgcn_class: {
3339     enum  {
3340       S_NAN = 1 << 0,        // Signaling NaN
3341       Q_NAN = 1 << 1,        // Quiet NaN
3342       N_INFINITY = 1 << 2,   // Negative infinity
3343       N_NORMAL = 1 << 3,     // Negative normal
3344       N_SUBNORMAL = 1 << 4,  // Negative subnormal
3345       N_ZERO = 1 << 5,       // Negative zero
3346       P_ZERO = 1 << 6,       // Positive zero
3347       P_SUBNORMAL = 1 << 7,  // Positive subnormal
3348       P_NORMAL = 1 << 8,     // Positive normal
3349       P_INFINITY = 1 << 9    // Positive infinity
3350     };
3351 
3352     const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
3353       N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
3354 
3355     Value *Src0 = II->getArgOperand(0);
3356     Value *Src1 = II->getArgOperand(1);
3357     const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
3358     if (!CMask) {
3359       if (isa<UndefValue>(Src0))
3360         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3361 
3362       if (isa<UndefValue>(Src1))
3363         return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3364       break;
3365     }
3366 
3367     uint32_t Mask = CMask->getZExtValue();
3368 
3369     // If all tests are made, it doesn't matter what the value is.
3370     if ((Mask & FullMask) == FullMask)
3371       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
3372 
3373     if ((Mask & FullMask) == 0)
3374       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
3375 
3376     if (Mask == (S_NAN | Q_NAN)) {
3377       // Equivalent of isnan. Replace with standard fcmp.
3378       Value *FCmp = Builder.CreateFCmpUNO(Src0, Src0);
3379       FCmp->takeName(II);
3380       return replaceInstUsesWith(*II, FCmp);
3381     }
3382 
3383     if (Mask == (N_ZERO | P_ZERO)) {
3384       // Equivalent of == 0.
3385       Value *FCmp = Builder.CreateFCmpOEQ(
3386         Src0, ConstantFP::get(Src0->getType(), 0.0));
3387 
3388       FCmp->takeName(II);
3389       return replaceInstUsesWith(*II, FCmp);
3390     }
3391 
3392     // fp_class (nnan x), qnan|snan|other -> fp_class (nnan x), other
3393     if (((Mask & S_NAN) || (Mask & Q_NAN)) && isKnownNeverNaN(Src0, &TLI)) {
3394       II->setArgOperand(1, ConstantInt::get(Src1->getType(),
3395                                             Mask & ~(S_NAN | Q_NAN)));
3396       return II;
3397     }
3398 
3399     const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
3400     if (!CVal) {
3401       if (isa<UndefValue>(Src0))
3402         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3403 
3404       // Clamp mask to used bits
3405       if ((Mask & FullMask) != Mask) {
3406         CallInst *NewCall = Builder.CreateCall(II->getCalledFunction(),
3407           { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
3408         );
3409 
3410         NewCall->takeName(II);
3411         return replaceInstUsesWith(*II, NewCall);
3412       }
3413 
3414       break;
3415     }
3416 
3417     const APFloat &Val = CVal->getValueAPF();
3418 
3419     bool Result =
3420       ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
3421       ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
3422       ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
3423       ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
3424       ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
3425       ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
3426       ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
3427       ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
3428       ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
3429       ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
3430 
3431     return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
3432   }
3433   case Intrinsic::amdgcn_cvt_pkrtz: {
3434     Value *Src0 = II->getArgOperand(0);
3435     Value *Src1 = II->getArgOperand(1);
3436     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3437       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3438         const fltSemantics &HalfSem
3439           = II->getType()->getScalarType()->getFltSemantics();
3440         bool LosesInfo;
3441         APFloat Val0 = C0->getValueAPF();
3442         APFloat Val1 = C1->getValueAPF();
3443         Val0.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3444         Val1.convert(HalfSem, APFloat::rmTowardZero, &LosesInfo);
3445 
3446         Constant *Folded = ConstantVector::get({
3447             ConstantFP::get(II->getContext(), Val0),
3448             ConstantFP::get(II->getContext(), Val1) });
3449         return replaceInstUsesWith(*II, Folded);
3450       }
3451     }
3452 
3453     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3454       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3455 
3456     break;
3457   }
3458   case Intrinsic::amdgcn_cvt_pknorm_i16:
3459   case Intrinsic::amdgcn_cvt_pknorm_u16:
3460   case Intrinsic::amdgcn_cvt_pk_i16:
3461   case Intrinsic::amdgcn_cvt_pk_u16: {
3462     Value *Src0 = II->getArgOperand(0);
3463     Value *Src1 = II->getArgOperand(1);
3464 
3465     if (isa<UndefValue>(Src0) && isa<UndefValue>(Src1))
3466       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3467 
3468     break;
3469   }
3470   case Intrinsic::amdgcn_ubfe:
3471   case Intrinsic::amdgcn_sbfe: {
3472     // Decompose simple cases into standard shifts.
3473     Value *Src = II->getArgOperand(0);
3474     if (isa<UndefValue>(Src))
3475       return replaceInstUsesWith(*II, Src);
3476 
3477     unsigned Width;
3478     Type *Ty = II->getType();
3479     unsigned IntSize = Ty->getIntegerBitWidth();
3480 
3481     ConstantInt *CWidth = dyn_cast<ConstantInt>(II->getArgOperand(2));
3482     if (CWidth) {
3483       Width = CWidth->getZExtValue();
3484       if ((Width & (IntSize - 1)) == 0)
3485         return replaceInstUsesWith(*II, ConstantInt::getNullValue(Ty));
3486 
3487       if (Width >= IntSize) {
3488         // Hardware ignores high bits, so remove those.
3489         II->setArgOperand(2, ConstantInt::get(CWidth->getType(),
3490                                               Width & (IntSize - 1)));
3491         return II;
3492       }
3493     }
3494 
3495     unsigned Offset;
3496     ConstantInt *COffset = dyn_cast<ConstantInt>(II->getArgOperand(1));
3497     if (COffset) {
3498       Offset = COffset->getZExtValue();
3499       if (Offset >= IntSize) {
3500         II->setArgOperand(1, ConstantInt::get(COffset->getType(),
3501                                               Offset & (IntSize - 1)));
3502         return II;
3503       }
3504     }
3505 
3506     bool Signed = II->getIntrinsicID() == Intrinsic::amdgcn_sbfe;
3507 
3508     if (!CWidth || !COffset)
3509       break;
3510 
3511     // The case of Width == 0 is handled above, which makes this tranformation
3512     // safe.  If Width == 0, then the ashr and lshr instructions become poison
3513     // value since the shift amount would be equal to the bit size.
3514     assert(Width != 0);
3515 
3516     // TODO: This allows folding to undef when the hardware has specific
3517     // behavior?
3518     if (Offset + Width < IntSize) {
3519       Value *Shl = Builder.CreateShl(Src, IntSize - Offset - Width);
3520       Value *RightShift = Signed ? Builder.CreateAShr(Shl, IntSize - Width)
3521                                  : Builder.CreateLShr(Shl, IntSize - Width);
3522       RightShift->takeName(II);
3523       return replaceInstUsesWith(*II, RightShift);
3524     }
3525 
3526     Value *RightShift = Signed ? Builder.CreateAShr(Src, Offset)
3527                                : Builder.CreateLShr(Src, Offset);
3528 
3529     RightShift->takeName(II);
3530     return replaceInstUsesWith(*II, RightShift);
3531   }
3532   case Intrinsic::amdgcn_exp:
3533   case Intrinsic::amdgcn_exp_compr: {
3534     ConstantInt *En = dyn_cast<ConstantInt>(II->getArgOperand(1));
3535     if (!En) // Illegal.
3536       break;
3537 
3538     unsigned EnBits = En->getZExtValue();
3539     if (EnBits == 0xf)
3540       break; // All inputs enabled.
3541 
3542     bool IsCompr = II->getIntrinsicID() == Intrinsic::amdgcn_exp_compr;
3543     bool Changed = false;
3544     for (int I = 0; I < (IsCompr ? 2 : 4); ++I) {
3545       if ((!IsCompr && (EnBits & (1 << I)) == 0) ||
3546           (IsCompr && ((EnBits & (0x3 << (2 * I))) == 0))) {
3547         Value *Src = II->getArgOperand(I + 2);
3548         if (!isa<UndefValue>(Src)) {
3549           II->setArgOperand(I + 2, UndefValue::get(Src->getType()));
3550           Changed = true;
3551         }
3552       }
3553     }
3554 
3555     if (Changed)
3556       return II;
3557 
3558     break;
3559   }
3560   case Intrinsic::amdgcn_fmed3: {
3561     // Note this does not preserve proper sNaN behavior if IEEE-mode is enabled
3562     // for the shader.
3563 
3564     Value *Src0 = II->getArgOperand(0);
3565     Value *Src1 = II->getArgOperand(1);
3566     Value *Src2 = II->getArgOperand(2);
3567 
3568     // Checking for NaN before canonicalization provides better fidelity when
3569     // mapping other operations onto fmed3 since the order of operands is
3570     // unchanged.
3571     CallInst *NewCall = nullptr;
3572     if (match(Src0, m_NaN()) || isa<UndefValue>(Src0)) {
3573       NewCall = Builder.CreateMinNum(Src1, Src2);
3574     } else if (match(Src1, m_NaN()) || isa<UndefValue>(Src1)) {
3575       NewCall = Builder.CreateMinNum(Src0, Src2);
3576     } else if (match(Src2, m_NaN()) || isa<UndefValue>(Src2)) {
3577       NewCall = Builder.CreateMaxNum(Src0, Src1);
3578     }
3579 
3580     if (NewCall) {
3581       NewCall->copyFastMathFlags(II);
3582       NewCall->takeName(II);
3583       return replaceInstUsesWith(*II, NewCall);
3584     }
3585 
3586     bool Swap = false;
3587     // Canonicalize constants to RHS operands.
3588     //
3589     // fmed3(c0, x, c1) -> fmed3(x, c0, c1)
3590     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3591       std::swap(Src0, Src1);
3592       Swap = true;
3593     }
3594 
3595     if (isa<Constant>(Src1) && !isa<Constant>(Src2)) {
3596       std::swap(Src1, Src2);
3597       Swap = true;
3598     }
3599 
3600     if (isa<Constant>(Src0) && !isa<Constant>(Src1)) {
3601       std::swap(Src0, Src1);
3602       Swap = true;
3603     }
3604 
3605     if (Swap) {
3606       II->setArgOperand(0, Src0);
3607       II->setArgOperand(1, Src1);
3608       II->setArgOperand(2, Src2);
3609       return II;
3610     }
3611 
3612     if (const ConstantFP *C0 = dyn_cast<ConstantFP>(Src0)) {
3613       if (const ConstantFP *C1 = dyn_cast<ConstantFP>(Src1)) {
3614         if (const ConstantFP *C2 = dyn_cast<ConstantFP>(Src2)) {
3615           APFloat Result = fmed3AMDGCN(C0->getValueAPF(), C1->getValueAPF(),
3616                                        C2->getValueAPF());
3617           return replaceInstUsesWith(*II,
3618             ConstantFP::get(Builder.getContext(), Result));
3619         }
3620       }
3621     }
3622 
3623     break;
3624   }
3625   case Intrinsic::amdgcn_icmp:
3626   case Intrinsic::amdgcn_fcmp: {
3627     const ConstantInt *CC = dyn_cast<ConstantInt>(II->getArgOperand(2));
3628     if (!CC)
3629       break;
3630 
3631     // Guard against invalid arguments.
3632     int64_t CCVal = CC->getZExtValue();
3633     bool IsInteger = II->getIntrinsicID() == Intrinsic::amdgcn_icmp;
3634     if ((IsInteger && (CCVal < CmpInst::FIRST_ICMP_PREDICATE ||
3635                        CCVal > CmpInst::LAST_ICMP_PREDICATE)) ||
3636         (!IsInteger && (CCVal < CmpInst::FIRST_FCMP_PREDICATE ||
3637                         CCVal > CmpInst::LAST_FCMP_PREDICATE)))
3638       break;
3639 
3640     Value *Src0 = II->getArgOperand(0);
3641     Value *Src1 = II->getArgOperand(1);
3642 
3643     if (auto *CSrc0 = dyn_cast<Constant>(Src0)) {
3644       if (auto *CSrc1 = dyn_cast<Constant>(Src1)) {
3645         Constant *CCmp = ConstantExpr::getCompare(CCVal, CSrc0, CSrc1);
3646         if (CCmp->isNullValue()) {
3647           return replaceInstUsesWith(
3648               *II, ConstantExpr::getSExt(CCmp, II->getType()));
3649         }
3650 
3651         // The result of V_ICMP/V_FCMP assembly instructions (which this
3652         // intrinsic exposes) is one bit per thread, masked with the EXEC
3653         // register (which contains the bitmask of live threads). So a
3654         // comparison that always returns true is the same as a read of the
3655         // EXEC register.
3656         Value *NewF = Intrinsic::getDeclaration(
3657             II->getModule(), Intrinsic::read_register, II->getType());
3658         Metadata *MDArgs[] = {MDString::get(II->getContext(), "exec")};
3659         MDNode *MD = MDNode::get(II->getContext(), MDArgs);
3660         Value *Args[] = {MetadataAsValue::get(II->getContext(), MD)};
3661         CallInst *NewCall = Builder.CreateCall(NewF, Args);
3662         NewCall->addAttribute(AttributeList::FunctionIndex,
3663                               Attribute::Convergent);
3664         NewCall->takeName(II);
3665         return replaceInstUsesWith(*II, NewCall);
3666       }
3667 
3668       // Canonicalize constants to RHS.
3669       CmpInst::Predicate SwapPred
3670         = CmpInst::getSwappedPredicate(static_cast<CmpInst::Predicate>(CCVal));
3671       II->setArgOperand(0, Src1);
3672       II->setArgOperand(1, Src0);
3673       II->setArgOperand(2, ConstantInt::get(CC->getType(),
3674                                             static_cast<int>(SwapPred)));
3675       return II;
3676     }
3677 
3678     if (CCVal != CmpInst::ICMP_EQ && CCVal != CmpInst::ICMP_NE)
3679       break;
3680 
3681     // Canonicalize compare eq with true value to compare != 0
3682     // llvm.amdgcn.icmp(zext (i1 x), 1, eq)
3683     //   -> llvm.amdgcn.icmp(zext (i1 x), 0, ne)
3684     // llvm.amdgcn.icmp(sext (i1 x), -1, eq)
3685     //   -> llvm.amdgcn.icmp(sext (i1 x), 0, ne)
3686     Value *ExtSrc;
3687     if (CCVal == CmpInst::ICMP_EQ &&
3688         ((match(Src1, m_One()) && match(Src0, m_ZExt(m_Value(ExtSrc)))) ||
3689          (match(Src1, m_AllOnes()) && match(Src0, m_SExt(m_Value(ExtSrc))))) &&
3690         ExtSrc->getType()->isIntegerTy(1)) {
3691       II->setArgOperand(1, ConstantInt::getNullValue(Src1->getType()));
3692       II->setArgOperand(2, ConstantInt::get(CC->getType(), CmpInst::ICMP_NE));
3693       return II;
3694     }
3695 
3696     CmpInst::Predicate SrcPred;
3697     Value *SrcLHS;
3698     Value *SrcRHS;
3699 
3700     // Fold compare eq/ne with 0 from a compare result as the predicate to the
3701     // intrinsic. The typical use is a wave vote function in the library, which
3702     // will be fed from a user code condition compared with 0. Fold in the
3703     // redundant compare.
3704 
3705     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, ne)
3706     //   -> llvm.amdgcn.[if]cmp(a, b, pred)
3707     //
3708     // llvm.amdgcn.icmp([sz]ext ([if]cmp pred a, b), 0, eq)
3709     //   -> llvm.amdgcn.[if]cmp(a, b, inv pred)
3710     if (match(Src1, m_Zero()) &&
3711         match(Src0,
3712               m_ZExtOrSExt(m_Cmp(SrcPred, m_Value(SrcLHS), m_Value(SrcRHS))))) {
3713       if (CCVal == CmpInst::ICMP_EQ)
3714         SrcPred = CmpInst::getInversePredicate(SrcPred);
3715 
3716       Intrinsic::ID NewIID = CmpInst::isFPPredicate(SrcPred) ?
3717         Intrinsic::amdgcn_fcmp : Intrinsic::amdgcn_icmp;
3718 
3719       Type *Ty = SrcLHS->getType();
3720       if (auto *CmpType = dyn_cast<IntegerType>(Ty)) {
3721         // Promote to next legal integer type.
3722         unsigned Width = CmpType->getBitWidth();
3723         unsigned NewWidth = Width;
3724 
3725         // Don't do anything for i1 comparisons.
3726         if (Width == 1)
3727           break;
3728 
3729         if (Width <= 16)
3730           NewWidth = 16;
3731         else if (Width <= 32)
3732           NewWidth = 32;
3733         else if (Width <= 64)
3734           NewWidth = 64;
3735         else if (Width > 64)
3736           break; // Can't handle this.
3737 
3738         if (Width != NewWidth) {
3739           IntegerType *CmpTy = Builder.getIntNTy(NewWidth);
3740           if (CmpInst::isSigned(SrcPred)) {
3741             SrcLHS = Builder.CreateSExt(SrcLHS, CmpTy);
3742             SrcRHS = Builder.CreateSExt(SrcRHS, CmpTy);
3743           } else {
3744             SrcLHS = Builder.CreateZExt(SrcLHS, CmpTy);
3745             SrcRHS = Builder.CreateZExt(SrcRHS, CmpTy);
3746           }
3747         }
3748       } else if (!Ty->isFloatTy() && !Ty->isDoubleTy() && !Ty->isHalfTy())
3749         break;
3750 
3751       Value *NewF = Intrinsic::getDeclaration(II->getModule(), NewIID,
3752                                               SrcLHS->getType());
3753       Value *Args[] = { SrcLHS, SrcRHS,
3754                         ConstantInt::get(CC->getType(), SrcPred) };
3755       CallInst *NewCall = Builder.CreateCall(NewF, Args);
3756       NewCall->takeName(II);
3757       return replaceInstUsesWith(*II, NewCall);
3758     }
3759 
3760     break;
3761   }
3762   case Intrinsic::amdgcn_wqm_vote: {
3763     // wqm_vote is identity when the argument is constant.
3764     if (!isa<Constant>(II->getArgOperand(0)))
3765       break;
3766 
3767     return replaceInstUsesWith(*II, II->getArgOperand(0));
3768   }
3769   case Intrinsic::amdgcn_kill: {
3770     const ConstantInt *C = dyn_cast<ConstantInt>(II->getArgOperand(0));
3771     if (!C || !C->getZExtValue())
3772       break;
3773 
3774     // amdgcn.kill(i1 1) is a no-op
3775     return eraseInstFromFunction(CI);
3776   }
3777   case Intrinsic::amdgcn_update_dpp: {
3778     Value *Old = II->getArgOperand(0);
3779 
3780     auto BC = dyn_cast<ConstantInt>(II->getArgOperand(5));
3781     auto RM = dyn_cast<ConstantInt>(II->getArgOperand(3));
3782     auto BM = dyn_cast<ConstantInt>(II->getArgOperand(4));
3783     if (!BC || !RM || !BM ||
3784         BC->isZeroValue() ||
3785         RM->getZExtValue() != 0xF ||
3786         BM->getZExtValue() != 0xF ||
3787         isa<UndefValue>(Old))
3788       break;
3789 
3790     // If bound_ctrl = 1, row mask = bank mask = 0xf we can omit old value.
3791     II->setOperand(0, UndefValue::get(Old->getType()));
3792     return II;
3793   }
3794   case Intrinsic::stackrestore: {
3795     // If the save is right next to the restore, remove the restore.  This can
3796     // happen when variable allocas are DCE'd.
3797     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
3798       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
3799         // Skip over debug info.
3800         if (SS->getNextNonDebugInstruction() == II) {
3801           return eraseInstFromFunction(CI);
3802         }
3803       }
3804     }
3805 
3806     // Scan down this block to see if there is another stack restore in the
3807     // same block without an intervening call/alloca.
3808     BasicBlock::iterator BI(II);
3809     Instruction *TI = II->getParent()->getTerminator();
3810     bool CannotRemove = false;
3811     for (++BI; &*BI != TI; ++BI) {
3812       if (isa<AllocaInst>(BI)) {
3813         CannotRemove = true;
3814         break;
3815       }
3816       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
3817         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
3818           // If there is a stackrestore below this one, remove this one.
3819           if (II->getIntrinsicID() == Intrinsic::stackrestore)
3820             return eraseInstFromFunction(CI);
3821 
3822           // Bail if we cross over an intrinsic with side effects, such as
3823           // llvm.stacksave, llvm.read_register, or llvm.setjmp.
3824           if (II->mayHaveSideEffects()) {
3825             CannotRemove = true;
3826             break;
3827           }
3828         } else {
3829           // If we found a non-intrinsic call, we can't remove the stack
3830           // restore.
3831           CannotRemove = true;
3832           break;
3833         }
3834       }
3835     }
3836 
3837     // If the stack restore is in a return, resume, or unwind block and if there
3838     // are no allocas or calls between the restore and the return, nuke the
3839     // restore.
3840     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
3841       return eraseInstFromFunction(CI);
3842     break;
3843   }
3844   case Intrinsic::lifetime_start:
3845     // Asan needs to poison memory to detect invalid access which is possible
3846     // even for empty lifetime range.
3847     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress) ||
3848         II->getFunction()->hasFnAttribute(Attribute::SanitizeHWAddress))
3849       break;
3850 
3851     if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
3852                                   Intrinsic::lifetime_end, *this))
3853       return nullptr;
3854     break;
3855   case Intrinsic::assume: {
3856     Value *IIOperand = II->getArgOperand(0);
3857     // Remove an assume if it is followed by an identical assume.
3858     // TODO: Do we need this? Unless there are conflicting assumptions, the
3859     // computeKnownBits(IIOperand) below here eliminates redundant assumes.
3860     Instruction *Next = II->getNextNonDebugInstruction();
3861     if (match(Next, m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
3862       return eraseInstFromFunction(CI);
3863 
3864     // Canonicalize assume(a && b) -> assume(a); assume(b);
3865     // Note: New assumption intrinsics created here are registered by
3866     // the InstCombineIRInserter object.
3867     Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
3868     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
3869       Builder.CreateCall(AssumeIntrinsic, A, II->getName());
3870       Builder.CreateCall(AssumeIntrinsic, B, II->getName());
3871       return eraseInstFromFunction(*II);
3872     }
3873     // assume(!(a || b)) -> assume(!a); assume(!b);
3874     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
3875       Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(A), II->getName());
3876       Builder.CreateCall(AssumeIntrinsic, Builder.CreateNot(B), II->getName());
3877       return eraseInstFromFunction(*II);
3878     }
3879 
3880     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
3881     // (if assume is valid at the load)
3882     CmpInst::Predicate Pred;
3883     Instruction *LHS;
3884     if (match(IIOperand, m_ICmp(Pred, m_Instruction(LHS), m_Zero())) &&
3885         Pred == ICmpInst::ICMP_NE && LHS->getOpcode() == Instruction::Load &&
3886         LHS->getType()->isPointerTy() &&
3887         isValidAssumeForContext(II, LHS, &DT)) {
3888       MDNode *MD = MDNode::get(II->getContext(), None);
3889       LHS->setMetadata(LLVMContext::MD_nonnull, MD);
3890       return eraseInstFromFunction(*II);
3891 
3892       // TODO: apply nonnull return attributes to calls and invokes
3893       // TODO: apply range metadata for range check patterns?
3894     }
3895 
3896     // If there is a dominating assume with the same condition as this one,
3897     // then this one is redundant, and should be removed.
3898     KnownBits Known(1);
3899     computeKnownBits(IIOperand, Known, 0, II);
3900     if (Known.isAllOnes())
3901       return eraseInstFromFunction(*II);
3902 
3903     // Update the cache of affected values for this assumption (we might be
3904     // here because we just simplified the condition).
3905     AC.updateAffectedValues(II);
3906     break;
3907   }
3908   case Intrinsic::experimental_gc_relocate: {
3909     // Translate facts known about a pointer before relocating into
3910     // facts about the relocate value, while being careful to
3911     // preserve relocation semantics.
3912     Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
3913 
3914     // Remove the relocation if unused, note that this check is required
3915     // to prevent the cases below from looping forever.
3916     if (II->use_empty())
3917       return eraseInstFromFunction(*II);
3918 
3919     // Undef is undef, even after relocation.
3920     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
3921     // most practical collectors, but there was discussion in the review thread
3922     // about whether it was legal for all possible collectors.
3923     if (isa<UndefValue>(DerivedPtr))
3924       // Use undef of gc_relocate's type to replace it.
3925       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
3926 
3927     if (auto *PT = dyn_cast<PointerType>(II->getType())) {
3928       // The relocation of null will be null for most any collector.
3929       // TODO: provide a hook for this in GCStrategy.  There might be some
3930       // weird collector this property does not hold for.
3931       if (isa<ConstantPointerNull>(DerivedPtr))
3932         // Use null-pointer of gc_relocate's type to replace it.
3933         return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
3934 
3935       // isKnownNonNull -> nonnull attribute
3936       if (!II->hasRetAttr(Attribute::NonNull) &&
3937           isKnownNonZero(DerivedPtr, DL, 0, &AC, II, &DT)) {
3938         II->addAttribute(AttributeList::ReturnIndex, Attribute::NonNull);
3939         return II;
3940       }
3941     }
3942 
3943     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
3944     // Canonicalize on the type from the uses to the defs
3945 
3946     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
3947     break;
3948   }
3949 
3950   case Intrinsic::experimental_guard: {
3951     // Is this guard followed by another guard?  We scan forward over a small
3952     // fixed window of instructions to handle common cases with conditions
3953     // computed between guards.
3954     Instruction *NextInst = II->getNextNode();
3955     for (unsigned i = 0; i < GuardWideningWindow; i++) {
3956       // Note: Using context-free form to avoid compile time blow up
3957       if (!isSafeToSpeculativelyExecute(NextInst))
3958         break;
3959       NextInst = NextInst->getNextNode();
3960     }
3961     Value *NextCond = nullptr;
3962     if (match(NextInst,
3963               m_Intrinsic<Intrinsic::experimental_guard>(m_Value(NextCond)))) {
3964       Value *CurrCond = II->getArgOperand(0);
3965 
3966       // Remove a guard that it is immediately preceded by an identical guard.
3967       if (CurrCond == NextCond)
3968         return eraseInstFromFunction(*NextInst);
3969 
3970       // Otherwise canonicalize guard(a); guard(b) -> guard(a & b).
3971       Instruction* MoveI = II->getNextNode();
3972       while (MoveI != NextInst) {
3973         auto *Temp = MoveI;
3974         MoveI = MoveI->getNextNode();
3975         Temp->moveBefore(II);
3976       }
3977       II->setArgOperand(0, Builder.CreateAnd(CurrCond, NextCond));
3978       return eraseInstFromFunction(*NextInst);
3979     }
3980     break;
3981   }
3982   }
3983   return visitCallSite(II);
3984 }
3985 
3986 // Fence instruction simplification
3987 Instruction *InstCombiner::visitFenceInst(FenceInst &FI) {
3988   // Remove identical consecutive fences.
3989   Instruction *Next = FI.getNextNonDebugInstruction();
3990   if (auto *NFI = dyn_cast<FenceInst>(Next))
3991     if (FI.isIdenticalTo(NFI))
3992       return eraseInstFromFunction(FI);
3993   return nullptr;
3994 }
3995 
3996 // InvokeInst simplification
3997 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3998   return visitCallSite(&II);
3999 }
4000 
4001 /// If this cast does not affect the value passed through the varargs area, we
4002 /// can eliminate the use of the cast.
4003 static bool isSafeToEliminateVarargsCast(const CallSite CS,
4004                                          const DataLayout &DL,
4005                                          const CastInst *const CI,
4006                                          const int ix) {
4007   if (!CI->isLosslessCast())
4008     return false;
4009 
4010   // If this is a GC intrinsic, avoid munging types.  We need types for
4011   // statepoint reconstruction in SelectionDAG.
4012   // TODO: This is probably something which should be expanded to all
4013   // intrinsics since the entire point of intrinsics is that
4014   // they are understandable by the optimizer.
4015   if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
4016     return false;
4017 
4018   // The size of ByVal or InAlloca arguments is derived from the type, so we
4019   // can't change to a type with a different size.  If the size were
4020   // passed explicitly we could avoid this check.
4021   if (!CS.isByValOrInAllocaArgument(ix))
4022     return true;
4023 
4024   Type* SrcTy =
4025             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
4026   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
4027   if (!SrcTy->isSized() || !DstTy->isSized())
4028     return false;
4029   if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
4030     return false;
4031   return true;
4032 }
4033 
4034 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
4035   if (!CI->getCalledFunction()) return nullptr;
4036 
4037   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
4038     replaceInstUsesWith(*From, With);
4039   };
4040   auto InstCombineErase = [this](Instruction *I) {
4041     eraseInstFromFunction(*I);
4042   };
4043   LibCallSimplifier Simplifier(DL, &TLI, ORE, InstCombineRAUW,
4044                                InstCombineErase);
4045   if (Value *With = Simplifier.optimizeCall(CI)) {
4046     ++NumSimplified;
4047     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
4048   }
4049 
4050   return nullptr;
4051 }
4052 
4053 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
4054   // Strip off at most one level of pointer casts, looking for an alloca.  This
4055   // is good enough in practice and simpler than handling any number of casts.
4056   Value *Underlying = TrampMem->stripPointerCasts();
4057   if (Underlying != TrampMem &&
4058       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
4059     return nullptr;
4060   if (!isa<AllocaInst>(Underlying))
4061     return nullptr;
4062 
4063   IntrinsicInst *InitTrampoline = nullptr;
4064   for (User *U : TrampMem->users()) {
4065     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
4066     if (!II)
4067       return nullptr;
4068     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
4069       if (InitTrampoline)
4070         // More than one init_trampoline writes to this value.  Give up.
4071         return nullptr;
4072       InitTrampoline = II;
4073       continue;
4074     }
4075     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
4076       // Allow any number of calls to adjust.trampoline.
4077       continue;
4078     return nullptr;
4079   }
4080 
4081   // No call to init.trampoline found.
4082   if (!InitTrampoline)
4083     return nullptr;
4084 
4085   // Check that the alloca is being used in the expected way.
4086   if (InitTrampoline->getOperand(0) != TrampMem)
4087     return nullptr;
4088 
4089   return InitTrampoline;
4090 }
4091 
4092 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
4093                                                Value *TrampMem) {
4094   // Visit all the previous instructions in the basic block, and try to find a
4095   // init.trampoline which has a direct path to the adjust.trampoline.
4096   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
4097                             E = AdjustTramp->getParent()->begin();
4098        I != E;) {
4099     Instruction *Inst = &*--I;
4100     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
4101       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
4102           II->getOperand(0) == TrampMem)
4103         return II;
4104     if (Inst->mayWriteToMemory())
4105       return nullptr;
4106   }
4107   return nullptr;
4108 }
4109 
4110 // Given a call to llvm.adjust.trampoline, find and return the corresponding
4111 // call to llvm.init.trampoline if the call to the trampoline can be optimized
4112 // to a direct call to a function.  Otherwise return NULL.
4113 static IntrinsicInst *findInitTrampoline(Value *Callee) {
4114   Callee = Callee->stripPointerCasts();
4115   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
4116   if (!AdjustTramp ||
4117       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
4118     return nullptr;
4119 
4120   Value *TrampMem = AdjustTramp->getOperand(0);
4121 
4122   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
4123     return IT;
4124   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
4125     return IT;
4126   return nullptr;
4127 }
4128 
4129 /// Improvements for call and invoke instructions.
4130 Instruction *InstCombiner::visitCallSite(CallSite CS) {
4131   if (isAllocLikeFn(CS.getInstruction(), &TLI))
4132     return visitAllocSite(*CS.getInstruction());
4133 
4134   bool Changed = false;
4135 
4136   // Mark any parameters that are known to be non-null with the nonnull
4137   // attribute.  This is helpful for inlining calls to functions with null
4138   // checks on their arguments.
4139   SmallVector<unsigned, 4> ArgNos;
4140   unsigned ArgNo = 0;
4141 
4142   for (Value *V : CS.args()) {
4143     if (V->getType()->isPointerTy() &&
4144         !CS.paramHasAttr(ArgNo, Attribute::NonNull) &&
4145         isKnownNonZero(V, DL, 0, &AC, CS.getInstruction(), &DT))
4146       ArgNos.push_back(ArgNo);
4147     ArgNo++;
4148   }
4149 
4150   assert(ArgNo == CS.arg_size() && "sanity check");
4151 
4152   if (!ArgNos.empty()) {
4153     AttributeList AS = CS.getAttributes();
4154     LLVMContext &Ctx = CS.getInstruction()->getContext();
4155     AS = AS.addParamAttribute(Ctx, ArgNos,
4156                               Attribute::get(Ctx, Attribute::NonNull));
4157     CS.setAttributes(AS);
4158     Changed = true;
4159   }
4160 
4161   // If the callee is a pointer to a function, attempt to move any casts to the
4162   // arguments of the call/invoke.
4163   Value *Callee = CS.getCalledValue();
4164   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
4165     return nullptr;
4166 
4167   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
4168     // Remove the convergent attr on calls when the callee is not convergent.
4169     if (CS.isConvergent() && !CalleeF->isConvergent() &&
4170         !CalleeF->isIntrinsic()) {
4171       LLVM_DEBUG(dbgs() << "Removing convergent attr from instr "
4172                         << CS.getInstruction() << "\n");
4173       CS.setNotConvergent();
4174       return CS.getInstruction();
4175     }
4176 
4177     // If the call and callee calling conventions don't match, this call must
4178     // be unreachable, as the call is undefined.
4179     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
4180         // Only do this for calls to a function with a body.  A prototype may
4181         // not actually end up matching the implementation's calling conv for a
4182         // variety of reasons (e.g. it may be written in assembly).
4183         !CalleeF->isDeclaration()) {
4184       Instruction *OldCall = CS.getInstruction();
4185       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4186                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
4187                                   OldCall);
4188       // If OldCall does not return void then replaceAllUsesWith undef.
4189       // This allows ValueHandlers and custom metadata to adjust itself.
4190       if (!OldCall->getType()->isVoidTy())
4191         replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
4192       if (isa<CallInst>(OldCall))
4193         return eraseInstFromFunction(*OldCall);
4194 
4195       // We cannot remove an invoke, because it would change the CFG, just
4196       // change the callee to a null pointer.
4197       cast<InvokeInst>(OldCall)->setCalledFunction(
4198                                     Constant::getNullValue(CalleeF->getType()));
4199       return nullptr;
4200     }
4201   }
4202 
4203   if ((isa<ConstantPointerNull>(Callee) &&
4204        !NullPointerIsDefined(CS.getInstruction()->getFunction())) ||
4205       isa<UndefValue>(Callee)) {
4206     // If CS does not return void then replaceAllUsesWith undef.
4207     // This allows ValueHandlers and custom metadata to adjust itself.
4208     if (!CS.getInstruction()->getType()->isVoidTy())
4209       replaceInstUsesWith(*CS.getInstruction(),
4210                           UndefValue::get(CS.getInstruction()->getType()));
4211 
4212     if (isa<InvokeInst>(CS.getInstruction())) {
4213       // Can't remove an invoke because we cannot change the CFG.
4214       return nullptr;
4215     }
4216 
4217     // This instruction is not reachable, just remove it.  We insert a store to
4218     // undef so that we know that this code is not reachable, despite the fact
4219     // that we can't modify the CFG here.
4220     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
4221                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
4222                   CS.getInstruction());
4223 
4224     return eraseInstFromFunction(*CS.getInstruction());
4225   }
4226 
4227   if (IntrinsicInst *II = findInitTrampoline(Callee))
4228     return transformCallThroughTrampoline(CS, II);
4229 
4230   PointerType *PTy = cast<PointerType>(Callee->getType());
4231   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4232   if (FTy->isVarArg()) {
4233     int ix = FTy->getNumParams();
4234     // See if we can optimize any arguments passed through the varargs area of
4235     // the call.
4236     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
4237            E = CS.arg_end(); I != E; ++I, ++ix) {
4238       CastInst *CI = dyn_cast<CastInst>(*I);
4239       if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
4240         *I = CI->getOperand(0);
4241         Changed = true;
4242       }
4243     }
4244   }
4245 
4246   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
4247     // Inline asm calls cannot throw - mark them 'nounwind'.
4248     CS.setDoesNotThrow();
4249     Changed = true;
4250   }
4251 
4252   // Try to optimize the call if possible, we require DataLayout for most of
4253   // this.  None of these calls are seen as possibly dead so go ahead and
4254   // delete the instruction now.
4255   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
4256     Instruction *I = tryOptimizeCall(CI);
4257     // If we changed something return the result, etc. Otherwise let
4258     // the fallthrough check.
4259     if (I) return eraseInstFromFunction(*I);
4260   }
4261 
4262   return Changed ? CS.getInstruction() : nullptr;
4263 }
4264 
4265 /// If the callee is a constexpr cast of a function, attempt to move the cast to
4266 /// the arguments of the call/invoke.
4267 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4268   auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
4269   if (!Callee)
4270     return false;
4271 
4272   // If this is a call to a thunk function, don't remove the cast. Thunks are
4273   // used to transparently forward all incoming parameters and outgoing return
4274   // values, so it's important to leave the cast in place.
4275   if (Callee->hasFnAttribute("thunk"))
4276     return false;
4277 
4278   // If this is a musttail call, the callee's prototype must match the caller's
4279   // prototype with the exception of pointee types. The code below doesn't
4280   // implement that, so we can't do this transform.
4281   // TODO: Do the transform if it only requires adding pointer casts.
4282   if (CS.isMustTailCall())
4283     return false;
4284 
4285   Instruction *Caller = CS.getInstruction();
4286   const AttributeList &CallerPAL = CS.getAttributes();
4287 
4288   // Okay, this is a cast from a function to a different type.  Unless doing so
4289   // would cause a type conversion of one of our arguments, change this call to
4290   // be a direct call with arguments casted to the appropriate types.
4291   FunctionType *FT = Callee->getFunctionType();
4292   Type *OldRetTy = Caller->getType();
4293   Type *NewRetTy = FT->getReturnType();
4294 
4295   // Check to see if we are changing the return type...
4296   if (OldRetTy != NewRetTy) {
4297 
4298     if (NewRetTy->isStructTy())
4299       return false; // TODO: Handle multiple return values.
4300 
4301     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
4302       if (Callee->isDeclaration())
4303         return false;   // Cannot transform this return value.
4304 
4305       if (!Caller->use_empty() &&
4306           // void -> non-void is handled specially
4307           !NewRetTy->isVoidTy())
4308         return false;   // Cannot transform this return value.
4309     }
4310 
4311     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
4312       AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
4313       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
4314         return false;   // Attribute not compatible with transformed value.
4315     }
4316 
4317     // If the callsite is an invoke instruction, and the return value is used by
4318     // a PHI node in a successor, we cannot change the return type of the call
4319     // because there is no place to put the cast instruction (without breaking
4320     // the critical edge).  Bail out in this case.
4321     if (!Caller->use_empty())
4322       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4323         for (User *U : II->users())
4324           if (PHINode *PN = dyn_cast<PHINode>(U))
4325             if (PN->getParent() == II->getNormalDest() ||
4326                 PN->getParent() == II->getUnwindDest())
4327               return false;
4328   }
4329 
4330   unsigned NumActualArgs = CS.arg_size();
4331   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4332 
4333   // Prevent us turning:
4334   // declare void @takes_i32_inalloca(i32* inalloca)
4335   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
4336   //
4337   // into:
4338   //  call void @takes_i32_inalloca(i32* null)
4339   //
4340   //  Similarly, avoid folding away bitcasts of byval calls.
4341   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
4342       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
4343     return false;
4344 
4345   CallSite::arg_iterator AI = CS.arg_begin();
4346   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4347     Type *ParamTy = FT->getParamType(i);
4348     Type *ActTy = (*AI)->getType();
4349 
4350     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
4351       return false;   // Cannot transform this parameter value.
4352 
4353     if (AttrBuilder(CallerPAL.getParamAttributes(i))
4354             .overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
4355       return false;   // Attribute not compatible with transformed value.
4356 
4357     if (CS.isInAllocaArgument(i))
4358       return false;   // Cannot transform to and from inalloca.
4359 
4360     // If the parameter is passed as a byval argument, then we have to have a
4361     // sized type and the sized type has to have the same size as the old type.
4362     if (ParamTy != ActTy && CallerPAL.hasParamAttribute(i, Attribute::ByVal)) {
4363       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
4364       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
4365         return false;
4366 
4367       Type *CurElTy = ActTy->getPointerElementType();
4368       if (DL.getTypeAllocSize(CurElTy) !=
4369           DL.getTypeAllocSize(ParamPTy->getElementType()))
4370         return false;
4371     }
4372   }
4373 
4374   if (Callee->isDeclaration()) {
4375     // Do not delete arguments unless we have a function body.
4376     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
4377       return false;
4378 
4379     // If the callee is just a declaration, don't change the varargsness of the
4380     // call.  We don't want to introduce a varargs call where one doesn't
4381     // already exist.
4382     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
4383     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
4384       return false;
4385 
4386     // If both the callee and the cast type are varargs, we still have to make
4387     // sure the number of fixed parameters are the same or we have the same
4388     // ABI issues as if we introduce a varargs call.
4389     if (FT->isVarArg() &&
4390         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
4391         FT->getNumParams() !=
4392         cast<FunctionType>(APTy->getElementType())->getNumParams())
4393       return false;
4394   }
4395 
4396   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
4397       !CallerPAL.isEmpty()) {
4398     // In this case we have more arguments than the new function type, but we
4399     // won't be dropping them.  Check that these extra arguments have attributes
4400     // that are compatible with being a vararg call argument.
4401     unsigned SRetIdx;
4402     if (CallerPAL.hasAttrSomewhere(Attribute::StructRet, &SRetIdx) &&
4403         SRetIdx > FT->getNumParams())
4404       return false;
4405   }
4406 
4407   // Okay, we decided that this is a safe thing to do: go ahead and start
4408   // inserting cast instructions as necessary.
4409   SmallVector<Value *, 8> Args;
4410   SmallVector<AttributeSet, 8> ArgAttrs;
4411   Args.reserve(NumActualArgs);
4412   ArgAttrs.reserve(NumActualArgs);
4413 
4414   // Get any return attributes.
4415   AttrBuilder RAttrs(CallerPAL, AttributeList::ReturnIndex);
4416 
4417   // If the return value is not being used, the type may not be compatible
4418   // with the existing attributes.  Wipe out any problematic attributes.
4419   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
4420 
4421   AI = CS.arg_begin();
4422   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4423     Type *ParamTy = FT->getParamType(i);
4424 
4425     Value *NewArg = *AI;
4426     if ((*AI)->getType() != ParamTy)
4427       NewArg = Builder.CreateBitOrPointerCast(*AI, ParamTy);
4428     Args.push_back(NewArg);
4429 
4430     // Add any parameter attributes.
4431     ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4432   }
4433 
4434   // If the function takes more arguments than the call was taking, add them
4435   // now.
4436   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i) {
4437     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4438     ArgAttrs.push_back(AttributeSet());
4439   }
4440 
4441   // If we are removing arguments to the function, emit an obnoxious warning.
4442   if (FT->getNumParams() < NumActualArgs) {
4443     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
4444     if (FT->isVarArg()) {
4445       // Add all of the arguments in their promoted form to the arg list.
4446       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4447         Type *PTy = getPromotedType((*AI)->getType());
4448         Value *NewArg = *AI;
4449         if (PTy != (*AI)->getType()) {
4450           // Must promote to pass through va_arg area!
4451           Instruction::CastOps opcode =
4452             CastInst::getCastOpcode(*AI, false, PTy, false);
4453           NewArg = Builder.CreateCast(opcode, *AI, PTy);
4454         }
4455         Args.push_back(NewArg);
4456 
4457         // Add any parameter attributes.
4458         ArgAttrs.push_back(CallerPAL.getParamAttributes(i));
4459       }
4460     }
4461   }
4462 
4463   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
4464 
4465   if (NewRetTy->isVoidTy())
4466     Caller->setName("");   // Void type should not have a name.
4467 
4468   assert((ArgAttrs.size() == FT->getNumParams() || FT->isVarArg()) &&
4469          "missing argument attributes");
4470   LLVMContext &Ctx = Callee->getContext();
4471   AttributeList NewCallerPAL = AttributeList::get(
4472       Ctx, FnAttrs, AttributeSet::get(Ctx, RAttrs), ArgAttrs);
4473 
4474   SmallVector<OperandBundleDef, 1> OpBundles;
4475   CS.getOperandBundlesAsDefs(OpBundles);
4476 
4477   CallSite NewCS;
4478   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4479     NewCS = Builder.CreateInvoke(Callee, II->getNormalDest(),
4480                                  II->getUnwindDest(), Args, OpBundles);
4481   } else {
4482     NewCS = Builder.CreateCall(Callee, Args, OpBundles);
4483     cast<CallInst>(NewCS.getInstruction())
4484         ->setTailCallKind(cast<CallInst>(Caller)->getTailCallKind());
4485   }
4486   NewCS->takeName(Caller);
4487   NewCS.setCallingConv(CS.getCallingConv());
4488   NewCS.setAttributes(NewCallerPAL);
4489 
4490   // Preserve the weight metadata for the new call instruction. The metadata
4491   // is used by SamplePGO to check callsite's hotness.
4492   uint64_t W;
4493   if (Caller->extractProfTotalWeight(W))
4494     NewCS->setProfWeight(W);
4495 
4496   // Insert a cast of the return type as necessary.
4497   Instruction *NC = NewCS.getInstruction();
4498   Value *NV = NC;
4499   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
4500     if (!NV->getType()->isVoidTy()) {
4501       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
4502       NC->setDebugLoc(Caller->getDebugLoc());
4503 
4504       // If this is an invoke instruction, we should insert it after the first
4505       // non-phi, instruction in the normal successor block.
4506       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4507         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
4508         InsertNewInstBefore(NC, *I);
4509       } else {
4510         // Otherwise, it's a call, just insert cast right after the call.
4511         InsertNewInstBefore(NC, *Caller);
4512       }
4513       Worklist.AddUsersToWorkList(*Caller);
4514     } else {
4515       NV = UndefValue::get(Caller->getType());
4516     }
4517   }
4518 
4519   if (!Caller->use_empty())
4520     replaceInstUsesWith(*Caller, NV);
4521   else if (Caller->hasValueHandle()) {
4522     if (OldRetTy == NV->getType())
4523       ValueHandleBase::ValueIsRAUWd(Caller, NV);
4524     else
4525       // We cannot call ValueIsRAUWd with a different type, and the
4526       // actual tracked value will disappear.
4527       ValueHandleBase::ValueIsDeleted(Caller);
4528   }
4529 
4530   eraseInstFromFunction(*Caller);
4531   return true;
4532 }
4533 
4534 /// Turn a call to a function created by init_trampoline / adjust_trampoline
4535 /// intrinsic pair into a direct call to the underlying function.
4536 Instruction *
4537 InstCombiner::transformCallThroughTrampoline(CallSite CS,
4538                                              IntrinsicInst *Tramp) {
4539   Value *Callee = CS.getCalledValue();
4540   PointerType *PTy = cast<PointerType>(Callee->getType());
4541   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4542   AttributeList Attrs = CS.getAttributes();
4543 
4544   // If the call already has the 'nest' attribute somewhere then give up -
4545   // otherwise 'nest' would occur twice after splicing in the chain.
4546   if (Attrs.hasAttrSomewhere(Attribute::Nest))
4547     return nullptr;
4548 
4549   assert(Tramp &&
4550          "transformCallThroughTrampoline called with incorrect CallSite.");
4551 
4552   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
4553   FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
4554 
4555   AttributeList NestAttrs = NestF->getAttributes();
4556   if (!NestAttrs.isEmpty()) {
4557     unsigned NestArgNo = 0;
4558     Type *NestTy = nullptr;
4559     AttributeSet NestAttr;
4560 
4561     // Look for a parameter marked with the 'nest' attribute.
4562     for (FunctionType::param_iterator I = NestFTy->param_begin(),
4563                                       E = NestFTy->param_end();
4564          I != E; ++NestArgNo, ++I) {
4565       AttributeSet AS = NestAttrs.getParamAttributes(NestArgNo);
4566       if (AS.hasAttribute(Attribute::Nest)) {
4567         // Record the parameter type and any other attributes.
4568         NestTy = *I;
4569         NestAttr = AS;
4570         break;
4571       }
4572     }
4573 
4574     if (NestTy) {
4575       Instruction *Caller = CS.getInstruction();
4576       std::vector<Value*> NewArgs;
4577       std::vector<AttributeSet> NewArgAttrs;
4578       NewArgs.reserve(CS.arg_size() + 1);
4579       NewArgAttrs.reserve(CS.arg_size());
4580 
4581       // Insert the nest argument into the call argument list, which may
4582       // mean appending it.  Likewise for attributes.
4583 
4584       {
4585         unsigned ArgNo = 0;
4586         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
4587         do {
4588           if (ArgNo == NestArgNo) {
4589             // Add the chain argument and attributes.
4590             Value *NestVal = Tramp->getArgOperand(2);
4591             if (NestVal->getType() != NestTy)
4592               NestVal = Builder.CreateBitCast(NestVal, NestTy, "nest");
4593             NewArgs.push_back(NestVal);
4594             NewArgAttrs.push_back(NestAttr);
4595           }
4596 
4597           if (I == E)
4598             break;
4599 
4600           // Add the original argument and attributes.
4601           NewArgs.push_back(*I);
4602           NewArgAttrs.push_back(Attrs.getParamAttributes(ArgNo));
4603 
4604           ++ArgNo;
4605           ++I;
4606         } while (true);
4607       }
4608 
4609       // The trampoline may have been bitcast to a bogus type (FTy).
4610       // Handle this by synthesizing a new function type, equal to FTy
4611       // with the chain parameter inserted.
4612 
4613       std::vector<Type*> NewTypes;
4614       NewTypes.reserve(FTy->getNumParams()+1);
4615 
4616       // Insert the chain's type into the list of parameter types, which may
4617       // mean appending it.
4618       {
4619         unsigned ArgNo = 0;
4620         FunctionType::param_iterator I = FTy->param_begin(),
4621           E = FTy->param_end();
4622 
4623         do {
4624           if (ArgNo == NestArgNo)
4625             // Add the chain's type.
4626             NewTypes.push_back(NestTy);
4627 
4628           if (I == E)
4629             break;
4630 
4631           // Add the original type.
4632           NewTypes.push_back(*I);
4633 
4634           ++ArgNo;
4635           ++I;
4636         } while (true);
4637       }
4638 
4639       // Replace the trampoline call with a direct call.  Let the generic
4640       // code sort out any function type mismatches.
4641       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
4642                                                 FTy->isVarArg());
4643       Constant *NewCallee =
4644         NestF->getType() == PointerType::getUnqual(NewFTy) ?
4645         NestF : ConstantExpr::getBitCast(NestF,
4646                                          PointerType::getUnqual(NewFTy));
4647       AttributeList NewPAL =
4648           AttributeList::get(FTy->getContext(), Attrs.getFnAttributes(),
4649                              Attrs.getRetAttributes(), NewArgAttrs);
4650 
4651       SmallVector<OperandBundleDef, 1> OpBundles;
4652       CS.getOperandBundlesAsDefs(OpBundles);
4653 
4654       Instruction *NewCaller;
4655       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4656         NewCaller = InvokeInst::Create(NewCallee,
4657                                        II->getNormalDest(), II->getUnwindDest(),
4658                                        NewArgs, OpBundles);
4659         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
4660         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
4661       } else {
4662         NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
4663         cast<CallInst>(NewCaller)->setTailCallKind(
4664             cast<CallInst>(Caller)->getTailCallKind());
4665         cast<CallInst>(NewCaller)->setCallingConv(
4666             cast<CallInst>(Caller)->getCallingConv());
4667         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
4668       }
4669       NewCaller->setDebugLoc(Caller->getDebugLoc());
4670 
4671       return NewCaller;
4672     }
4673   }
4674 
4675   // Replace the trampoline call with a direct call.  Since there is no 'nest'
4676   // parameter, there is no need to adjust the argument list.  Let the generic
4677   // code sort out any function type mismatches.
4678   Constant *NewCallee =
4679     NestF->getType() == PTy ? NestF :
4680                               ConstantExpr::getBitCast(NestF, PTy);
4681   CS.setCalledFunction(NewCallee);
4682   return CS.getInstruction();
4683 }
4684