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