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