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