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 /// Return the specified type promoted as it would be to pass though a va_arg
64 /// area.
65 static Type *getPromotedType(Type *Ty) {
66   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
67     if (ITy->getBitWidth() < 32)
68       return Type::getInt32Ty(Ty->getContext());
69   }
70   return Ty;
71 }
72 
73 /// Given an aggregate type which ultimately holds a single scalar element,
74 /// like {{{type}}} or [1 x type], return type.
75 static Type *reduceToSingleValueType(Type *T) {
76   while (!T->isSingleValueType()) {
77     if (StructType *STy = dyn_cast<StructType>(T)) {
78       if (STy->getNumElements() == 1)
79         T = STy->getElementType(0);
80       else
81         break;
82     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
83       if (ATy->getNumElements() == 1)
84         T = ATy->getElementType();
85       else
86         break;
87     } else
88       break;
89   }
90 
91   return T;
92 }
93 
94 /// Return a constant boolean vector that has true elements in all positions
95 /// where the input constant data vector has an element with the sign bit set.
96 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
97   SmallVector<Constant *, 32> BoolVec;
98   IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
99   for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
100     Constant *Elt = V->getElementAsConstant(I);
101     assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
102            "Unexpected constant data vector element type");
103     bool Sign = V->getElementType()->isIntegerTy()
104                     ? cast<ConstantInt>(Elt)->isNegative()
105                     : cast<ConstantFP>(Elt)->isNegative();
106     BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
107   }
108   return ConstantVector::get(BoolVec);
109 }
110 
111 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
112   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, &AC, &DT);
113   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, &AC, &DT);
114   unsigned MinAlign = std::min(DstAlign, SrcAlign);
115   unsigned CopyAlign = MI->getAlignment();
116 
117   if (CopyAlign < MinAlign) {
118     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
119     return MI;
120   }
121 
122   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
123   // load/store.
124   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
125   if (!MemOpLength) return nullptr;
126 
127   // Source and destination pointer types are always "i8*" for intrinsic.  See
128   // if the size is something we can handle with a single primitive load/store.
129   // A single load+store correctly handles overlapping memory in the memmove
130   // case.
131   uint64_t Size = MemOpLength->getLimitedValue();
132   assert(Size && "0-sized memory transferring should be removed already.");
133 
134   if (Size > 8 || (Size&(Size-1)))
135     return nullptr;  // If not 1/2/4/8 bytes, exit.
136 
137   // Use an integer load+store unless we can find something better.
138   unsigned SrcAddrSp =
139     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
140   unsigned DstAddrSp =
141     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
142 
143   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
144   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
145   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
146 
147   // Memcpy forces the use of i8* for the source and destination.  That means
148   // that if you're using memcpy to move one double around, you'll get a cast
149   // from double* to i8*.  We'd much rather use a double load+store rather than
150   // an i64 load+store, here because this improves the odds that the source or
151   // dest address will be promotable.  See if we can find a better type than the
152   // integer datatype.
153   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
154   MDNode *CopyMD = nullptr;
155   if (StrippedDest != MI->getArgOperand(0)) {
156     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
157                                     ->getElementType();
158     if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
159       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
160       // down through these levels if so.
161       SrcETy = reduceToSingleValueType(SrcETy);
162 
163       if (SrcETy->isSingleValueType()) {
164         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
165         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
166 
167         // If the memcpy has metadata describing the members, see if we can
168         // get the TBAA tag describing our copy.
169         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
170           if (M->getNumOperands() == 3 && M->getOperand(0) &&
171               mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
172               mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
173               M->getOperand(1) &&
174               mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
175               mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
176                   Size &&
177               M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
178             CopyMD = cast<MDNode>(M->getOperand(2));
179         }
180       }
181     }
182   }
183 
184   // If the memcpy/memmove provides better alignment info than we can
185   // infer, use it.
186   SrcAlign = std::max(SrcAlign, CopyAlign);
187   DstAlign = std::max(DstAlign, CopyAlign);
188 
189   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
190   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
191   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
192   L->setAlignment(SrcAlign);
193   if (CopyMD)
194     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
195   MDNode *LoopMemParallelMD =
196     MI->getMetadata(LLVMContext::MD_mem_parallel_loop_access);
197   if (LoopMemParallelMD)
198     L->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
199 
200   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
201   S->setAlignment(DstAlign);
202   if (CopyMD)
203     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
204   if (LoopMemParallelMD)
205     S->setMetadata(LLVMContext::MD_mem_parallel_loop_access, LoopMemParallelMD);
206 
207   // Set the size of the copy to 0, it will be deleted on the next iteration.
208   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
209   return MI;
210 }
211 
212 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
213   unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, &AC, &DT);
214   if (MI->getAlignment() < Alignment) {
215     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
216                                              Alignment, false));
217     return MI;
218   }
219 
220   // Extract the length and alignment and fill if they are constant.
221   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
222   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
223   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
224     return nullptr;
225   uint64_t Len = LenC->getLimitedValue();
226   Alignment = MI->getAlignment();
227   assert(Len && "0-sized memory setting should be removed already.");
228 
229   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
230   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
231     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
232 
233     Value *Dest = MI->getDest();
234     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
235     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
236     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
237 
238     // Alignment 0 is identity for alignment 1 for memset, but not store.
239     if (Alignment == 0) Alignment = 1;
240 
241     // Extract the fill value and store.
242     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
243     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
244                                         MI->isVolatile());
245     S->setAlignment(Alignment);
246 
247     // Set the size of the copy to 0, it will be deleted on the next iteration.
248     MI->setLength(Constant::getNullValue(LenC->getType()));
249     return MI;
250   }
251 
252   return nullptr;
253 }
254 
255 static Value *simplifyX86immShift(const IntrinsicInst &II,
256                                   InstCombiner::BuilderTy &Builder) {
257   bool LogicalShift = false;
258   bool ShiftLeft = false;
259 
260   switch (II.getIntrinsicID()) {
261   default: llvm_unreachable("Unexpected intrinsic!");
262   case Intrinsic::x86_sse2_psra_d:
263   case Intrinsic::x86_sse2_psra_w:
264   case Intrinsic::x86_sse2_psrai_d:
265   case Intrinsic::x86_sse2_psrai_w:
266   case Intrinsic::x86_avx2_psra_d:
267   case Intrinsic::x86_avx2_psra_w:
268   case Intrinsic::x86_avx2_psrai_d:
269   case Intrinsic::x86_avx2_psrai_w:
270   case Intrinsic::x86_avx512_psra_q_128:
271   case Intrinsic::x86_avx512_psrai_q_128:
272   case Intrinsic::x86_avx512_psra_q_256:
273   case Intrinsic::x86_avx512_psrai_q_256:
274   case Intrinsic::x86_avx512_psra_d_512:
275   case Intrinsic::x86_avx512_psra_q_512:
276   case Intrinsic::x86_avx512_psra_w_512:
277   case Intrinsic::x86_avx512_psrai_d_512:
278   case Intrinsic::x86_avx512_psrai_q_512:
279   case Intrinsic::x86_avx512_psrai_w_512:
280     LogicalShift = false; ShiftLeft = false;
281     break;
282   case Intrinsic::x86_sse2_psrl_d:
283   case Intrinsic::x86_sse2_psrl_q:
284   case Intrinsic::x86_sse2_psrl_w:
285   case Intrinsic::x86_sse2_psrli_d:
286   case Intrinsic::x86_sse2_psrli_q:
287   case Intrinsic::x86_sse2_psrli_w:
288   case Intrinsic::x86_avx2_psrl_d:
289   case Intrinsic::x86_avx2_psrl_q:
290   case Intrinsic::x86_avx2_psrl_w:
291   case Intrinsic::x86_avx2_psrli_d:
292   case Intrinsic::x86_avx2_psrli_q:
293   case Intrinsic::x86_avx2_psrli_w:
294   case Intrinsic::x86_avx512_psrl_d_512:
295   case Intrinsic::x86_avx512_psrl_q_512:
296   case Intrinsic::x86_avx512_psrl_w_512:
297   case Intrinsic::x86_avx512_psrli_d_512:
298   case Intrinsic::x86_avx512_psrli_q_512:
299   case Intrinsic::x86_avx512_psrli_w_512:
300     LogicalShift = true; ShiftLeft = false;
301     break;
302   case Intrinsic::x86_sse2_psll_d:
303   case Intrinsic::x86_sse2_psll_q:
304   case Intrinsic::x86_sse2_psll_w:
305   case Intrinsic::x86_sse2_pslli_d:
306   case Intrinsic::x86_sse2_pslli_q:
307   case Intrinsic::x86_sse2_pslli_w:
308   case Intrinsic::x86_avx2_psll_d:
309   case Intrinsic::x86_avx2_psll_q:
310   case Intrinsic::x86_avx2_psll_w:
311   case Intrinsic::x86_avx2_pslli_d:
312   case Intrinsic::x86_avx2_pslli_q:
313   case Intrinsic::x86_avx2_pslli_w:
314   case Intrinsic::x86_avx512_psll_d_512:
315   case Intrinsic::x86_avx512_psll_q_512:
316   case Intrinsic::x86_avx512_psll_w_512:
317   case Intrinsic::x86_avx512_pslli_d_512:
318   case Intrinsic::x86_avx512_pslli_q_512:
319   case Intrinsic::x86_avx512_pslli_w_512:
320     LogicalShift = true; ShiftLeft = true;
321     break;
322   }
323   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
324 
325   // Simplify if count is constant.
326   auto Arg1 = II.getArgOperand(1);
327   auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
328   auto CDV = dyn_cast<ConstantDataVector>(Arg1);
329   auto CInt = dyn_cast<ConstantInt>(Arg1);
330   if (!CAZ && !CDV && !CInt)
331     return nullptr;
332 
333   APInt Count(64, 0);
334   if (CDV) {
335     // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
336     // operand to compute the shift amount.
337     auto VT = cast<VectorType>(CDV->getType());
338     unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
339     assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
340     unsigned NumSubElts = 64 / BitWidth;
341 
342     // Concatenate the sub-elements to create the 64-bit value.
343     for (unsigned i = 0; i != NumSubElts; ++i) {
344       unsigned SubEltIdx = (NumSubElts - 1) - i;
345       auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
346       Count = Count.shl(BitWidth);
347       Count |= SubElt->getValue().zextOrTrunc(64);
348     }
349   }
350   else if (CInt)
351     Count = CInt->getValue();
352 
353   auto Vec = II.getArgOperand(0);
354   auto VT = cast<VectorType>(Vec->getType());
355   auto SVT = VT->getElementType();
356   unsigned VWidth = VT->getNumElements();
357   unsigned BitWidth = SVT->getPrimitiveSizeInBits();
358 
359   // If shift-by-zero then just return the original value.
360   if (Count == 0)
361     return Vec;
362 
363   // Handle cases when Shift >= BitWidth.
364   if (Count.uge(BitWidth)) {
365     // If LogicalShift - just return zero.
366     if (LogicalShift)
367       return ConstantAggregateZero::get(VT);
368 
369     // If ArithmeticShift - clamp Shift to (BitWidth - 1).
370     Count = APInt(64, BitWidth - 1);
371   }
372 
373   // Get a constant vector of the same type as the first operand.
374   auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
375   auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
376 
377   if (ShiftLeft)
378     return Builder.CreateShl(Vec, ShiftVec);
379 
380   if (LogicalShift)
381     return Builder.CreateLShr(Vec, ShiftVec);
382 
383   return Builder.CreateAShr(Vec, ShiftVec);
384 }
385 
386 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
387 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out
388 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
389 static Value *simplifyX86varShift(const IntrinsicInst &II,
390                                   InstCombiner::BuilderTy &Builder) {
391   bool LogicalShift = false;
392   bool ShiftLeft = false;
393 
394   switch (II.getIntrinsicID()) {
395   default: llvm_unreachable("Unexpected intrinsic!");
396   case Intrinsic::x86_avx2_psrav_d:
397   case Intrinsic::x86_avx2_psrav_d_256:
398   case Intrinsic::x86_avx512_psrav_q_128:
399   case Intrinsic::x86_avx512_psrav_q_256:
400   case Intrinsic::x86_avx512_psrav_d_512:
401   case Intrinsic::x86_avx512_psrav_q_512:
402   case Intrinsic::x86_avx512_psrav_w_128:
403   case Intrinsic::x86_avx512_psrav_w_256:
404   case Intrinsic::x86_avx512_psrav_w_512:
405     LogicalShift = false;
406     ShiftLeft = false;
407     break;
408   case Intrinsic::x86_avx2_psrlv_d:
409   case Intrinsic::x86_avx2_psrlv_d_256:
410   case Intrinsic::x86_avx2_psrlv_q:
411   case Intrinsic::x86_avx2_psrlv_q_256:
412   case Intrinsic::x86_avx512_psrlv_d_512:
413   case Intrinsic::x86_avx512_psrlv_q_512:
414   case Intrinsic::x86_avx512_psrlv_w_128:
415   case Intrinsic::x86_avx512_psrlv_w_256:
416   case Intrinsic::x86_avx512_psrlv_w_512:
417     LogicalShift = true;
418     ShiftLeft = false;
419     break;
420   case Intrinsic::x86_avx2_psllv_d:
421   case Intrinsic::x86_avx2_psllv_d_256:
422   case Intrinsic::x86_avx2_psllv_q:
423   case Intrinsic::x86_avx2_psllv_q_256:
424   case Intrinsic::x86_avx512_psllv_d_512:
425   case Intrinsic::x86_avx512_psllv_q_512:
426   case Intrinsic::x86_avx512_psllv_w_128:
427   case Intrinsic::x86_avx512_psllv_w_256:
428   case Intrinsic::x86_avx512_psllv_w_512:
429     LogicalShift = true;
430     ShiftLeft = true;
431     break;
432   }
433   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
434 
435   // Simplify if all shift amounts are constant/undef.
436   auto *CShift = dyn_cast<Constant>(II.getArgOperand(1));
437   if (!CShift)
438     return nullptr;
439 
440   auto Vec = II.getArgOperand(0);
441   auto VT = cast<VectorType>(II.getType());
442   auto SVT = VT->getVectorElementType();
443   int NumElts = VT->getNumElements();
444   int BitWidth = SVT->getIntegerBitWidth();
445 
446   // Collect each element's shift amount.
447   // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
448   bool AnyOutOfRange = false;
449   SmallVector<int, 8> ShiftAmts;
450   for (int I = 0; I < NumElts; ++I) {
451     auto *CElt = CShift->getAggregateElement(I);
452     if (CElt && isa<UndefValue>(CElt)) {
453       ShiftAmts.push_back(-1);
454       continue;
455     }
456 
457     auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
458     if (!COp)
459       return nullptr;
460 
461     // Handle out of range shifts.
462     // If LogicalShift - set to BitWidth (special case).
463     // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
464     APInt ShiftVal = COp->getValue();
465     if (ShiftVal.uge(BitWidth)) {
466       AnyOutOfRange = LogicalShift;
467       ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
468       continue;
469     }
470 
471     ShiftAmts.push_back((int)ShiftVal.getZExtValue());
472   }
473 
474   // If all elements out of range or UNDEF, return vector of zeros/undefs.
475   // ArithmeticShift should only hit this if they are all UNDEF.
476   auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
477   if (all_of(ShiftAmts, OutOfRange)) {
478     SmallVector<Constant *, 8> ConstantVec;
479     for (int Idx : ShiftAmts) {
480       if (Idx < 0) {
481         ConstantVec.push_back(UndefValue::get(SVT));
482       } else {
483         assert(LogicalShift && "Logical shift expected");
484         ConstantVec.push_back(ConstantInt::getNullValue(SVT));
485       }
486     }
487     return ConstantVector::get(ConstantVec);
488   }
489 
490   // We can't handle only some out of range values with generic logical shifts.
491   if (AnyOutOfRange)
492     return nullptr;
493 
494   // Build the shift amount constant vector.
495   SmallVector<Constant *, 8> ShiftVecAmts;
496   for (int Idx : ShiftAmts) {
497     if (Idx < 0)
498       ShiftVecAmts.push_back(UndefValue::get(SVT));
499     else
500       ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
501   }
502   auto ShiftVec = ConstantVector::get(ShiftVecAmts);
503 
504   if (ShiftLeft)
505     return Builder.CreateShl(Vec, ShiftVec);
506 
507   if (LogicalShift)
508     return Builder.CreateLShr(Vec, ShiftVec);
509 
510   return Builder.CreateAShr(Vec, ShiftVec);
511 }
512 
513 static Value *simplifyX86movmsk(const IntrinsicInst &II,
514                                 InstCombiner::BuilderTy &Builder) {
515   Value *Arg = II.getArgOperand(0);
516   Type *ResTy = II.getType();
517   Type *ArgTy = Arg->getType();
518 
519   // movmsk(undef) -> zero as we must ensure the upper bits are zero.
520   if (isa<UndefValue>(Arg))
521     return Constant::getNullValue(ResTy);
522 
523   // We can't easily peek through x86_mmx types.
524   if (!ArgTy->isVectorTy())
525     return nullptr;
526 
527   auto *C = dyn_cast<Constant>(Arg);
528   if (!C)
529     return nullptr;
530 
531   // Extract signbits of the vector input and pack into integer result.
532   APInt Result(ResTy->getPrimitiveSizeInBits(), 0);
533   for (unsigned I = 0, E = ArgTy->getVectorNumElements(); I != E; ++I) {
534     auto *COp = C->getAggregateElement(I);
535     if (!COp)
536       return nullptr;
537     if (isa<UndefValue>(COp))
538       continue;
539 
540     auto *CInt = dyn_cast<ConstantInt>(COp);
541     auto *CFp = dyn_cast<ConstantFP>(COp);
542     if (!CInt && !CFp)
543       return nullptr;
544 
545     if ((CInt && CInt->isNegative()) || (CFp && CFp->isNegative()))
546       Result.setBit(I);
547   }
548 
549   return Constant::getIntegerValue(ResTy, Result);
550 }
551 
552 static Value *simplifyX86insertps(const IntrinsicInst &II,
553                                   InstCombiner::BuilderTy &Builder) {
554   auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
555   if (!CInt)
556     return nullptr;
557 
558   VectorType *VecTy = cast<VectorType>(II.getType());
559   assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
560 
561   // The immediate permute control byte looks like this:
562   //    [3:0] - zero mask for each 32-bit lane
563   //    [5:4] - select one 32-bit destination lane
564   //    [7:6] - select one 32-bit source lane
565 
566   uint8_t Imm = CInt->getZExtValue();
567   uint8_t ZMask = Imm & 0xf;
568   uint8_t DestLane = (Imm >> 4) & 0x3;
569   uint8_t SourceLane = (Imm >> 6) & 0x3;
570 
571   ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
572 
573   // If all zero mask bits are set, this was just a weird way to
574   // generate a zero vector.
575   if (ZMask == 0xf)
576     return ZeroVector;
577 
578   // Initialize by passing all of the first source bits through.
579   uint32_t ShuffleMask[4] = { 0, 1, 2, 3 };
580 
581   // We may replace the second operand with the zero vector.
582   Value *V1 = II.getArgOperand(1);
583 
584   if (ZMask) {
585     // If the zero mask is being used with a single input or the zero mask
586     // overrides the destination lane, this is a shuffle with the zero vector.
587     if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
588         (ZMask & (1 << DestLane))) {
589       V1 = ZeroVector;
590       // We may still move 32-bits of the first source vector from one lane
591       // to another.
592       ShuffleMask[DestLane] = SourceLane;
593       // The zero mask may override the previous insert operation.
594       for (unsigned i = 0; i < 4; ++i)
595         if ((ZMask >> i) & 0x1)
596           ShuffleMask[i] = i + 4;
597     } else {
598       // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
599       return nullptr;
600     }
601   } else {
602     // Replace the selected destination lane with the selected source lane.
603     ShuffleMask[DestLane] = SourceLane + 4;
604   }
605 
606   return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
607 }
608 
609 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
610 /// or conversion to a shuffle vector.
611 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
612                                ConstantInt *CILength, ConstantInt *CIIndex,
613                                InstCombiner::BuilderTy &Builder) {
614   auto LowConstantHighUndef = [&](uint64_t Val) {
615     Type *IntTy64 = Type::getInt64Ty(II.getContext());
616     Constant *Args[] = {ConstantInt::get(IntTy64, Val),
617                         UndefValue::get(IntTy64)};
618     return ConstantVector::get(Args);
619   };
620 
621   // See if we're dealing with constant values.
622   Constant *C0 = dyn_cast<Constant>(Op0);
623   ConstantInt *CI0 =
624       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
625          : nullptr;
626 
627   // Attempt to constant fold.
628   if (CILength && CIIndex) {
629     // From AMD documentation: "The bit index and field length are each six
630     // bits in length other bits of the field are ignored."
631     APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
632     APInt APLength = CILength->getValue().zextOrTrunc(6);
633 
634     unsigned Index = APIndex.getZExtValue();
635 
636     // From AMD documentation: "a value of zero in the field length is
637     // defined as length of 64".
638     unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
639 
640     // From AMD documentation: "If the sum of the bit index + length field
641     // is greater than 64, the results are undefined".
642     unsigned End = Index + Length;
643 
644     // Note that both field index and field length are 8-bit quantities.
645     // Since variables 'Index' and 'Length' are unsigned values
646     // obtained from zero-extending field index and field length
647     // respectively, their sum should never wrap around.
648     if (End > 64)
649       return UndefValue::get(II.getType());
650 
651     // If we are inserting whole bytes, we can convert this to a shuffle.
652     // Lowering can recognize EXTRQI shuffle masks.
653     if ((Length % 8) == 0 && (Index % 8) == 0) {
654       // Convert bit indices to byte indices.
655       Length /= 8;
656       Index /= 8;
657 
658       Type *IntTy8 = Type::getInt8Ty(II.getContext());
659       Type *IntTy32 = Type::getInt32Ty(II.getContext());
660       VectorType *ShufTy = VectorType::get(IntTy8, 16);
661 
662       SmallVector<Constant *, 16> ShuffleMask;
663       for (int i = 0; i != (int)Length; ++i)
664         ShuffleMask.push_back(
665             Constant::getIntegerValue(IntTy32, APInt(32, i + Index)));
666       for (int i = Length; i != 8; ++i)
667         ShuffleMask.push_back(
668             Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
669       for (int i = 8; i != 16; ++i)
670         ShuffleMask.push_back(UndefValue::get(IntTy32));
671 
672       Value *SV = Builder.CreateShuffleVector(
673           Builder.CreateBitCast(Op0, ShufTy),
674           ConstantAggregateZero::get(ShufTy), ConstantVector::get(ShuffleMask));
675       return Builder.CreateBitCast(SV, II.getType());
676     }
677 
678     // Constant Fold - shift Index'th bit to lowest position and mask off
679     // Length bits.
680     if (CI0) {
681       APInt Elt = CI0->getValue();
682       Elt = Elt.lshr(Index).zextOrTrunc(Length);
683       return LowConstantHighUndef(Elt.getZExtValue());
684     }
685 
686     // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
687     if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
688       Value *Args[] = {Op0, CILength, CIIndex};
689       Module *M = II.getModule();
690       Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
691       return Builder.CreateCall(F, Args);
692     }
693   }
694 
695   // Constant Fold - extraction from zero is always {zero, undef}.
696   if (CI0 && CI0->equalsInt(0))
697     return LowConstantHighUndef(0);
698 
699   return nullptr;
700 }
701 
702 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
703 /// folding or conversion to a shuffle vector.
704 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
705                                  APInt APLength, APInt APIndex,
706                                  InstCombiner::BuilderTy &Builder) {
707   // From AMD documentation: "The bit index and field length are each six bits
708   // in length other bits of the field are ignored."
709   APIndex = APIndex.zextOrTrunc(6);
710   APLength = APLength.zextOrTrunc(6);
711 
712   // Attempt to constant fold.
713   unsigned Index = APIndex.getZExtValue();
714 
715   // From AMD documentation: "a value of zero in the field length is
716   // defined as length of 64".
717   unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
718 
719   // From AMD documentation: "If the sum of the bit index + length field
720   // is greater than 64, the results are undefined".
721   unsigned End = Index + Length;
722 
723   // Note that both field index and field length are 8-bit quantities.
724   // Since variables 'Index' and 'Length' are unsigned values
725   // obtained from zero-extending field index and field length
726   // respectively, their sum should never wrap around.
727   if (End > 64)
728     return UndefValue::get(II.getType());
729 
730   // If we are inserting whole bytes, we can convert this to a shuffle.
731   // Lowering can recognize INSERTQI shuffle masks.
732   if ((Length % 8) == 0 && (Index % 8) == 0) {
733     // Convert bit indices to byte indices.
734     Length /= 8;
735     Index /= 8;
736 
737     Type *IntTy8 = Type::getInt8Ty(II.getContext());
738     Type *IntTy32 = Type::getInt32Ty(II.getContext());
739     VectorType *ShufTy = VectorType::get(IntTy8, 16);
740 
741     SmallVector<Constant *, 16> ShuffleMask;
742     for (int i = 0; i != (int)Index; ++i)
743       ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
744     for (int i = 0; i != (int)Length; ++i)
745       ShuffleMask.push_back(
746           Constant::getIntegerValue(IntTy32, APInt(32, i + 16)));
747     for (int i = Index + Length; i != 8; ++i)
748       ShuffleMask.push_back(Constant::getIntegerValue(IntTy32, APInt(32, i)));
749     for (int i = 8; i != 16; ++i)
750       ShuffleMask.push_back(UndefValue::get(IntTy32));
751 
752     Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
753                                             Builder.CreateBitCast(Op1, ShufTy),
754                                             ConstantVector::get(ShuffleMask));
755     return Builder.CreateBitCast(SV, II.getType());
756   }
757 
758   // See if we're dealing with constant values.
759   Constant *C0 = dyn_cast<Constant>(Op0);
760   Constant *C1 = dyn_cast<Constant>(Op1);
761   ConstantInt *CI00 =
762       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
763          : nullptr;
764   ConstantInt *CI10 =
765       C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
766          : nullptr;
767 
768   // Constant Fold - insert bottom Length bits starting at the Index'th bit.
769   if (CI00 && CI10) {
770     APInt V00 = CI00->getValue();
771     APInt V10 = CI10->getValue();
772     APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
773     V00 = V00 & ~Mask;
774     V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
775     APInt Val = V00 | V10;
776     Type *IntTy64 = Type::getInt64Ty(II.getContext());
777     Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
778                         UndefValue::get(IntTy64)};
779     return ConstantVector::get(Args);
780   }
781 
782   // If we were an INSERTQ call, we'll save demanded elements if we convert to
783   // INSERTQI.
784   if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
785     Type *IntTy8 = Type::getInt8Ty(II.getContext());
786     Constant *CILength = ConstantInt::get(IntTy8, Length, false);
787     Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
788 
789     Value *Args[] = {Op0, Op1, CILength, CIIndex};
790     Module *M = II.getModule();
791     Value *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
792     return Builder.CreateCall(F, Args);
793   }
794 
795   return nullptr;
796 }
797 
798 /// Attempt to convert pshufb* to shufflevector if the mask is constant.
799 static Value *simplifyX86pshufb(const IntrinsicInst &II,
800                                 InstCombiner::BuilderTy &Builder) {
801   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
802   if (!V)
803     return nullptr;
804 
805   auto *VecTy = cast<VectorType>(II.getType());
806   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
807   unsigned NumElts = VecTy->getNumElements();
808   assert((NumElts == 16 || NumElts == 32) &&
809          "Unexpected number of elements in shuffle mask!");
810 
811   // Construct a shuffle mask from constant integers or UNDEFs.
812   Constant *Indexes[32] = {nullptr};
813 
814   // Each byte in the shuffle control mask forms an index to permute the
815   // corresponding byte in the destination operand.
816   for (unsigned I = 0; I < NumElts; ++I) {
817     Constant *COp = V->getAggregateElement(I);
818     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
819       return nullptr;
820 
821     if (isa<UndefValue>(COp)) {
822       Indexes[I] = UndefValue::get(MaskEltTy);
823       continue;
824     }
825 
826     int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
827 
828     // If the most significant bit (bit[7]) of each byte of the shuffle
829     // control mask is set, then zero is written in the result byte.
830     // The zero vector is in the right-hand side of the resulting
831     // shufflevector.
832 
833     // The value of each index for the high 128-bit lane is the least
834     // significant 4 bits of the respective shuffle control byte.
835     Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
836     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
837   }
838 
839   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
840   auto V1 = II.getArgOperand(0);
841   auto V2 = Constant::getNullValue(VecTy);
842   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
843 }
844 
845 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
846 static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
847                                     InstCombiner::BuilderTy &Builder) {
848   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
849   if (!V)
850     return nullptr;
851 
852   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
853   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
854   assert(NumElts == 8 || NumElts == 4 || NumElts == 2);
855 
856   // Construct a shuffle mask from constant integers or UNDEFs.
857   Constant *Indexes[8] = {nullptr};
858 
859   // The intrinsics only read one or two bits, clear the rest.
860   for (unsigned I = 0; I < NumElts; ++I) {
861     Constant *COp = V->getAggregateElement(I);
862     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
863       return nullptr;
864 
865     if (isa<UndefValue>(COp)) {
866       Indexes[I] = UndefValue::get(MaskEltTy);
867       continue;
868     }
869 
870     APInt Index = cast<ConstantInt>(COp)->getValue();
871     Index = Index.zextOrTrunc(32).getLoBits(2);
872 
873     // The PD variants uses bit 1 to select per-lane element index, so
874     // shift down to convert to generic shuffle mask index.
875     if (II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
876         II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
877       Index = Index.lshr(1);
878 
879     // The _256 variants are a bit trickier since the mask bits always index
880     // into the corresponding 128 half. In order to convert to a generic
881     // shuffle, we have to make that explicit.
882     if ((II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
883          II.getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) &&
884         ((NumElts / 2) <= I)) {
885       Index += APInt(32, NumElts / 2);
886     }
887 
888     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
889   }
890 
891   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, NumElts));
892   auto V1 = II.getArgOperand(0);
893   auto V2 = UndefValue::get(V1->getType());
894   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
895 }
896 
897 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
898 static Value *simplifyX86vpermv(const IntrinsicInst &II,
899                                 InstCombiner::BuilderTy &Builder) {
900   auto *V = dyn_cast<Constant>(II.getArgOperand(1));
901   if (!V)
902     return nullptr;
903 
904   auto *VecTy = cast<VectorType>(II.getType());
905   auto *MaskEltTy = Type::getInt32Ty(II.getContext());
906   unsigned Size = VecTy->getNumElements();
907   assert(Size == 8 && "Unexpected shuffle mask size");
908 
909   // Construct a shuffle mask from constant integers or UNDEFs.
910   Constant *Indexes[8] = {nullptr};
911 
912   for (unsigned I = 0; I < Size; ++I) {
913     Constant *COp = V->getAggregateElement(I);
914     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
915       return nullptr;
916 
917     if (isa<UndefValue>(COp)) {
918       Indexes[I] = UndefValue::get(MaskEltTy);
919       continue;
920     }
921 
922     APInt Index = cast<ConstantInt>(COp)->getValue();
923     Index = Index.zextOrTrunc(32).getLoBits(3);
924     Indexes[I] = ConstantInt::get(MaskEltTy, Index);
925   }
926 
927   auto ShuffleMask = ConstantVector::get(makeArrayRef(Indexes, Size));
928   auto V1 = II.getArgOperand(0);
929   auto V2 = UndefValue::get(VecTy);
930   return Builder.CreateShuffleVector(V1, V2, ShuffleMask);
931 }
932 
933 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
934 /// source vectors, unless a zero bit is set. If a zero bit is set,
935 /// then ignore that half of the mask and clear that half of the vector.
936 static Value *simplifyX86vperm2(const IntrinsicInst &II,
937                                 InstCombiner::BuilderTy &Builder) {
938   auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
939   if (!CInt)
940     return nullptr;
941 
942   VectorType *VecTy = cast<VectorType>(II.getType());
943   ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
944 
945   // The immediate permute control byte looks like this:
946   //    [1:0] - select 128 bits from sources for low half of destination
947   //    [2]   - ignore
948   //    [3]   - zero low half of destination
949   //    [5:4] - select 128 bits from sources for high half of destination
950   //    [6]   - ignore
951   //    [7]   - zero high half of destination
952 
953   uint8_t Imm = CInt->getZExtValue();
954 
955   bool LowHalfZero = Imm & 0x08;
956   bool HighHalfZero = Imm & 0x80;
957 
958   // If both zero mask bits are set, this was just a weird way to
959   // generate a zero vector.
960   if (LowHalfZero && HighHalfZero)
961     return ZeroVector;
962 
963   // If 0 or 1 zero mask bits are set, this is a simple shuffle.
964   unsigned NumElts = VecTy->getNumElements();
965   unsigned HalfSize = NumElts / 2;
966   SmallVector<uint32_t, 8> ShuffleMask(NumElts);
967 
968   // The high bit of the selection field chooses the 1st or 2nd operand.
969   bool LowInputSelect = Imm & 0x02;
970   bool HighInputSelect = Imm & 0x20;
971 
972   // The low bit of the selection field chooses the low or high half
973   // of the selected operand.
974   bool LowHalfSelect = Imm & 0x01;
975   bool HighHalfSelect = Imm & 0x10;
976 
977   // Determine which operand(s) are actually in use for this instruction.
978   Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
979   Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
980 
981   // If needed, replace operands based on zero mask.
982   V0 = LowHalfZero ? ZeroVector : V0;
983   V1 = HighHalfZero ? ZeroVector : V1;
984 
985   // Permute low half of result.
986   unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
987   for (unsigned i = 0; i < HalfSize; ++i)
988     ShuffleMask[i] = StartIndex + i;
989 
990   // Permute high half of result.
991   StartIndex = HighHalfSelect ? HalfSize : 0;
992   StartIndex += NumElts;
993   for (unsigned i = 0; i < HalfSize; ++i)
994     ShuffleMask[i + HalfSize] = StartIndex + i;
995 
996   return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
997 }
998 
999 /// Decode XOP integer vector comparison intrinsics.
1000 static Value *simplifyX86vpcom(const IntrinsicInst &II,
1001                                InstCombiner::BuilderTy &Builder,
1002                                bool IsSigned) {
1003   if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1004     uint64_t Imm = CInt->getZExtValue() & 0x7;
1005     VectorType *VecTy = cast<VectorType>(II.getType());
1006     CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
1007 
1008     switch (Imm) {
1009     case 0x0:
1010       Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1011       break;
1012     case 0x1:
1013       Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1014       break;
1015     case 0x2:
1016       Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1017       break;
1018     case 0x3:
1019       Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1020       break;
1021     case 0x4:
1022       Pred = ICmpInst::ICMP_EQ; break;
1023     case 0x5:
1024       Pred = ICmpInst::ICMP_NE; break;
1025     case 0x6:
1026       return ConstantInt::getSigned(VecTy, 0); // FALSE
1027     case 0x7:
1028       return ConstantInt::getSigned(VecTy, -1); // TRUE
1029     }
1030 
1031     if (Value *Cmp = Builder.CreateICmp(Pred, II.getArgOperand(0),
1032                                         II.getArgOperand(1)))
1033       return Builder.CreateSExtOrTrunc(Cmp, VecTy);
1034   }
1035   return nullptr;
1036 }
1037 
1038 static Value *simplifyMinnumMaxnum(const IntrinsicInst &II) {
1039   Value *Arg0 = II.getArgOperand(0);
1040   Value *Arg1 = II.getArgOperand(1);
1041 
1042   // fmin(x, x) -> x
1043   if (Arg0 == Arg1)
1044     return Arg0;
1045 
1046   const auto *C1 = dyn_cast<ConstantFP>(Arg1);
1047 
1048   // fmin(x, nan) -> x
1049   if (C1 && C1->isNaN())
1050     return Arg0;
1051 
1052   // This is the value because if undef were NaN, we would return the other
1053   // value and cannot return a NaN unless both operands are.
1054   //
1055   // fmin(undef, x) -> x
1056   if (isa<UndefValue>(Arg0))
1057     return Arg1;
1058 
1059   // fmin(x, undef) -> x
1060   if (isa<UndefValue>(Arg1))
1061     return Arg0;
1062 
1063   Value *X = nullptr;
1064   Value *Y = nullptr;
1065   if (II.getIntrinsicID() == Intrinsic::minnum) {
1066     // fmin(x, fmin(x, y)) -> fmin(x, y)
1067     // fmin(y, fmin(x, y)) -> fmin(x, y)
1068     if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
1069       if (Arg0 == X || Arg0 == Y)
1070         return Arg1;
1071     }
1072 
1073     // fmin(fmin(x, y), x) -> fmin(x, y)
1074     // fmin(fmin(x, y), y) -> fmin(x, y)
1075     if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
1076       if (Arg1 == X || Arg1 == Y)
1077         return Arg0;
1078     }
1079 
1080     // TODO: fmin(nnan x, inf) -> x
1081     // TODO: fmin(nnan ninf x, flt_max) -> x
1082     if (C1 && C1->isInfinity()) {
1083       // fmin(x, -inf) -> -inf
1084       if (C1->isNegative())
1085         return Arg1;
1086     }
1087   } else {
1088     assert(II.getIntrinsicID() == Intrinsic::maxnum);
1089     // fmax(x, fmax(x, y)) -> fmax(x, y)
1090     // fmax(y, fmax(x, y)) -> fmax(x, y)
1091     if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
1092       if (Arg0 == X || Arg0 == Y)
1093         return Arg1;
1094     }
1095 
1096     // fmax(fmax(x, y), x) -> fmax(x, y)
1097     // fmax(fmax(x, y), y) -> fmax(x, y)
1098     if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
1099       if (Arg1 == X || Arg1 == Y)
1100         return Arg0;
1101     }
1102 
1103     // TODO: fmax(nnan x, -inf) -> x
1104     // TODO: fmax(nnan ninf x, -flt_max) -> x
1105     if (C1 && C1->isInfinity()) {
1106       // fmax(x, inf) -> inf
1107       if (!C1->isNegative())
1108         return Arg1;
1109     }
1110   }
1111   return nullptr;
1112 }
1113 
1114 static bool maskIsAllOneOrUndef(Value *Mask) {
1115   auto *ConstMask = dyn_cast<Constant>(Mask);
1116   if (!ConstMask)
1117     return false;
1118   if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1119     return true;
1120   for (unsigned I = 0, E = ConstMask->getType()->getVectorNumElements(); I != E;
1121        ++I) {
1122     if (auto *MaskElt = ConstMask->getAggregateElement(I))
1123       if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1124         continue;
1125     return false;
1126   }
1127   return true;
1128 }
1129 
1130 static Value *simplifyMaskedLoad(const IntrinsicInst &II,
1131                                  InstCombiner::BuilderTy &Builder) {
1132   // If the mask is all ones or undefs, this is a plain vector load of the 1st
1133   // argument.
1134   if (maskIsAllOneOrUndef(II.getArgOperand(2))) {
1135     Value *LoadPtr = II.getArgOperand(0);
1136     unsigned Alignment = cast<ConstantInt>(II.getArgOperand(1))->getZExtValue();
1137     return Builder.CreateAlignedLoad(LoadPtr, Alignment, "unmaskedload");
1138   }
1139 
1140   return nullptr;
1141 }
1142 
1143 static Instruction *simplifyMaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1144   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1145   if (!ConstMask)
1146     return nullptr;
1147 
1148   // If the mask is all zeros, this instruction does nothing.
1149   if (ConstMask->isNullValue())
1150     return IC.eraseInstFromFunction(II);
1151 
1152   // If the mask is all ones, this is a plain vector store of the 1st argument.
1153   if (ConstMask->isAllOnesValue()) {
1154     Value *StorePtr = II.getArgOperand(1);
1155     unsigned Alignment = cast<ConstantInt>(II.getArgOperand(2))->getZExtValue();
1156     return new StoreInst(II.getArgOperand(0), StorePtr, false, Alignment);
1157   }
1158 
1159   return nullptr;
1160 }
1161 
1162 static Instruction *simplifyMaskedGather(IntrinsicInst &II, InstCombiner &IC) {
1163   // If the mask is all zeros, return the "passthru" argument of the gather.
1164   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(2));
1165   if (ConstMask && ConstMask->isNullValue())
1166     return IC.replaceInstUsesWith(II, II.getArgOperand(3));
1167 
1168   return nullptr;
1169 }
1170 
1171 static Instruction *simplifyMaskedScatter(IntrinsicInst &II, InstCombiner &IC) {
1172   // If the mask is all zeros, a scatter does nothing.
1173   auto *ConstMask = dyn_cast<Constant>(II.getArgOperand(3));
1174   if (ConstMask && ConstMask->isNullValue())
1175     return IC.eraseInstFromFunction(II);
1176 
1177   return nullptr;
1178 }
1179 
1180 static Instruction *foldCttzCtlz(IntrinsicInst &II, InstCombiner &IC) {
1181   assert((II.getIntrinsicID() == Intrinsic::cttz ||
1182           II.getIntrinsicID() == Intrinsic::ctlz) &&
1183          "Expected cttz or ctlz intrinsic");
1184   Value *Op0 = II.getArgOperand(0);
1185   // FIXME: Try to simplify vectors of integers.
1186   auto *IT = dyn_cast<IntegerType>(Op0->getType());
1187   if (!IT)
1188     return nullptr;
1189 
1190   unsigned BitWidth = IT->getBitWidth();
1191   APInt KnownZero(BitWidth, 0);
1192   APInt KnownOne(BitWidth, 0);
1193   IC.computeKnownBits(Op0, KnownZero, KnownOne, 0, &II);
1194 
1195   // Create a mask for bits above (ctlz) or below (cttz) the first known one.
1196   bool IsTZ = II.getIntrinsicID() == Intrinsic::cttz;
1197   unsigned NumMaskBits = IsTZ ? KnownOne.countTrailingZeros()
1198                               : KnownOne.countLeadingZeros();
1199   APInt Mask = IsTZ ? APInt::getLowBitsSet(BitWidth, NumMaskBits)
1200                     : APInt::getHighBitsSet(BitWidth, NumMaskBits);
1201 
1202   // If all bits above (ctlz) or below (cttz) the first known one are known
1203   // zero, this value is constant.
1204   // FIXME: This should be in InstSimplify because we're replacing an
1205   // instruction with a constant.
1206   if ((Mask & KnownZero) == Mask) {
1207     auto *C = ConstantInt::get(IT, APInt(BitWidth, NumMaskBits));
1208     return IC.replaceInstUsesWith(II, C);
1209   }
1210 
1211   // If the input to cttz/ctlz is known to be non-zero,
1212   // then change the 'ZeroIsUndef' parameter to 'true'
1213   // because we know the zero behavior can't affect the result.
1214   if (KnownOne != 0 || isKnownNonZero(Op0, IC.getDataLayout())) {
1215     if (!match(II.getArgOperand(1), m_One())) {
1216       II.setOperand(1, IC.Builder->getTrue());
1217       return &II;
1218     }
1219   }
1220 
1221   return nullptr;
1222 }
1223 
1224 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1225 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1226 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1227 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
1228   Value *Ptr = II.getOperand(0);
1229   Value *Mask = II.getOperand(1);
1230   Constant *ZeroVec = Constant::getNullValue(II.getType());
1231 
1232   // Special case a zero mask since that's not a ConstantDataVector.
1233   // This masked load instruction creates a zero vector.
1234   if (isa<ConstantAggregateZero>(Mask))
1235     return IC.replaceInstUsesWith(II, ZeroVec);
1236 
1237   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1238   if (!ConstMask)
1239     return nullptr;
1240 
1241   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1242   // to allow target-independent optimizations.
1243 
1244   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1245   // the LLVM intrinsic definition for the pointer argument.
1246   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1247   PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
1248   Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1249 
1250   // Second, convert the x86 XMM integer vector mask to a vector of bools based
1251   // on each element's most significant bit (the sign bit).
1252   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1253 
1254   // The pass-through vector for an x86 masked load is a zero vector.
1255   CallInst *NewMaskedLoad =
1256       IC.Builder->CreateMaskedLoad(PtrCast, 1, BoolMask, ZeroVec);
1257   return IC.replaceInstUsesWith(II, NewMaskedLoad);
1258 }
1259 
1260 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
1261 // XMM register mask efficiently, we could transform all x86 masked intrinsics
1262 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
1263 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
1264   Value *Ptr = II.getOperand(0);
1265   Value *Mask = II.getOperand(1);
1266   Value *Vec = II.getOperand(2);
1267 
1268   // Special case a zero mask since that's not a ConstantDataVector:
1269   // this masked store instruction does nothing.
1270   if (isa<ConstantAggregateZero>(Mask)) {
1271     IC.eraseInstFromFunction(II);
1272     return true;
1273   }
1274 
1275   // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
1276   // anything else at this level.
1277   if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
1278     return false;
1279 
1280   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
1281   if (!ConstMask)
1282     return false;
1283 
1284   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
1285   // to allow target-independent optimizations.
1286 
1287   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
1288   // the LLVM intrinsic definition for the pointer argument.
1289   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
1290   PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
1291   Value *PtrCast = IC.Builder->CreateBitCast(Ptr, VecPtrTy, "castvec");
1292 
1293   // Second, convert the x86 XMM integer vector mask to a vector of bools based
1294   // on each element's most significant bit (the sign bit).
1295   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
1296 
1297   IC.Builder->CreateMaskedStore(Vec, PtrCast, 1, BoolMask);
1298 
1299   // 'Replace uses' doesn't work for stores. Erase the original masked store.
1300   IC.eraseInstFromFunction(II);
1301   return true;
1302 }
1303 
1304 // Returns true iff the 2 intrinsics have the same operands, limiting the
1305 // comparison to the first NumOperands.
1306 static bool haveSameOperands(const IntrinsicInst &I, const IntrinsicInst &E,
1307                              unsigned NumOperands) {
1308   assert(I.getNumArgOperands() >= NumOperands && "Not enough operands");
1309   assert(E.getNumArgOperands() >= NumOperands && "Not enough operands");
1310   for (unsigned i = 0; i < NumOperands; i++)
1311     if (I.getArgOperand(i) != E.getArgOperand(i))
1312       return false;
1313   return true;
1314 }
1315 
1316 // Remove trivially empty start/end intrinsic ranges, i.e. a start
1317 // immediately followed by an end (ignoring debuginfo or other
1318 // start/end intrinsics in between). As this handles only the most trivial
1319 // cases, tracking the nesting level is not needed:
1320 //
1321 //   call @llvm.foo.start(i1 0) ; &I
1322 //   call @llvm.foo.start(i1 0)
1323 //   call @llvm.foo.end(i1 0) ; This one will not be skipped: it will be removed
1324 //   call @llvm.foo.end(i1 0)
1325 static bool removeTriviallyEmptyRange(IntrinsicInst &I, unsigned StartID,
1326                                       unsigned EndID, InstCombiner &IC) {
1327   assert(I.getIntrinsicID() == StartID &&
1328          "Start intrinsic does not have expected ID");
1329   BasicBlock::iterator BI(I), BE(I.getParent()->end());
1330   for (++BI; BI != BE; ++BI) {
1331     if (auto *E = dyn_cast<IntrinsicInst>(BI)) {
1332       if (isa<DbgInfoIntrinsic>(E) || E->getIntrinsicID() == StartID)
1333         continue;
1334       if (E->getIntrinsicID() == EndID &&
1335           haveSameOperands(I, *E, E->getNumArgOperands())) {
1336         IC.eraseInstFromFunction(*E);
1337         IC.eraseInstFromFunction(I);
1338         return true;
1339       }
1340     }
1341     break;
1342   }
1343 
1344   return false;
1345 }
1346 
1347 Instruction *InstCombiner::visitVAStartInst(VAStartInst &I) {
1348   removeTriviallyEmptyRange(I, Intrinsic::vastart, Intrinsic::vaend, *this);
1349   return nullptr;
1350 }
1351 
1352 Instruction *InstCombiner::visitVACopyInst(VACopyInst &I) {
1353   removeTriviallyEmptyRange(I, Intrinsic::vacopy, Intrinsic::vaend, *this);
1354   return nullptr;
1355 }
1356 
1357 /// CallInst simplification. This mostly only handles folding of intrinsic
1358 /// instructions. For normal calls, it allows visitCallSite to do the heavy
1359 /// lifting.
1360 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1361   auto Args = CI.arg_operands();
1362   if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
1363                               &TLI, &DT, &AC))
1364     return replaceInstUsesWith(CI, V);
1365 
1366   if (isFreeCall(&CI, &TLI))
1367     return visitFree(CI);
1368 
1369   // If the caller function is nounwind, mark the call as nounwind, even if the
1370   // callee isn't.
1371   if (CI.getFunction()->doesNotThrow() && !CI.doesNotThrow()) {
1372     CI.setDoesNotThrow();
1373     return &CI;
1374   }
1375 
1376   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
1377   if (!II) return visitCallSite(&CI);
1378 
1379   // Intrinsics cannot occur in an invoke, so handle them here instead of in
1380   // visitCallSite.
1381   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
1382     bool Changed = false;
1383 
1384     // memmove/cpy/set of zero bytes is a noop.
1385     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
1386       if (NumBytes->isNullValue())
1387         return eraseInstFromFunction(CI);
1388 
1389       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
1390         if (CI->getZExtValue() == 1) {
1391           // Replace the instruction with just byte operations.  We would
1392           // transform other cases to loads/stores, but we don't know if
1393           // alignment is sufficient.
1394         }
1395     }
1396 
1397     // No other transformations apply to volatile transfers.
1398     if (MI->isVolatile())
1399       return nullptr;
1400 
1401     // If we have a memmove and the source operation is a constant global,
1402     // then the source and dest pointers can't alias, so we can change this
1403     // into a call to memcpy.
1404     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
1405       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
1406         if (GVSrc->isConstant()) {
1407           Module *M = CI.getModule();
1408           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
1409           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
1410                            CI.getArgOperand(1)->getType(),
1411                            CI.getArgOperand(2)->getType() };
1412           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
1413           Changed = true;
1414         }
1415     }
1416 
1417     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
1418       // memmove(x,x,size) -> noop.
1419       if (MTI->getSource() == MTI->getDest())
1420         return eraseInstFromFunction(CI);
1421     }
1422 
1423     // If we can determine a pointer alignment that is bigger than currently
1424     // set, update the alignment.
1425     if (isa<MemTransferInst>(MI)) {
1426       if (Instruction *I = SimplifyMemTransfer(MI))
1427         return I;
1428     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
1429       if (Instruction *I = SimplifyMemSet(MSI))
1430         return I;
1431     }
1432 
1433     if (Changed) return II;
1434   }
1435 
1436   auto SimplifyDemandedVectorEltsLow = [this](Value *Op, unsigned Width,
1437                                               unsigned DemandedWidth) {
1438     APInt UndefElts(Width, 0);
1439     APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
1440     return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1441   };
1442   auto SimplifyDemandedVectorEltsHigh = [this](Value *Op, unsigned Width,
1443                                               unsigned DemandedWidth) {
1444     APInt UndefElts(Width, 0);
1445     APInt DemandedElts = APInt::getHighBitsSet(Width, DemandedWidth);
1446     return SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
1447   };
1448 
1449   switch (II->getIntrinsicID()) {
1450   default: break;
1451   case Intrinsic::objectsize: {
1452     uint64_t Size;
1453     if (getObjectSize(II->getArgOperand(0), Size, DL, &TLI)) {
1454       APInt APSize(II->getType()->getIntegerBitWidth(), Size);
1455       // Equality check to be sure that `Size` can fit in a value of type
1456       // `II->getType()`
1457       if (APSize == Size)
1458         return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), APSize));
1459     }
1460     return nullptr;
1461   }
1462   case Intrinsic::bswap: {
1463     Value *IIOperand = II->getArgOperand(0);
1464     Value *X = nullptr;
1465 
1466     // bswap(bswap(x)) -> x
1467     if (match(IIOperand, m_BSwap(m_Value(X))))
1468         return replaceInstUsesWith(CI, X);
1469 
1470     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
1471     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
1472       unsigned C = X->getType()->getPrimitiveSizeInBits() -
1473         IIOperand->getType()->getPrimitiveSizeInBits();
1474       Value *CV = ConstantInt::get(X->getType(), C);
1475       Value *V = Builder->CreateLShr(X, CV);
1476       return new TruncInst(V, IIOperand->getType());
1477     }
1478     break;
1479   }
1480 
1481   case Intrinsic::bitreverse: {
1482     Value *IIOperand = II->getArgOperand(0);
1483     Value *X = nullptr;
1484 
1485     // bitreverse(bitreverse(x)) -> x
1486     if (match(IIOperand, m_Intrinsic<Intrinsic::bitreverse>(m_Value(X))))
1487       return replaceInstUsesWith(CI, X);
1488     break;
1489   }
1490 
1491   case Intrinsic::masked_load:
1492     if (Value *SimplifiedMaskedOp = simplifyMaskedLoad(*II, *Builder))
1493       return replaceInstUsesWith(CI, SimplifiedMaskedOp);
1494     break;
1495   case Intrinsic::masked_store:
1496     return simplifyMaskedStore(*II, *this);
1497   case Intrinsic::masked_gather:
1498     return simplifyMaskedGather(*II, *this);
1499   case Intrinsic::masked_scatter:
1500     return simplifyMaskedScatter(*II, *this);
1501 
1502   case Intrinsic::powi:
1503     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
1504       // powi(x, 0) -> 1.0
1505       if (Power->isZero())
1506         return replaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
1507       // powi(x, 1) -> x
1508       if (Power->isOne())
1509         return replaceInstUsesWith(CI, II->getArgOperand(0));
1510       // powi(x, -1) -> 1/x
1511       if (Power->isAllOnesValue())
1512         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
1513                                           II->getArgOperand(0));
1514     }
1515     break;
1516 
1517   case Intrinsic::cttz:
1518   case Intrinsic::ctlz:
1519     if (auto *I = foldCttzCtlz(*II, *this))
1520       return I;
1521     break;
1522 
1523   case Intrinsic::uadd_with_overflow:
1524   case Intrinsic::sadd_with_overflow:
1525   case Intrinsic::umul_with_overflow:
1526   case Intrinsic::smul_with_overflow:
1527     if (isa<Constant>(II->getArgOperand(0)) &&
1528         !isa<Constant>(II->getArgOperand(1))) {
1529       // Canonicalize constants into the RHS.
1530       Value *LHS = II->getArgOperand(0);
1531       II->setArgOperand(0, II->getArgOperand(1));
1532       II->setArgOperand(1, LHS);
1533       return II;
1534     }
1535     LLVM_FALLTHROUGH;
1536 
1537   case Intrinsic::usub_with_overflow:
1538   case Intrinsic::ssub_with_overflow: {
1539     OverflowCheckFlavor OCF =
1540         IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
1541     assert(OCF != OCF_INVALID && "unexpected!");
1542 
1543     Value *OperationResult = nullptr;
1544     Constant *OverflowResult = nullptr;
1545     if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
1546                               *II, OperationResult, OverflowResult))
1547       return CreateOverflowTuple(II, OperationResult, OverflowResult);
1548 
1549     break;
1550   }
1551 
1552   case Intrinsic::minnum:
1553   case Intrinsic::maxnum: {
1554     Value *Arg0 = II->getArgOperand(0);
1555     Value *Arg1 = II->getArgOperand(1);
1556     // Canonicalize constants to the RHS.
1557     if (isa<ConstantFP>(Arg0) && !isa<ConstantFP>(Arg1)) {
1558       II->setArgOperand(0, Arg1);
1559       II->setArgOperand(1, Arg0);
1560       return II;
1561     }
1562     if (Value *V = simplifyMinnumMaxnum(*II))
1563       return replaceInstUsesWith(*II, V);
1564     break;
1565   }
1566   case Intrinsic::ppc_altivec_lvx:
1567   case Intrinsic::ppc_altivec_lvxl:
1568     // Turn PPC lvx -> load if the pointer is known aligned.
1569     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1570                                    &DT) >= 16) {
1571       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1572                                          PointerType::getUnqual(II->getType()));
1573       return new LoadInst(Ptr);
1574     }
1575     break;
1576   case Intrinsic::ppc_vsx_lxvw4x:
1577   case Intrinsic::ppc_vsx_lxvd2x: {
1578     // Turn PPC VSX loads into normal loads.
1579     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1580                                         PointerType::getUnqual(II->getType()));
1581     return new LoadInst(Ptr, Twine(""), false, 1);
1582   }
1583   case Intrinsic::ppc_altivec_stvx:
1584   case Intrinsic::ppc_altivec_stvxl:
1585     // Turn stvx -> store if the pointer is known aligned.
1586     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1587                                    &DT) >= 16) {
1588       Type *OpPtrTy =
1589         PointerType::getUnqual(II->getArgOperand(0)->getType());
1590       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1591       return new StoreInst(II->getArgOperand(0), Ptr);
1592     }
1593     break;
1594   case Intrinsic::ppc_vsx_stxvw4x:
1595   case Intrinsic::ppc_vsx_stxvd2x: {
1596     // Turn PPC VSX stores into normal stores.
1597     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
1598     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1599     return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
1600   }
1601   case Intrinsic::ppc_qpx_qvlfs:
1602     // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
1603     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, &AC,
1604                                    &DT) >= 16) {
1605       Type *VTy = VectorType::get(Builder->getFloatTy(),
1606                                   II->getType()->getVectorNumElements());
1607       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1608                                          PointerType::getUnqual(VTy));
1609       Value *Load = Builder->CreateLoad(Ptr);
1610       return new FPExtInst(Load, II->getType());
1611     }
1612     break;
1613   case Intrinsic::ppc_qpx_qvlfd:
1614     // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
1615     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, &AC,
1616                                    &DT) >= 32) {
1617       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
1618                                          PointerType::getUnqual(II->getType()));
1619       return new LoadInst(Ptr);
1620     }
1621     break;
1622   case Intrinsic::ppc_qpx_qvstfs:
1623     // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
1624     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, &AC,
1625                                    &DT) >= 16) {
1626       Type *VTy = VectorType::get(Builder->getFloatTy(),
1627           II->getArgOperand(0)->getType()->getVectorNumElements());
1628       Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
1629       Type *OpPtrTy = PointerType::getUnqual(VTy);
1630       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1631       return new StoreInst(TOp, Ptr);
1632     }
1633     break;
1634   case Intrinsic::ppc_qpx_qvstfd:
1635     // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
1636     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, &AC,
1637                                    &DT) >= 32) {
1638       Type *OpPtrTy =
1639         PointerType::getUnqual(II->getArgOperand(0)->getType());
1640       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
1641       return new StoreInst(II->getArgOperand(0), Ptr);
1642     }
1643     break;
1644 
1645   case Intrinsic::x86_vcvtph2ps_128:
1646   case Intrinsic::x86_vcvtph2ps_256: {
1647     auto Arg = II->getArgOperand(0);
1648     auto ArgType = cast<VectorType>(Arg->getType());
1649     auto RetType = cast<VectorType>(II->getType());
1650     unsigned ArgWidth = ArgType->getNumElements();
1651     unsigned RetWidth = RetType->getNumElements();
1652     assert(RetWidth <= ArgWidth && "Unexpected input/return vector widths");
1653     assert(ArgType->isIntOrIntVectorTy() &&
1654            ArgType->getScalarSizeInBits() == 16 &&
1655            "CVTPH2PS input type should be 16-bit integer vector");
1656     assert(RetType->getScalarType()->isFloatTy() &&
1657            "CVTPH2PS output type should be 32-bit float vector");
1658 
1659     // Constant folding: Convert to generic half to single conversion.
1660     if (isa<ConstantAggregateZero>(Arg))
1661       return replaceInstUsesWith(*II, ConstantAggregateZero::get(RetType));
1662 
1663     if (isa<ConstantDataVector>(Arg)) {
1664       auto VectorHalfAsShorts = Arg;
1665       if (RetWidth < ArgWidth) {
1666         SmallVector<uint32_t, 8> SubVecMask;
1667         for (unsigned i = 0; i != RetWidth; ++i)
1668           SubVecMask.push_back((int)i);
1669         VectorHalfAsShorts = Builder->CreateShuffleVector(
1670             Arg, UndefValue::get(ArgType), SubVecMask);
1671       }
1672 
1673       auto VectorHalfType =
1674           VectorType::get(Type::getHalfTy(II->getContext()), RetWidth);
1675       auto VectorHalfs =
1676           Builder->CreateBitCast(VectorHalfAsShorts, VectorHalfType);
1677       auto VectorFloats = Builder->CreateFPExt(VectorHalfs, RetType);
1678       return replaceInstUsesWith(*II, VectorFloats);
1679     }
1680 
1681     // We only use the lowest lanes of the argument.
1682     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, ArgWidth, RetWidth)) {
1683       II->setArgOperand(0, V);
1684       return II;
1685     }
1686     break;
1687   }
1688 
1689   case Intrinsic::x86_sse_cvtss2si:
1690   case Intrinsic::x86_sse_cvtss2si64:
1691   case Intrinsic::x86_sse_cvttss2si:
1692   case Intrinsic::x86_sse_cvttss2si64:
1693   case Intrinsic::x86_sse2_cvtsd2si:
1694   case Intrinsic::x86_sse2_cvtsd2si64:
1695   case Intrinsic::x86_sse2_cvttsd2si:
1696   case Intrinsic::x86_sse2_cvttsd2si64: {
1697     // These intrinsics only demand the 0th element of their input vectors. If
1698     // we can simplify the input based on that, do so now.
1699     Value *Arg = II->getArgOperand(0);
1700     unsigned VWidth = Arg->getType()->getVectorNumElements();
1701     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
1702       II->setArgOperand(0, V);
1703       return II;
1704     }
1705     break;
1706   }
1707 
1708   case Intrinsic::x86_mmx_pmovmskb:
1709   case Intrinsic::x86_sse_movmsk_ps:
1710   case Intrinsic::x86_sse2_movmsk_pd:
1711   case Intrinsic::x86_sse2_pmovmskb_128:
1712   case Intrinsic::x86_avx_movmsk_pd_256:
1713   case Intrinsic::x86_avx_movmsk_ps_256:
1714   case Intrinsic::x86_avx2_pmovmskb: {
1715     if (Value *V = simplifyX86movmsk(*II, *Builder))
1716       return replaceInstUsesWith(*II, V);
1717     break;
1718   }
1719 
1720   case Intrinsic::x86_sse_comieq_ss:
1721   case Intrinsic::x86_sse_comige_ss:
1722   case Intrinsic::x86_sse_comigt_ss:
1723   case Intrinsic::x86_sse_comile_ss:
1724   case Intrinsic::x86_sse_comilt_ss:
1725   case Intrinsic::x86_sse_comineq_ss:
1726   case Intrinsic::x86_sse_ucomieq_ss:
1727   case Intrinsic::x86_sse_ucomige_ss:
1728   case Intrinsic::x86_sse_ucomigt_ss:
1729   case Intrinsic::x86_sse_ucomile_ss:
1730   case Intrinsic::x86_sse_ucomilt_ss:
1731   case Intrinsic::x86_sse_ucomineq_ss:
1732   case Intrinsic::x86_sse2_comieq_sd:
1733   case Intrinsic::x86_sse2_comige_sd:
1734   case Intrinsic::x86_sse2_comigt_sd:
1735   case Intrinsic::x86_sse2_comile_sd:
1736   case Intrinsic::x86_sse2_comilt_sd:
1737   case Intrinsic::x86_sse2_comineq_sd:
1738   case Intrinsic::x86_sse2_ucomieq_sd:
1739   case Intrinsic::x86_sse2_ucomige_sd:
1740   case Intrinsic::x86_sse2_ucomigt_sd:
1741   case Intrinsic::x86_sse2_ucomile_sd:
1742   case Intrinsic::x86_sse2_ucomilt_sd:
1743   case Intrinsic::x86_sse2_ucomineq_sd: {
1744     // These intrinsics only demand the 0th element of their input vectors. If
1745     // we can simplify the input based on that, do so now.
1746     bool MadeChange = false;
1747     Value *Arg0 = II->getArgOperand(0);
1748     Value *Arg1 = II->getArgOperand(1);
1749     unsigned VWidth = Arg0->getType()->getVectorNumElements();
1750     if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1751       II->setArgOperand(0, V);
1752       MadeChange = true;
1753     }
1754     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1755       II->setArgOperand(1, V);
1756       MadeChange = true;
1757     }
1758     if (MadeChange)
1759       return II;
1760     break;
1761   }
1762 
1763   case Intrinsic::x86_sse_min_ss:
1764   case Intrinsic::x86_sse_max_ss:
1765   case Intrinsic::x86_sse_cmp_ss:
1766   case Intrinsic::x86_sse2_min_sd:
1767   case Intrinsic::x86_sse2_max_sd:
1768   case Intrinsic::x86_sse2_cmp_sd: {
1769     // These intrinsics only demand the lowest element of the second input
1770     // vector.
1771     Value *Arg1 = II->getArgOperand(1);
1772     unsigned VWidth = Arg1->getType()->getVectorNumElements();
1773     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1774       II->setArgOperand(1, V);
1775       return II;
1776     }
1777     break;
1778   }
1779 
1780   case Intrinsic::x86_sse41_round_ss:
1781   case Intrinsic::x86_sse41_round_sd: {
1782     // These intrinsics demand the upper elements of the first input vector and
1783     // the lowest element of the second input vector.
1784     bool MadeChange = false;
1785     Value *Arg0 = II->getArgOperand(0);
1786     Value *Arg1 = II->getArgOperand(1);
1787     unsigned VWidth = Arg0->getType()->getVectorNumElements();
1788     if (Value *V = SimplifyDemandedVectorEltsHigh(Arg0, VWidth, VWidth - 1)) {
1789       II->setArgOperand(0, V);
1790       MadeChange = true;
1791     }
1792     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1793       II->setArgOperand(1, V);
1794       MadeChange = true;
1795     }
1796     if (MadeChange)
1797       return II;
1798     break;
1799   }
1800 
1801   // Constant fold ashr( <A x Bi>, Ci ).
1802   // Constant fold lshr( <A x Bi>, Ci ).
1803   // Constant fold shl( <A x Bi>, Ci ).
1804   case Intrinsic::x86_sse2_psrai_d:
1805   case Intrinsic::x86_sse2_psrai_w:
1806   case Intrinsic::x86_avx2_psrai_d:
1807   case Intrinsic::x86_avx2_psrai_w:
1808   case Intrinsic::x86_avx512_psrai_q_128:
1809   case Intrinsic::x86_avx512_psrai_q_256:
1810   case Intrinsic::x86_avx512_psrai_d_512:
1811   case Intrinsic::x86_avx512_psrai_q_512:
1812   case Intrinsic::x86_avx512_psrai_w_512:
1813   case Intrinsic::x86_sse2_psrli_d:
1814   case Intrinsic::x86_sse2_psrli_q:
1815   case Intrinsic::x86_sse2_psrli_w:
1816   case Intrinsic::x86_avx2_psrli_d:
1817   case Intrinsic::x86_avx2_psrli_q:
1818   case Intrinsic::x86_avx2_psrli_w:
1819   case Intrinsic::x86_avx512_psrli_d_512:
1820   case Intrinsic::x86_avx512_psrli_q_512:
1821   case Intrinsic::x86_avx512_psrli_w_512:
1822   case Intrinsic::x86_sse2_pslli_d:
1823   case Intrinsic::x86_sse2_pslli_q:
1824   case Intrinsic::x86_sse2_pslli_w:
1825   case Intrinsic::x86_avx2_pslli_d:
1826   case Intrinsic::x86_avx2_pslli_q:
1827   case Intrinsic::x86_avx2_pslli_w:
1828   case Intrinsic::x86_avx512_pslli_d_512:
1829   case Intrinsic::x86_avx512_pslli_q_512:
1830   case Intrinsic::x86_avx512_pslli_w_512:
1831     if (Value *V = simplifyX86immShift(*II, *Builder))
1832       return replaceInstUsesWith(*II, V);
1833     break;
1834 
1835   case Intrinsic::x86_sse2_psra_d:
1836   case Intrinsic::x86_sse2_psra_w:
1837   case Intrinsic::x86_avx2_psra_d:
1838   case Intrinsic::x86_avx2_psra_w:
1839   case Intrinsic::x86_avx512_psra_q_128:
1840   case Intrinsic::x86_avx512_psra_q_256:
1841   case Intrinsic::x86_avx512_psra_d_512:
1842   case Intrinsic::x86_avx512_psra_q_512:
1843   case Intrinsic::x86_avx512_psra_w_512:
1844   case Intrinsic::x86_sse2_psrl_d:
1845   case Intrinsic::x86_sse2_psrl_q:
1846   case Intrinsic::x86_sse2_psrl_w:
1847   case Intrinsic::x86_avx2_psrl_d:
1848   case Intrinsic::x86_avx2_psrl_q:
1849   case Intrinsic::x86_avx2_psrl_w:
1850   case Intrinsic::x86_avx512_psrl_d_512:
1851   case Intrinsic::x86_avx512_psrl_q_512:
1852   case Intrinsic::x86_avx512_psrl_w_512:
1853   case Intrinsic::x86_sse2_psll_d:
1854   case Intrinsic::x86_sse2_psll_q:
1855   case Intrinsic::x86_sse2_psll_w:
1856   case Intrinsic::x86_avx2_psll_d:
1857   case Intrinsic::x86_avx2_psll_q:
1858   case Intrinsic::x86_avx2_psll_w:
1859   case Intrinsic::x86_avx512_psll_d_512:
1860   case Intrinsic::x86_avx512_psll_q_512:
1861   case Intrinsic::x86_avx512_psll_w_512: {
1862     if (Value *V = simplifyX86immShift(*II, *Builder))
1863       return replaceInstUsesWith(*II, V);
1864 
1865     // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1866     // operand to compute the shift amount.
1867     Value *Arg1 = II->getArgOperand(1);
1868     assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
1869            "Unexpected packed shift size");
1870     unsigned VWidth = Arg1->getType()->getVectorNumElements();
1871 
1872     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
1873       II->setArgOperand(1, V);
1874       return II;
1875     }
1876     break;
1877   }
1878 
1879   case Intrinsic::x86_avx2_psllv_d:
1880   case Intrinsic::x86_avx2_psllv_d_256:
1881   case Intrinsic::x86_avx2_psllv_q:
1882   case Intrinsic::x86_avx2_psllv_q_256:
1883   case Intrinsic::x86_avx512_psllv_d_512:
1884   case Intrinsic::x86_avx512_psllv_q_512:
1885   case Intrinsic::x86_avx512_psllv_w_128:
1886   case Intrinsic::x86_avx512_psllv_w_256:
1887   case Intrinsic::x86_avx512_psllv_w_512:
1888   case Intrinsic::x86_avx2_psrav_d:
1889   case Intrinsic::x86_avx2_psrav_d_256:
1890   case Intrinsic::x86_avx512_psrav_q_128:
1891   case Intrinsic::x86_avx512_psrav_q_256:
1892   case Intrinsic::x86_avx512_psrav_d_512:
1893   case Intrinsic::x86_avx512_psrav_q_512:
1894   case Intrinsic::x86_avx512_psrav_w_128:
1895   case Intrinsic::x86_avx512_psrav_w_256:
1896   case Intrinsic::x86_avx512_psrav_w_512:
1897   case Intrinsic::x86_avx2_psrlv_d:
1898   case Intrinsic::x86_avx2_psrlv_d_256:
1899   case Intrinsic::x86_avx2_psrlv_q:
1900   case Intrinsic::x86_avx2_psrlv_q_256:
1901   case Intrinsic::x86_avx512_psrlv_d_512:
1902   case Intrinsic::x86_avx512_psrlv_q_512:
1903   case Intrinsic::x86_avx512_psrlv_w_128:
1904   case Intrinsic::x86_avx512_psrlv_w_256:
1905   case Intrinsic::x86_avx512_psrlv_w_512:
1906     if (Value *V = simplifyX86varShift(*II, *Builder))
1907       return replaceInstUsesWith(*II, V);
1908     break;
1909 
1910   case Intrinsic::x86_sse41_insertps:
1911     if (Value *V = simplifyX86insertps(*II, *Builder))
1912       return replaceInstUsesWith(*II, V);
1913     break;
1914 
1915   case Intrinsic::x86_sse4a_extrq: {
1916     Value *Op0 = II->getArgOperand(0);
1917     Value *Op1 = II->getArgOperand(1);
1918     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
1919     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
1920     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1921            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1922            VWidth1 == 16 && "Unexpected operand sizes");
1923 
1924     // See if we're dealing with constant values.
1925     Constant *C1 = dyn_cast<Constant>(Op1);
1926     ConstantInt *CILength =
1927         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
1928            : nullptr;
1929     ConstantInt *CIIndex =
1930         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
1931            : nullptr;
1932 
1933     // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
1934     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
1935       return replaceInstUsesWith(*II, V);
1936 
1937     // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1938     // operands and the lowest 16-bits of the second.
1939     bool MadeChange = false;
1940     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1941       II->setArgOperand(0, V);
1942       MadeChange = true;
1943     }
1944     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1945       II->setArgOperand(1, V);
1946       MadeChange = true;
1947     }
1948     if (MadeChange)
1949       return II;
1950     break;
1951   }
1952 
1953   case Intrinsic::x86_sse4a_extrqi: {
1954     // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1955     // bits of the lower 64-bits. The upper 64-bits are undefined.
1956     Value *Op0 = II->getArgOperand(0);
1957     unsigned VWidth = Op0->getType()->getVectorNumElements();
1958     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1959            "Unexpected operand size");
1960 
1961     // See if we're dealing with constant values.
1962     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(1));
1963     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(2));
1964 
1965     // Attempt to simplify to a constant or shuffle vector.
1966     if (Value *V = simplifyX86extrq(*II, Op0, CILength, CIIndex, *Builder))
1967       return replaceInstUsesWith(*II, V);
1968 
1969     // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1970     // operand.
1971     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
1972       II->setArgOperand(0, V);
1973       return II;
1974     }
1975     break;
1976   }
1977 
1978   case Intrinsic::x86_sse4a_insertq: {
1979     Value *Op0 = II->getArgOperand(0);
1980     Value *Op1 = II->getArgOperand(1);
1981     unsigned VWidth = Op0->getType()->getVectorNumElements();
1982     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1983            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1984            Op1->getType()->getVectorNumElements() == 2 &&
1985            "Unexpected operand size");
1986 
1987     // See if we're dealing with constant values.
1988     Constant *C1 = dyn_cast<Constant>(Op1);
1989     ConstantInt *CI11 =
1990         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
1991            : nullptr;
1992 
1993     // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1994     if (CI11) {
1995       const APInt &V11 = CI11->getValue();
1996       APInt Len = V11.zextOrTrunc(6);
1997       APInt Idx = V11.lshr(8).zextOrTrunc(6);
1998       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
1999         return replaceInstUsesWith(*II, V);
2000     }
2001 
2002     // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
2003     // operand.
2004     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
2005       II->setArgOperand(0, V);
2006       return II;
2007     }
2008     break;
2009   }
2010 
2011   case Intrinsic::x86_sse4a_insertqi: {
2012     // INSERTQI: Extract lowest Length bits from lower half of second source and
2013     // insert over first source starting at Index bit. The upper 64-bits are
2014     // undefined.
2015     Value *Op0 = II->getArgOperand(0);
2016     Value *Op1 = II->getArgOperand(1);
2017     unsigned VWidth0 = Op0->getType()->getVectorNumElements();
2018     unsigned VWidth1 = Op1->getType()->getVectorNumElements();
2019     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
2020            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
2021            VWidth1 == 2 && "Unexpected operand sizes");
2022 
2023     // See if we're dealing with constant values.
2024     ConstantInt *CILength = dyn_cast<ConstantInt>(II->getArgOperand(2));
2025     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3));
2026 
2027     // Attempt to simplify to a constant or shuffle vector.
2028     if (CILength && CIIndex) {
2029       APInt Len = CILength->getValue().zextOrTrunc(6);
2030       APInt Idx = CIIndex->getValue().zextOrTrunc(6);
2031       if (Value *V = simplifyX86insertq(*II, Op0, Op1, Len, Idx, *Builder))
2032         return replaceInstUsesWith(*II, V);
2033     }
2034 
2035     // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
2036     // operands.
2037     bool MadeChange = false;
2038     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
2039       II->setArgOperand(0, V);
2040       MadeChange = true;
2041     }
2042     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
2043       II->setArgOperand(1, V);
2044       MadeChange = true;
2045     }
2046     if (MadeChange)
2047       return II;
2048     break;
2049   }
2050 
2051   case Intrinsic::x86_sse41_pblendvb:
2052   case Intrinsic::x86_sse41_blendvps:
2053   case Intrinsic::x86_sse41_blendvpd:
2054   case Intrinsic::x86_avx_blendv_ps_256:
2055   case Intrinsic::x86_avx_blendv_pd_256:
2056   case Intrinsic::x86_avx2_pblendvb: {
2057     // Convert blendv* to vector selects if the mask is constant.
2058     // This optimization is convoluted because the intrinsic is defined as
2059     // getting a vector of floats or doubles for the ps and pd versions.
2060     // FIXME: That should be changed.
2061 
2062     Value *Op0 = II->getArgOperand(0);
2063     Value *Op1 = II->getArgOperand(1);
2064     Value *Mask = II->getArgOperand(2);
2065 
2066     // fold (blend A, A, Mask) -> A
2067     if (Op0 == Op1)
2068       return replaceInstUsesWith(CI, Op0);
2069 
2070     // Zero Mask - select 1st argument.
2071     if (isa<ConstantAggregateZero>(Mask))
2072       return replaceInstUsesWith(CI, Op0);
2073 
2074     // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
2075     if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
2076       Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
2077       return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
2078     }
2079     break;
2080   }
2081 
2082   case Intrinsic::x86_ssse3_pshuf_b_128:
2083   case Intrinsic::x86_avx2_pshuf_b:
2084     if (Value *V = simplifyX86pshufb(*II, *Builder))
2085       return replaceInstUsesWith(*II, V);
2086     break;
2087 
2088   case Intrinsic::x86_avx_vpermilvar_ps:
2089   case Intrinsic::x86_avx_vpermilvar_ps_256:
2090   case Intrinsic::x86_avx_vpermilvar_pd:
2091   case Intrinsic::x86_avx_vpermilvar_pd_256:
2092     if (Value *V = simplifyX86vpermilvar(*II, *Builder))
2093       return replaceInstUsesWith(*II, V);
2094     break;
2095 
2096   case Intrinsic::x86_avx2_permd:
2097   case Intrinsic::x86_avx2_permps:
2098     if (Value *V = simplifyX86vpermv(*II, *Builder))
2099       return replaceInstUsesWith(*II, V);
2100     break;
2101 
2102   case Intrinsic::x86_avx_vperm2f128_pd_256:
2103   case Intrinsic::x86_avx_vperm2f128_ps_256:
2104   case Intrinsic::x86_avx_vperm2f128_si_256:
2105   case Intrinsic::x86_avx2_vperm2i128:
2106     if (Value *V = simplifyX86vperm2(*II, *Builder))
2107       return replaceInstUsesWith(*II, V);
2108     break;
2109 
2110   case Intrinsic::x86_avx_maskload_ps:
2111   case Intrinsic::x86_avx_maskload_pd:
2112   case Intrinsic::x86_avx_maskload_ps_256:
2113   case Intrinsic::x86_avx_maskload_pd_256:
2114   case Intrinsic::x86_avx2_maskload_d:
2115   case Intrinsic::x86_avx2_maskload_q:
2116   case Intrinsic::x86_avx2_maskload_d_256:
2117   case Intrinsic::x86_avx2_maskload_q_256:
2118     if (Instruction *I = simplifyX86MaskedLoad(*II, *this))
2119       return I;
2120     break;
2121 
2122   case Intrinsic::x86_sse2_maskmov_dqu:
2123   case Intrinsic::x86_avx_maskstore_ps:
2124   case Intrinsic::x86_avx_maskstore_pd:
2125   case Intrinsic::x86_avx_maskstore_ps_256:
2126   case Intrinsic::x86_avx_maskstore_pd_256:
2127   case Intrinsic::x86_avx2_maskstore_d:
2128   case Intrinsic::x86_avx2_maskstore_q:
2129   case Intrinsic::x86_avx2_maskstore_d_256:
2130   case Intrinsic::x86_avx2_maskstore_q_256:
2131     if (simplifyX86MaskedStore(*II, *this))
2132       return nullptr;
2133     break;
2134 
2135   case Intrinsic::x86_xop_vpcomb:
2136   case Intrinsic::x86_xop_vpcomd:
2137   case Intrinsic::x86_xop_vpcomq:
2138   case Intrinsic::x86_xop_vpcomw:
2139     if (Value *V = simplifyX86vpcom(*II, *Builder, true))
2140       return replaceInstUsesWith(*II, V);
2141     break;
2142 
2143   case Intrinsic::x86_xop_vpcomub:
2144   case Intrinsic::x86_xop_vpcomud:
2145   case Intrinsic::x86_xop_vpcomuq:
2146   case Intrinsic::x86_xop_vpcomuw:
2147     if (Value *V = simplifyX86vpcom(*II, *Builder, false))
2148       return replaceInstUsesWith(*II, V);
2149     break;
2150 
2151   case Intrinsic::ppc_altivec_vperm:
2152     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
2153     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
2154     // a vectorshuffle for little endian, we must undo the transformation
2155     // performed on vec_perm in altivec.h.  That is, we must complement
2156     // the permutation mask with respect to 31 and reverse the order of
2157     // V1 and V2.
2158     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
2159       assert(Mask->getType()->getVectorNumElements() == 16 &&
2160              "Bad type for intrinsic!");
2161 
2162       // Check that all of the elements are integer constants or undefs.
2163       bool AllEltsOk = true;
2164       for (unsigned i = 0; i != 16; ++i) {
2165         Constant *Elt = Mask->getAggregateElement(i);
2166         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
2167           AllEltsOk = false;
2168           break;
2169         }
2170       }
2171 
2172       if (AllEltsOk) {
2173         // Cast the input vectors to byte vectors.
2174         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
2175                                             Mask->getType());
2176         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
2177                                             Mask->getType());
2178         Value *Result = UndefValue::get(Op0->getType());
2179 
2180         // Only extract each element once.
2181         Value *ExtractedElts[32];
2182         memset(ExtractedElts, 0, sizeof(ExtractedElts));
2183 
2184         for (unsigned i = 0; i != 16; ++i) {
2185           if (isa<UndefValue>(Mask->getAggregateElement(i)))
2186             continue;
2187           unsigned Idx =
2188             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
2189           Idx &= 31;  // Match the hardware behavior.
2190           if (DL.isLittleEndian())
2191             Idx = 31 - Idx;
2192 
2193           if (!ExtractedElts[Idx]) {
2194             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
2195             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
2196             ExtractedElts[Idx] =
2197               Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
2198                                             Builder->getInt32(Idx&15));
2199           }
2200 
2201           // Insert this value into the result vector.
2202           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
2203                                                 Builder->getInt32(i));
2204         }
2205         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
2206       }
2207     }
2208     break;
2209 
2210   case Intrinsic::arm_neon_vld1:
2211   case Intrinsic::arm_neon_vld2:
2212   case Intrinsic::arm_neon_vld3:
2213   case Intrinsic::arm_neon_vld4:
2214   case Intrinsic::arm_neon_vld2lane:
2215   case Intrinsic::arm_neon_vld3lane:
2216   case Intrinsic::arm_neon_vld4lane:
2217   case Intrinsic::arm_neon_vst1:
2218   case Intrinsic::arm_neon_vst2:
2219   case Intrinsic::arm_neon_vst3:
2220   case Intrinsic::arm_neon_vst4:
2221   case Intrinsic::arm_neon_vst2lane:
2222   case Intrinsic::arm_neon_vst3lane:
2223   case Intrinsic::arm_neon_vst4lane: {
2224     unsigned MemAlign =
2225         getKnownAlignment(II->getArgOperand(0), DL, II, &AC, &DT);
2226     unsigned AlignArg = II->getNumArgOperands() - 1;
2227     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
2228     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
2229       II->setArgOperand(AlignArg,
2230                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
2231                                          MemAlign, false));
2232       return II;
2233     }
2234     break;
2235   }
2236 
2237   case Intrinsic::arm_neon_vmulls:
2238   case Intrinsic::arm_neon_vmullu:
2239   case Intrinsic::aarch64_neon_smull:
2240   case Intrinsic::aarch64_neon_umull: {
2241     Value *Arg0 = II->getArgOperand(0);
2242     Value *Arg1 = II->getArgOperand(1);
2243 
2244     // Handle mul by zero first:
2245     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
2246       return replaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
2247     }
2248 
2249     // Check for constant LHS & RHS - in this case we just simplify.
2250     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
2251                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
2252     VectorType *NewVT = cast<VectorType>(II->getType());
2253     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
2254       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
2255         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
2256         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
2257 
2258         return replaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
2259       }
2260 
2261       // Couldn't simplify - canonicalize constant to the RHS.
2262       std::swap(Arg0, Arg1);
2263     }
2264 
2265     // Handle mul by one:
2266     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
2267       if (ConstantInt *Splat =
2268               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
2269         if (Splat->isOne())
2270           return CastInst::CreateIntegerCast(Arg0, II->getType(),
2271                                              /*isSigned=*/!Zext);
2272 
2273     break;
2274   }
2275 
2276   case Intrinsic::amdgcn_rcp: {
2277     if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
2278       const APFloat &ArgVal = C->getValueAPF();
2279       APFloat Val(ArgVal.getSemantics(), 1.0);
2280       APFloat::opStatus Status = Val.divide(ArgVal,
2281                                             APFloat::rmNearestTiesToEven);
2282       // Only do this if it was exact and therefore not dependent on the
2283       // rounding mode.
2284       if (Status == APFloat::opOK)
2285         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
2286     }
2287 
2288     break;
2289   }
2290   case Intrinsic::amdgcn_frexp_mant:
2291   case Intrinsic::amdgcn_frexp_exp: {
2292     Value *Src = II->getArgOperand(0);
2293     if (const ConstantFP *C = dyn_cast<ConstantFP>(Src)) {
2294       int Exp;
2295       APFloat Significand = frexp(C->getValueAPF(), Exp,
2296                                   APFloat::rmNearestTiesToEven);
2297 
2298       if (II->getIntrinsicID() == Intrinsic::amdgcn_frexp_mant) {
2299         return replaceInstUsesWith(CI, ConstantFP::get(II->getContext(),
2300                                                        Significand));
2301       }
2302 
2303       // Match instruction special case behavior.
2304       if (Exp == APFloat::IEK_NaN || Exp == APFloat::IEK_Inf)
2305         Exp = 0;
2306 
2307       return replaceInstUsesWith(CI, ConstantInt::get(II->getType(), Exp));
2308     }
2309 
2310     if (isa<UndefValue>(Src))
2311       return replaceInstUsesWith(CI, UndefValue::get(II->getType()));
2312 
2313     break;
2314   }
2315   case Intrinsic::amdgcn_class: {
2316     enum  {
2317       S_NAN = 1 << 0,        // Signaling NaN
2318       Q_NAN = 1 << 1,        // Quiet NaN
2319       N_INFINITY = 1 << 2,   // Negative infinity
2320       N_NORMAL = 1 << 3,     // Negative normal
2321       N_SUBNORMAL = 1 << 4,  // Negative subnormal
2322       N_ZERO = 1 << 5,       // Negative zero
2323       P_ZERO = 1 << 6,       // Positive zero
2324       P_SUBNORMAL = 1 << 7,  // Positive subnormal
2325       P_NORMAL = 1 << 8,     // Positive normal
2326       P_INFINITY = 1 << 9    // Positive infinity
2327     };
2328 
2329     const uint32_t FullMask = S_NAN | Q_NAN | N_INFINITY | N_NORMAL |
2330       N_SUBNORMAL | N_ZERO | P_ZERO | P_SUBNORMAL | P_NORMAL | P_INFINITY;
2331 
2332     Value *Src0 = II->getArgOperand(0);
2333     Value *Src1 = II->getArgOperand(1);
2334     const ConstantInt *CMask = dyn_cast<ConstantInt>(Src1);
2335     if (!CMask) {
2336       if (isa<UndefValue>(Src0))
2337         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2338 
2339       if (isa<UndefValue>(Src1))
2340         return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2341       break;
2342     }
2343 
2344     uint32_t Mask = CMask->getZExtValue();
2345 
2346     // If all tests are made, it doesn't matter what the value is.
2347     if ((Mask & FullMask) == FullMask)
2348       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), true));
2349 
2350     if ((Mask & FullMask) == 0)
2351       return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), false));
2352 
2353     if (Mask == (S_NAN | Q_NAN)) {
2354       // Equivalent of isnan. Replace with standard fcmp.
2355       Value *FCmp = Builder->CreateFCmpUNO(Src0, Src0);
2356       FCmp->takeName(II);
2357       return replaceInstUsesWith(*II, FCmp);
2358     }
2359 
2360     const ConstantFP *CVal = dyn_cast<ConstantFP>(Src0);
2361     if (!CVal) {
2362       if (isa<UndefValue>(Src0))
2363         return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2364 
2365       // Clamp mask to used bits
2366       if ((Mask & FullMask) != Mask) {
2367         CallInst *NewCall = Builder->CreateCall(II->getCalledFunction(),
2368           { Src0, ConstantInt::get(Src1->getType(), Mask & FullMask) }
2369         );
2370 
2371         NewCall->takeName(II);
2372         return replaceInstUsesWith(*II, NewCall);
2373       }
2374 
2375       break;
2376     }
2377 
2378     const APFloat &Val = CVal->getValueAPF();
2379 
2380     bool Result =
2381       ((Mask & S_NAN) && Val.isNaN() && Val.isSignaling()) ||
2382       ((Mask & Q_NAN) && Val.isNaN() && !Val.isSignaling()) ||
2383       ((Mask & N_INFINITY) && Val.isInfinity() && Val.isNegative()) ||
2384       ((Mask & N_NORMAL) && Val.isNormal() && Val.isNegative()) ||
2385       ((Mask & N_SUBNORMAL) && Val.isDenormal() && Val.isNegative()) ||
2386       ((Mask & N_ZERO) && Val.isZero() && Val.isNegative()) ||
2387       ((Mask & P_ZERO) && Val.isZero() && !Val.isNegative()) ||
2388       ((Mask & P_SUBNORMAL) && Val.isDenormal() && !Val.isNegative()) ||
2389       ((Mask & P_NORMAL) && Val.isNormal() && !Val.isNegative()) ||
2390       ((Mask & P_INFINITY) && Val.isInfinity() && !Val.isNegative());
2391 
2392     return replaceInstUsesWith(*II, ConstantInt::get(II->getType(), Result));
2393   }
2394   case Intrinsic::stackrestore: {
2395     // If the save is right next to the restore, remove the restore.  This can
2396     // happen when variable allocas are DCE'd.
2397     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
2398       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
2399         if (&*++SS->getIterator() == II)
2400           return eraseInstFromFunction(CI);
2401       }
2402     }
2403 
2404     // Scan down this block to see if there is another stack restore in the
2405     // same block without an intervening call/alloca.
2406     BasicBlock::iterator BI(II);
2407     TerminatorInst *TI = II->getParent()->getTerminator();
2408     bool CannotRemove = false;
2409     for (++BI; &*BI != TI; ++BI) {
2410       if (isa<AllocaInst>(BI)) {
2411         CannotRemove = true;
2412         break;
2413       }
2414       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
2415         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
2416           // If there is a stackrestore below this one, remove this one.
2417           if (II->getIntrinsicID() == Intrinsic::stackrestore)
2418             return eraseInstFromFunction(CI);
2419 
2420           // Bail if we cross over an intrinsic with side effects, such as
2421           // llvm.stacksave, llvm.read_register, or llvm.setjmp.
2422           if (II->mayHaveSideEffects()) {
2423             CannotRemove = true;
2424             break;
2425           }
2426         } else {
2427           // If we found a non-intrinsic call, we can't remove the stack
2428           // restore.
2429           CannotRemove = true;
2430           break;
2431         }
2432       }
2433     }
2434 
2435     // If the stack restore is in a return, resume, or unwind block and if there
2436     // are no allocas or calls between the restore and the return, nuke the
2437     // restore.
2438     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
2439       return eraseInstFromFunction(CI);
2440     break;
2441   }
2442   case Intrinsic::lifetime_start:
2443     // Asan needs to poison memory to detect invalid access which is possible
2444     // even for empty lifetime range.
2445     if (II->getFunction()->hasFnAttribute(Attribute::SanitizeAddress))
2446       break;
2447 
2448     if (removeTriviallyEmptyRange(*II, Intrinsic::lifetime_start,
2449                                   Intrinsic::lifetime_end, *this))
2450       return nullptr;
2451     break;
2452   case Intrinsic::assume: {
2453     Value *IIOperand = II->getArgOperand(0);
2454     // Remove an assume if it is immediately followed by an identical assume.
2455     if (match(II->getNextNode(),
2456               m_Intrinsic<Intrinsic::assume>(m_Specific(IIOperand))))
2457       return eraseInstFromFunction(CI);
2458 
2459     // Canonicalize assume(a && b) -> assume(a); assume(b);
2460     // Note: New assumption intrinsics created here are registered by
2461     // the InstCombineIRInserter object.
2462     Value *AssumeIntrinsic = II->getCalledValue(), *A, *B;
2463     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
2464       Builder->CreateCall(AssumeIntrinsic, A, II->getName());
2465       Builder->CreateCall(AssumeIntrinsic, B, II->getName());
2466       return eraseInstFromFunction(*II);
2467     }
2468     // assume(!(a || b)) -> assume(!a); assume(!b);
2469     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
2470       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
2471                           II->getName());
2472       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
2473                           II->getName());
2474       return eraseInstFromFunction(*II);
2475     }
2476 
2477     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
2478     // (if assume is valid at the load)
2479     if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
2480       Value *LHS = ICmp->getOperand(0);
2481       Value *RHS = ICmp->getOperand(1);
2482       if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
2483           isa<LoadInst>(LHS) &&
2484           isa<Constant>(RHS) &&
2485           RHS->getType()->isPointerTy() &&
2486           cast<Constant>(RHS)->isNullValue()) {
2487         LoadInst* LI = cast<LoadInst>(LHS);
2488         if (isValidAssumeForContext(II, LI, &DT)) {
2489           MDNode *MD = MDNode::get(II->getContext(), None);
2490           LI->setMetadata(LLVMContext::MD_nonnull, MD);
2491           return eraseInstFromFunction(*II);
2492         }
2493       }
2494       // TODO: apply nonnull return attributes to calls and invokes
2495       // TODO: apply range metadata for range check patterns?
2496     }
2497     // If there is a dominating assume with the same condition as this one,
2498     // then this one is redundant, and should be removed.
2499     APInt KnownZero(1, 0), KnownOne(1, 0);
2500     computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
2501     if (KnownOne.isAllOnesValue())
2502       return eraseInstFromFunction(*II);
2503 
2504     break;
2505   }
2506   case Intrinsic::experimental_gc_relocate: {
2507     // Translate facts known about a pointer before relocating into
2508     // facts about the relocate value, while being careful to
2509     // preserve relocation semantics.
2510     Value *DerivedPtr = cast<GCRelocateInst>(II)->getDerivedPtr();
2511 
2512     // Remove the relocation if unused, note that this check is required
2513     // to prevent the cases below from looping forever.
2514     if (II->use_empty())
2515       return eraseInstFromFunction(*II);
2516 
2517     // Undef is undef, even after relocation.
2518     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
2519     // most practical collectors, but there was discussion in the review thread
2520     // about whether it was legal for all possible collectors.
2521     if (isa<UndefValue>(DerivedPtr))
2522       // Use undef of gc_relocate's type to replace it.
2523       return replaceInstUsesWith(*II, UndefValue::get(II->getType()));
2524 
2525     if (auto *PT = dyn_cast<PointerType>(II->getType())) {
2526       // The relocation of null will be null for most any collector.
2527       // TODO: provide a hook for this in GCStrategy.  There might be some
2528       // weird collector this property does not hold for.
2529       if (isa<ConstantPointerNull>(DerivedPtr))
2530         // Use null-pointer of gc_relocate's type to replace it.
2531         return replaceInstUsesWith(*II, ConstantPointerNull::get(PT));
2532 
2533       // isKnownNonNull -> nonnull attribute
2534       if (isKnownNonNullAt(DerivedPtr, II, &DT))
2535         II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
2536     }
2537 
2538     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
2539     // Canonicalize on the type from the uses to the defs
2540 
2541     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
2542     break;
2543   }
2544   }
2545 
2546   return visitCallSite(II);
2547 }
2548 
2549 // InvokeInst simplification
2550 //
2551 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
2552   return visitCallSite(&II);
2553 }
2554 
2555 /// If this cast does not affect the value passed through the varargs area, we
2556 /// can eliminate the use of the cast.
2557 static bool isSafeToEliminateVarargsCast(const CallSite CS,
2558                                          const DataLayout &DL,
2559                                          const CastInst *const CI,
2560                                          const int ix) {
2561   if (!CI->isLosslessCast())
2562     return false;
2563 
2564   // If this is a GC intrinsic, avoid munging types.  We need types for
2565   // statepoint reconstruction in SelectionDAG.
2566   // TODO: This is probably something which should be expanded to all
2567   // intrinsics since the entire point of intrinsics is that
2568   // they are understandable by the optimizer.
2569   if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
2570     return false;
2571 
2572   // The size of ByVal or InAlloca arguments is derived from the type, so we
2573   // can't change to a type with a different size.  If the size were
2574   // passed explicitly we could avoid this check.
2575   if (!CS.isByValOrInAllocaArgument(ix))
2576     return true;
2577 
2578   Type* SrcTy =
2579             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
2580   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
2581   if (!SrcTy->isSized() || !DstTy->isSized())
2582     return false;
2583   if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
2584     return false;
2585   return true;
2586 }
2587 
2588 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
2589   if (!CI->getCalledFunction()) return nullptr;
2590 
2591   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
2592     replaceInstUsesWith(*From, With);
2593   };
2594   LibCallSimplifier Simplifier(DL, &TLI, InstCombineRAUW);
2595   if (Value *With = Simplifier.optimizeCall(CI)) {
2596     ++NumSimplified;
2597     return CI->use_empty() ? CI : replaceInstUsesWith(*CI, With);
2598   }
2599 
2600   return nullptr;
2601 }
2602 
2603 static IntrinsicInst *findInitTrampolineFromAlloca(Value *TrampMem) {
2604   // Strip off at most one level of pointer casts, looking for an alloca.  This
2605   // is good enough in practice and simpler than handling any number of casts.
2606   Value *Underlying = TrampMem->stripPointerCasts();
2607   if (Underlying != TrampMem &&
2608       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
2609     return nullptr;
2610   if (!isa<AllocaInst>(Underlying))
2611     return nullptr;
2612 
2613   IntrinsicInst *InitTrampoline = nullptr;
2614   for (User *U : TrampMem->users()) {
2615     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
2616     if (!II)
2617       return nullptr;
2618     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
2619       if (InitTrampoline)
2620         // More than one init_trampoline writes to this value.  Give up.
2621         return nullptr;
2622       InitTrampoline = II;
2623       continue;
2624     }
2625     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
2626       // Allow any number of calls to adjust.trampoline.
2627       continue;
2628     return nullptr;
2629   }
2630 
2631   // No call to init.trampoline found.
2632   if (!InitTrampoline)
2633     return nullptr;
2634 
2635   // Check that the alloca is being used in the expected way.
2636   if (InitTrampoline->getOperand(0) != TrampMem)
2637     return nullptr;
2638 
2639   return InitTrampoline;
2640 }
2641 
2642 static IntrinsicInst *findInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
2643                                                Value *TrampMem) {
2644   // Visit all the previous instructions in the basic block, and try to find a
2645   // init.trampoline which has a direct path to the adjust.trampoline.
2646   for (BasicBlock::iterator I = AdjustTramp->getIterator(),
2647                             E = AdjustTramp->getParent()->begin();
2648        I != E;) {
2649     Instruction *Inst = &*--I;
2650     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2651       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
2652           II->getOperand(0) == TrampMem)
2653         return II;
2654     if (Inst->mayWriteToMemory())
2655       return nullptr;
2656   }
2657   return nullptr;
2658 }
2659 
2660 // Given a call to llvm.adjust.trampoline, find and return the corresponding
2661 // call to llvm.init.trampoline if the call to the trampoline can be optimized
2662 // to a direct call to a function.  Otherwise return NULL.
2663 //
2664 static IntrinsicInst *findInitTrampoline(Value *Callee) {
2665   Callee = Callee->stripPointerCasts();
2666   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
2667   if (!AdjustTramp ||
2668       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
2669     return nullptr;
2670 
2671   Value *TrampMem = AdjustTramp->getOperand(0);
2672 
2673   if (IntrinsicInst *IT = findInitTrampolineFromAlloca(TrampMem))
2674     return IT;
2675   if (IntrinsicInst *IT = findInitTrampolineFromBB(AdjustTramp, TrampMem))
2676     return IT;
2677   return nullptr;
2678 }
2679 
2680 /// Improvements for call and invoke instructions.
2681 Instruction *InstCombiner::visitCallSite(CallSite CS) {
2682   if (isAllocLikeFn(CS.getInstruction(), &TLI))
2683     return visitAllocSite(*CS.getInstruction());
2684 
2685   bool Changed = false;
2686 
2687   // Mark any parameters that are known to be non-null with the nonnull
2688   // attribute.  This is helpful for inlining calls to functions with null
2689   // checks on their arguments.
2690   SmallVector<unsigned, 4> Indices;
2691   unsigned ArgNo = 0;
2692 
2693   for (Value *V : CS.args()) {
2694     if (V->getType()->isPointerTy() &&
2695         !CS.paramHasAttr(ArgNo + 1, Attribute::NonNull) &&
2696         isKnownNonNullAt(V, CS.getInstruction(), &DT))
2697       Indices.push_back(ArgNo + 1);
2698     ArgNo++;
2699   }
2700 
2701   assert(ArgNo == CS.arg_size() && "sanity check");
2702 
2703   if (!Indices.empty()) {
2704     AttributeSet AS = CS.getAttributes();
2705     LLVMContext &Ctx = CS.getInstruction()->getContext();
2706     AS = AS.addAttribute(Ctx, Indices,
2707                          Attribute::get(Ctx, Attribute::NonNull));
2708     CS.setAttributes(AS);
2709     Changed = true;
2710   }
2711 
2712   // If the callee is a pointer to a function, attempt to move any casts to the
2713   // arguments of the call/invoke.
2714   Value *Callee = CS.getCalledValue();
2715   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
2716     return nullptr;
2717 
2718   if (Function *CalleeF = dyn_cast<Function>(Callee)) {
2719     // Remove the convergent attr on calls when the callee is not convergent.
2720     if (CS.isConvergent() && !CalleeF->isConvergent() &&
2721         !CalleeF->isIntrinsic()) {
2722       DEBUG(dbgs() << "Removing convergent attr from instr "
2723                    << CS.getInstruction() << "\n");
2724       CS.setNotConvergent();
2725       return CS.getInstruction();
2726     }
2727 
2728     // If the call and callee calling conventions don't match, this call must
2729     // be unreachable, as the call is undefined.
2730     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
2731         // Only do this for calls to a function with a body.  A prototype may
2732         // not actually end up matching the implementation's calling conv for a
2733         // variety of reasons (e.g. it may be written in assembly).
2734         !CalleeF->isDeclaration()) {
2735       Instruction *OldCall = CS.getInstruction();
2736       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2737                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2738                                   OldCall);
2739       // If OldCall does not return void then replaceAllUsesWith undef.
2740       // This allows ValueHandlers and custom metadata to adjust itself.
2741       if (!OldCall->getType()->isVoidTy())
2742         replaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
2743       if (isa<CallInst>(OldCall))
2744         return eraseInstFromFunction(*OldCall);
2745 
2746       // We cannot remove an invoke, because it would change the CFG, just
2747       // change the callee to a null pointer.
2748       cast<InvokeInst>(OldCall)->setCalledFunction(
2749                                     Constant::getNullValue(CalleeF->getType()));
2750       return nullptr;
2751     }
2752   }
2753 
2754   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
2755     // If CS does not return void then replaceAllUsesWith undef.
2756     // This allows ValueHandlers and custom metadata to adjust itself.
2757     if (!CS.getInstruction()->getType()->isVoidTy())
2758       replaceInstUsesWith(*CS.getInstruction(),
2759                           UndefValue::get(CS.getInstruction()->getType()));
2760 
2761     if (isa<InvokeInst>(CS.getInstruction())) {
2762       // Can't remove an invoke because we cannot change the CFG.
2763       return nullptr;
2764     }
2765 
2766     // This instruction is not reachable, just remove it.  We insert a store to
2767     // undef so that we know that this code is not reachable, despite the fact
2768     // that we can't modify the CFG here.
2769     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
2770                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
2771                   CS.getInstruction());
2772 
2773     return eraseInstFromFunction(*CS.getInstruction());
2774   }
2775 
2776   if (IntrinsicInst *II = findInitTrampoline(Callee))
2777     return transformCallThroughTrampoline(CS, II);
2778 
2779   PointerType *PTy = cast<PointerType>(Callee->getType());
2780   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
2781   if (FTy->isVarArg()) {
2782     int ix = FTy->getNumParams();
2783     // See if we can optimize any arguments passed through the varargs area of
2784     // the call.
2785     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
2786            E = CS.arg_end(); I != E; ++I, ++ix) {
2787       CastInst *CI = dyn_cast<CastInst>(*I);
2788       if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
2789         *I = CI->getOperand(0);
2790         Changed = true;
2791       }
2792     }
2793   }
2794 
2795   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
2796     // Inline asm calls cannot throw - mark them 'nounwind'.
2797     CS.setDoesNotThrow();
2798     Changed = true;
2799   }
2800 
2801   // Try to optimize the call if possible, we require DataLayout for most of
2802   // this.  None of these calls are seen as possibly dead so go ahead and
2803   // delete the instruction now.
2804   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
2805     Instruction *I = tryOptimizeCall(CI);
2806     // If we changed something return the result, etc. Otherwise let
2807     // the fallthrough check.
2808     if (I) return eraseInstFromFunction(*I);
2809   }
2810 
2811   return Changed ? CS.getInstruction() : nullptr;
2812 }
2813 
2814 /// If the callee is a constexpr cast of a function, attempt to move the cast to
2815 /// the arguments of the call/invoke.
2816 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
2817   auto *Callee = dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
2818   if (!Callee)
2819     return false;
2820 
2821   // The prototype of a thunk is a lie. Don't directly call such a function.
2822   if (Callee->hasFnAttribute("thunk"))
2823     return false;
2824 
2825   Instruction *Caller = CS.getInstruction();
2826   const AttributeSet &CallerPAL = CS.getAttributes();
2827 
2828   // Okay, this is a cast from a function to a different type.  Unless doing so
2829   // would cause a type conversion of one of our arguments, change this call to
2830   // be a direct call with arguments casted to the appropriate types.
2831   //
2832   FunctionType *FT = Callee->getFunctionType();
2833   Type *OldRetTy = Caller->getType();
2834   Type *NewRetTy = FT->getReturnType();
2835 
2836   // Check to see if we are changing the return type...
2837   if (OldRetTy != NewRetTy) {
2838 
2839     if (NewRetTy->isStructTy())
2840       return false; // TODO: Handle multiple return values.
2841 
2842     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
2843       if (Callee->isDeclaration())
2844         return false;   // Cannot transform this return value.
2845 
2846       if (!Caller->use_empty() &&
2847           // void -> non-void is handled specially
2848           !NewRetTy->isVoidTy())
2849         return false;   // Cannot transform this return value.
2850     }
2851 
2852     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
2853       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
2854       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
2855         return false;   // Attribute not compatible with transformed value.
2856     }
2857 
2858     // If the callsite is an invoke instruction, and the return value is used by
2859     // a PHI node in a successor, we cannot change the return type of the call
2860     // because there is no place to put the cast instruction (without breaking
2861     // the critical edge).  Bail out in this case.
2862     if (!Caller->use_empty())
2863       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
2864         for (User *U : II->users())
2865           if (PHINode *PN = dyn_cast<PHINode>(U))
2866             if (PN->getParent() == II->getNormalDest() ||
2867                 PN->getParent() == II->getUnwindDest())
2868               return false;
2869   }
2870 
2871   unsigned NumActualArgs = CS.arg_size();
2872   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
2873 
2874   // Prevent us turning:
2875   // declare void @takes_i32_inalloca(i32* inalloca)
2876   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
2877   //
2878   // into:
2879   //  call void @takes_i32_inalloca(i32* null)
2880   //
2881   //  Similarly, avoid folding away bitcasts of byval calls.
2882   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
2883       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
2884     return false;
2885 
2886   CallSite::arg_iterator AI = CS.arg_begin();
2887   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
2888     Type *ParamTy = FT->getParamType(i);
2889     Type *ActTy = (*AI)->getType();
2890 
2891     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
2892       return false;   // Cannot transform this parameter value.
2893 
2894     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
2895           overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
2896       return false;   // Attribute not compatible with transformed value.
2897 
2898     if (CS.isInAllocaArgument(i))
2899       return false;   // Cannot transform to and from inalloca.
2900 
2901     // If the parameter is passed as a byval argument, then we have to have a
2902     // sized type and the sized type has to have the same size as the old type.
2903     if (ParamTy != ActTy &&
2904         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
2905                                                          Attribute::ByVal)) {
2906       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
2907       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
2908         return false;
2909 
2910       Type *CurElTy = ActTy->getPointerElementType();
2911       if (DL.getTypeAllocSize(CurElTy) !=
2912           DL.getTypeAllocSize(ParamPTy->getElementType()))
2913         return false;
2914     }
2915   }
2916 
2917   if (Callee->isDeclaration()) {
2918     // Do not delete arguments unless we have a function body.
2919     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
2920       return false;
2921 
2922     // If the callee is just a declaration, don't change the varargsness of the
2923     // call.  We don't want to introduce a varargs call where one doesn't
2924     // already exist.
2925     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
2926     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
2927       return false;
2928 
2929     // If both the callee and the cast type are varargs, we still have to make
2930     // sure the number of fixed parameters are the same or we have the same
2931     // ABI issues as if we introduce a varargs call.
2932     if (FT->isVarArg() &&
2933         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
2934         FT->getNumParams() !=
2935         cast<FunctionType>(APTy->getElementType())->getNumParams())
2936       return false;
2937   }
2938 
2939   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
2940       !CallerPAL.isEmpty())
2941     // In this case we have more arguments than the new function type, but we
2942     // won't be dropping them.  Check that these extra arguments have attributes
2943     // that are compatible with being a vararg call argument.
2944     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
2945       unsigned Index = CallerPAL.getSlotIndex(i - 1);
2946       if (Index <= FT->getNumParams())
2947         break;
2948 
2949       // Check if it has an attribute that's incompatible with varargs.
2950       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
2951       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
2952         return false;
2953     }
2954 
2955 
2956   // Okay, we decided that this is a safe thing to do: go ahead and start
2957   // inserting cast instructions as necessary.
2958   std::vector<Value*> Args;
2959   Args.reserve(NumActualArgs);
2960   SmallVector<AttributeSet, 8> attrVec;
2961   attrVec.reserve(NumCommonArgs);
2962 
2963   // Get any return attributes.
2964   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
2965 
2966   // If the return value is not being used, the type may not be compatible
2967   // with the existing attributes.  Wipe out any problematic attributes.
2968   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
2969 
2970   // Add the new return attributes.
2971   if (RAttrs.hasAttributes())
2972     attrVec.push_back(AttributeSet::get(Caller->getContext(),
2973                                         AttributeSet::ReturnIndex, RAttrs));
2974 
2975   AI = CS.arg_begin();
2976   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
2977     Type *ParamTy = FT->getParamType(i);
2978 
2979     if ((*AI)->getType() == ParamTy) {
2980       Args.push_back(*AI);
2981     } else {
2982       Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
2983     }
2984 
2985     // Add any parameter attributes.
2986     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
2987     if (PAttrs.hasAttributes())
2988       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
2989                                           PAttrs));
2990   }
2991 
2992   // If the function takes more arguments than the call was taking, add them
2993   // now.
2994   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
2995     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
2996 
2997   // If we are removing arguments to the function, emit an obnoxious warning.
2998   if (FT->getNumParams() < NumActualArgs) {
2999     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
3000     if (FT->isVarArg()) {
3001       // Add all of the arguments in their promoted form to the arg list.
3002       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3003         Type *PTy = getPromotedType((*AI)->getType());
3004         if (PTy != (*AI)->getType()) {
3005           // Must promote to pass through va_arg area!
3006           Instruction::CastOps opcode =
3007             CastInst::getCastOpcode(*AI, false, PTy, false);
3008           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
3009         } else {
3010           Args.push_back(*AI);
3011         }
3012 
3013         // Add any parameter attributes.
3014         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
3015         if (PAttrs.hasAttributes())
3016           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
3017                                               PAttrs));
3018       }
3019     }
3020   }
3021 
3022   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
3023   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
3024     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
3025 
3026   if (NewRetTy->isVoidTy())
3027     Caller->setName("");   // Void type should not have a name.
3028 
3029   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
3030                                                        attrVec);
3031 
3032   SmallVector<OperandBundleDef, 1> OpBundles;
3033   CS.getOperandBundlesAsDefs(OpBundles);
3034 
3035   Instruction *NC;
3036   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3037     NC = Builder->CreateInvoke(Callee, II->getNormalDest(), II->getUnwindDest(),
3038                                Args, OpBundles);
3039     NC->takeName(II);
3040     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
3041     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
3042   } else {
3043     CallInst *CI = cast<CallInst>(Caller);
3044     NC = Builder->CreateCall(Callee, Args, OpBundles);
3045     NC->takeName(CI);
3046     cast<CallInst>(NC)->setTailCallKind(CI->getTailCallKind());
3047     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
3048     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
3049   }
3050 
3051   // Insert a cast of the return type as necessary.
3052   Value *NV = NC;
3053   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
3054     if (!NV->getType()->isVoidTy()) {
3055       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
3056       NC->setDebugLoc(Caller->getDebugLoc());
3057 
3058       // If this is an invoke instruction, we should insert it after the first
3059       // non-phi, instruction in the normal successor block.
3060       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3061         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
3062         InsertNewInstBefore(NC, *I);
3063       } else {
3064         // Otherwise, it's a call, just insert cast right after the call.
3065         InsertNewInstBefore(NC, *Caller);
3066       }
3067       Worklist.AddUsersToWorkList(*Caller);
3068     } else {
3069       NV = UndefValue::get(Caller->getType());
3070     }
3071   }
3072 
3073   if (!Caller->use_empty())
3074     replaceInstUsesWith(*Caller, NV);
3075   else if (Caller->hasValueHandle()) {
3076     if (OldRetTy == NV->getType())
3077       ValueHandleBase::ValueIsRAUWd(Caller, NV);
3078     else
3079       // We cannot call ValueIsRAUWd with a different type, and the
3080       // actual tracked value will disappear.
3081       ValueHandleBase::ValueIsDeleted(Caller);
3082   }
3083 
3084   eraseInstFromFunction(*Caller);
3085   return true;
3086 }
3087 
3088 /// Turn a call to a function created by init_trampoline / adjust_trampoline
3089 /// intrinsic pair into a direct call to the underlying function.
3090 Instruction *
3091 InstCombiner::transformCallThroughTrampoline(CallSite CS,
3092                                              IntrinsicInst *Tramp) {
3093   Value *Callee = CS.getCalledValue();
3094   PointerType *PTy = cast<PointerType>(Callee->getType());
3095   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3096   const AttributeSet &Attrs = CS.getAttributes();
3097 
3098   // If the call already has the 'nest' attribute somewhere then give up -
3099   // otherwise 'nest' would occur twice after splicing in the chain.
3100   if (Attrs.hasAttrSomewhere(Attribute::Nest))
3101     return nullptr;
3102 
3103   assert(Tramp &&
3104          "transformCallThroughTrampoline called with incorrect CallSite.");
3105 
3106   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
3107   FunctionType *NestFTy = cast<FunctionType>(NestF->getValueType());
3108 
3109   const AttributeSet &NestAttrs = NestF->getAttributes();
3110   if (!NestAttrs.isEmpty()) {
3111     unsigned NestIdx = 1;
3112     Type *NestTy = nullptr;
3113     AttributeSet NestAttr;
3114 
3115     // Look for a parameter marked with the 'nest' attribute.
3116     for (FunctionType::param_iterator I = NestFTy->param_begin(),
3117          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
3118       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
3119         // Record the parameter type and any other attributes.
3120         NestTy = *I;
3121         NestAttr = NestAttrs.getParamAttributes(NestIdx);
3122         break;
3123       }
3124 
3125     if (NestTy) {
3126       Instruction *Caller = CS.getInstruction();
3127       std::vector<Value*> NewArgs;
3128       NewArgs.reserve(CS.arg_size() + 1);
3129 
3130       SmallVector<AttributeSet, 8> NewAttrs;
3131       NewAttrs.reserve(Attrs.getNumSlots() + 1);
3132 
3133       // Insert the nest argument into the call argument list, which may
3134       // mean appending it.  Likewise for attributes.
3135 
3136       // Add any result attributes.
3137       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
3138         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3139                                              Attrs.getRetAttributes()));
3140 
3141       {
3142         unsigned Idx = 1;
3143         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
3144         do {
3145           if (Idx == NestIdx) {
3146             // Add the chain argument and attributes.
3147             Value *NestVal = Tramp->getArgOperand(2);
3148             if (NestVal->getType() != NestTy)
3149               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
3150             NewArgs.push_back(NestVal);
3151             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3152                                                  NestAttr));
3153           }
3154 
3155           if (I == E)
3156             break;
3157 
3158           // Add the original argument and attributes.
3159           NewArgs.push_back(*I);
3160           AttributeSet Attr = Attrs.getParamAttributes(Idx);
3161           if (Attr.hasAttributes(Idx)) {
3162             AttrBuilder B(Attr, Idx);
3163             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
3164                                                  Idx + (Idx >= NestIdx), B));
3165           }
3166 
3167           ++Idx;
3168           ++I;
3169         } while (true);
3170       }
3171 
3172       // Add any function attributes.
3173       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
3174         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
3175                                              Attrs.getFnAttributes()));
3176 
3177       // The trampoline may have been bitcast to a bogus type (FTy).
3178       // Handle this by synthesizing a new function type, equal to FTy
3179       // with the chain parameter inserted.
3180 
3181       std::vector<Type*> NewTypes;
3182       NewTypes.reserve(FTy->getNumParams()+1);
3183 
3184       // Insert the chain's type into the list of parameter types, which may
3185       // mean appending it.
3186       {
3187         unsigned Idx = 1;
3188         FunctionType::param_iterator I = FTy->param_begin(),
3189           E = FTy->param_end();
3190 
3191         do {
3192           if (Idx == NestIdx)
3193             // Add the chain's type.
3194             NewTypes.push_back(NestTy);
3195 
3196           if (I == E)
3197             break;
3198 
3199           // Add the original type.
3200           NewTypes.push_back(*I);
3201 
3202           ++Idx;
3203           ++I;
3204         } while (true);
3205       }
3206 
3207       // Replace the trampoline call with a direct call.  Let the generic
3208       // code sort out any function type mismatches.
3209       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
3210                                                 FTy->isVarArg());
3211       Constant *NewCallee =
3212         NestF->getType() == PointerType::getUnqual(NewFTy) ?
3213         NestF : ConstantExpr::getBitCast(NestF,
3214                                          PointerType::getUnqual(NewFTy));
3215       const AttributeSet &NewPAL =
3216           AttributeSet::get(FTy->getContext(), NewAttrs);
3217 
3218       SmallVector<OperandBundleDef, 1> OpBundles;
3219       CS.getOperandBundlesAsDefs(OpBundles);
3220 
3221       Instruction *NewCaller;
3222       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3223         NewCaller = InvokeInst::Create(NewCallee,
3224                                        II->getNormalDest(), II->getUnwindDest(),
3225                                        NewArgs, OpBundles);
3226         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
3227         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
3228       } else {
3229         NewCaller = CallInst::Create(NewCallee, NewArgs, OpBundles);
3230         cast<CallInst>(NewCaller)->setTailCallKind(
3231             cast<CallInst>(Caller)->getTailCallKind());
3232         cast<CallInst>(NewCaller)->setCallingConv(
3233             cast<CallInst>(Caller)->getCallingConv());
3234         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
3235       }
3236 
3237       return NewCaller;
3238     }
3239   }
3240 
3241   // Replace the trampoline call with a direct call.  Since there is no 'nest'
3242   // parameter, there is no need to adjust the argument list.  Let the generic
3243   // code sort out any function type mismatches.
3244   Constant *NewCallee =
3245     NestF->getType() == PTy ? NestF :
3246                               ConstantExpr::getBitCast(NestF, PTy);
3247   CS.setCalledFunction(NewCallee);
3248   return CS.getInstruction();
3249 }
3250