1 //===-- X86InstCombineIntrinsic.cpp - X86 specific InstCombine pass -------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 /// This file implements a TargetTransformInfo analysis pass specific to the
10 /// X86 target machine. It uses the target's detailed information to provide
11 /// more precise answers to certain TTI queries, while letting the target
12 /// independent and default TTI implementations handle the rest.
13 ///
14 //===----------------------------------------------------------------------===//
15 
16 #include "X86TargetTransformInfo.h"
17 #include "llvm/IR/IntrinsicInst.h"
18 #include "llvm/IR/IntrinsicsX86.h"
19 #include "llvm/Transforms/InstCombine/InstCombiner.h"
20 
21 using namespace llvm;
22 
23 #define DEBUG_TYPE "x86tti"
24 
25 /// Return a constant boolean vector that has true elements in all positions
26 /// where the input constant data vector has an element with the sign bit set.
27 static Constant *getNegativeIsTrueBoolVec(ConstantDataVector *V) {
28   SmallVector<Constant *, 32> BoolVec;
29   IntegerType *BoolTy = Type::getInt1Ty(V->getContext());
30   for (unsigned I = 0, E = V->getNumElements(); I != E; ++I) {
31     Constant *Elt = V->getElementAsConstant(I);
32     assert((isa<ConstantInt>(Elt) || isa<ConstantFP>(Elt)) &&
33            "Unexpected constant data vector element type");
34     bool Sign = V->getElementType()->isIntegerTy()
35                     ? cast<ConstantInt>(Elt)->isNegative()
36                     : cast<ConstantFP>(Elt)->isNegative();
37     BoolVec.push_back(ConstantInt::get(BoolTy, Sign));
38   }
39   return ConstantVector::get(BoolVec);
40 }
41 
42 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
43 // XMM register mask efficiently, we could transform all x86 masked intrinsics
44 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
45 static Instruction *simplifyX86MaskedLoad(IntrinsicInst &II, InstCombiner &IC) {
46   Value *Ptr = II.getOperand(0);
47   Value *Mask = II.getOperand(1);
48   Constant *ZeroVec = Constant::getNullValue(II.getType());
49 
50   // Special case a zero mask since that's not a ConstantDataVector.
51   // This masked load instruction creates a zero vector.
52   if (isa<ConstantAggregateZero>(Mask))
53     return IC.replaceInstUsesWith(II, ZeroVec);
54 
55   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
56   if (!ConstMask)
57     return nullptr;
58 
59   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
60   // to allow target-independent optimizations.
61 
62   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
63   // the LLVM intrinsic definition for the pointer argument.
64   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
65   PointerType *VecPtrTy = PointerType::get(II.getType(), AddrSpace);
66   Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
67 
68   // Second, convert the x86 XMM integer vector mask to a vector of bools based
69   // on each element's most significant bit (the sign bit).
70   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
71 
72   // The pass-through vector for an x86 masked load is a zero vector.
73   CallInst *NewMaskedLoad =
74       IC.Builder.CreateMaskedLoad(PtrCast, Align(1), BoolMask, ZeroVec);
75   return IC.replaceInstUsesWith(II, NewMaskedLoad);
76 }
77 
78 // TODO: If the x86 backend knew how to convert a bool vector mask back to an
79 // XMM register mask efficiently, we could transform all x86 masked intrinsics
80 // to LLVM masked intrinsics and remove the x86 masked intrinsic defs.
81 static bool simplifyX86MaskedStore(IntrinsicInst &II, InstCombiner &IC) {
82   Value *Ptr = II.getOperand(0);
83   Value *Mask = II.getOperand(1);
84   Value *Vec = II.getOperand(2);
85 
86   // Special case a zero mask since that's not a ConstantDataVector:
87   // this masked store instruction does nothing.
88   if (isa<ConstantAggregateZero>(Mask)) {
89     IC.eraseInstFromFunction(II);
90     return true;
91   }
92 
93   // The SSE2 version is too weird (eg, unaligned but non-temporal) to do
94   // anything else at this level.
95   if (II.getIntrinsicID() == Intrinsic::x86_sse2_maskmov_dqu)
96     return false;
97 
98   auto *ConstMask = dyn_cast<ConstantDataVector>(Mask);
99   if (!ConstMask)
100     return false;
101 
102   // The mask is constant. Convert this x86 intrinsic to the LLVM instrinsic
103   // to allow target-independent optimizations.
104 
105   // First, cast the x86 intrinsic scalar pointer to a vector pointer to match
106   // the LLVM intrinsic definition for the pointer argument.
107   unsigned AddrSpace = cast<PointerType>(Ptr->getType())->getAddressSpace();
108   PointerType *VecPtrTy = PointerType::get(Vec->getType(), AddrSpace);
109   Value *PtrCast = IC.Builder.CreateBitCast(Ptr, VecPtrTy, "castvec");
110 
111   // Second, convert the x86 XMM integer vector mask to a vector of bools based
112   // on each element's most significant bit (the sign bit).
113   Constant *BoolMask = getNegativeIsTrueBoolVec(ConstMask);
114 
115   IC.Builder.CreateMaskedStore(Vec, PtrCast, Align(1), BoolMask);
116 
117   // 'Replace uses' doesn't work for stores. Erase the original masked store.
118   IC.eraseInstFromFunction(II);
119   return true;
120 }
121 
122 static Value *simplifyX86immShift(const IntrinsicInst &II,
123                                   InstCombiner::BuilderTy &Builder) {
124   bool LogicalShift = false;
125   bool ShiftLeft = false;
126   bool IsImm = false;
127 
128   switch (II.getIntrinsicID()) {
129   default:
130     llvm_unreachable("Unexpected intrinsic!");
131   case Intrinsic::x86_sse2_psrai_d:
132   case Intrinsic::x86_sse2_psrai_w:
133   case Intrinsic::x86_avx2_psrai_d:
134   case Intrinsic::x86_avx2_psrai_w:
135   case Intrinsic::x86_avx512_psrai_q_128:
136   case Intrinsic::x86_avx512_psrai_q_256:
137   case Intrinsic::x86_avx512_psrai_d_512:
138   case Intrinsic::x86_avx512_psrai_q_512:
139   case Intrinsic::x86_avx512_psrai_w_512:
140     IsImm = true;
141     LLVM_FALLTHROUGH;
142   case Intrinsic::x86_sse2_psra_d:
143   case Intrinsic::x86_sse2_psra_w:
144   case Intrinsic::x86_avx2_psra_d:
145   case Intrinsic::x86_avx2_psra_w:
146   case Intrinsic::x86_avx512_psra_q_128:
147   case Intrinsic::x86_avx512_psra_q_256:
148   case Intrinsic::x86_avx512_psra_d_512:
149   case Intrinsic::x86_avx512_psra_q_512:
150   case Intrinsic::x86_avx512_psra_w_512:
151     LogicalShift = false;
152     ShiftLeft = false;
153     break;
154   case Intrinsic::x86_sse2_psrli_d:
155   case Intrinsic::x86_sse2_psrli_q:
156   case Intrinsic::x86_sse2_psrli_w:
157   case Intrinsic::x86_avx2_psrli_d:
158   case Intrinsic::x86_avx2_psrli_q:
159   case Intrinsic::x86_avx2_psrli_w:
160   case Intrinsic::x86_avx512_psrli_d_512:
161   case Intrinsic::x86_avx512_psrli_q_512:
162   case Intrinsic::x86_avx512_psrli_w_512:
163     IsImm = true;
164     LLVM_FALLTHROUGH;
165   case Intrinsic::x86_sse2_psrl_d:
166   case Intrinsic::x86_sse2_psrl_q:
167   case Intrinsic::x86_sse2_psrl_w:
168   case Intrinsic::x86_avx2_psrl_d:
169   case Intrinsic::x86_avx2_psrl_q:
170   case Intrinsic::x86_avx2_psrl_w:
171   case Intrinsic::x86_avx512_psrl_d_512:
172   case Intrinsic::x86_avx512_psrl_q_512:
173   case Intrinsic::x86_avx512_psrl_w_512:
174     LogicalShift = true;
175     ShiftLeft = false;
176     break;
177   case Intrinsic::x86_sse2_pslli_d:
178   case Intrinsic::x86_sse2_pslli_q:
179   case Intrinsic::x86_sse2_pslli_w:
180   case Intrinsic::x86_avx2_pslli_d:
181   case Intrinsic::x86_avx2_pslli_q:
182   case Intrinsic::x86_avx2_pslli_w:
183   case Intrinsic::x86_avx512_pslli_d_512:
184   case Intrinsic::x86_avx512_pslli_q_512:
185   case Intrinsic::x86_avx512_pslli_w_512:
186     IsImm = true;
187     LLVM_FALLTHROUGH;
188   case Intrinsic::x86_sse2_psll_d:
189   case Intrinsic::x86_sse2_psll_q:
190   case Intrinsic::x86_sse2_psll_w:
191   case Intrinsic::x86_avx2_psll_d:
192   case Intrinsic::x86_avx2_psll_q:
193   case Intrinsic::x86_avx2_psll_w:
194   case Intrinsic::x86_avx512_psll_d_512:
195   case Intrinsic::x86_avx512_psll_q_512:
196   case Intrinsic::x86_avx512_psll_w_512:
197     LogicalShift = true;
198     ShiftLeft = true;
199     break;
200   }
201   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
202 
203   auto Vec = II.getArgOperand(0);
204   auto Amt = II.getArgOperand(1);
205   auto VT = cast<FixedVectorType>(Vec->getType());
206   auto SVT = VT->getElementType();
207   auto AmtVT = Amt->getType();
208   unsigned VWidth = VT->getNumElements();
209   unsigned BitWidth = SVT->getPrimitiveSizeInBits();
210 
211   // If the shift amount is guaranteed to be in-range we can replace it with a
212   // generic shift. If its guaranteed to be out of range, logical shifts combine
213   // to zero and arithmetic shifts are clamped to (BitWidth - 1).
214   if (IsImm) {
215     assert(AmtVT->isIntegerTy(32) && "Unexpected shift-by-immediate type");
216     KnownBits KnownAmtBits =
217         llvm::computeKnownBits(Amt, II.getModule()->getDataLayout());
218     if (KnownAmtBits.getMaxValue().ult(BitWidth)) {
219       Amt = Builder.CreateZExtOrTrunc(Amt, SVT);
220       Amt = Builder.CreateVectorSplat(VWidth, Amt);
221       return (LogicalShift ? (ShiftLeft ? Builder.CreateShl(Vec, Amt)
222                                         : Builder.CreateLShr(Vec, Amt))
223                            : Builder.CreateAShr(Vec, Amt));
224     }
225     if (KnownAmtBits.getMinValue().uge(BitWidth)) {
226       if (LogicalShift)
227         return ConstantAggregateZero::get(VT);
228       Amt = ConstantInt::get(SVT, BitWidth - 1);
229       return Builder.CreateAShr(Vec, Builder.CreateVectorSplat(VWidth, Amt));
230     }
231   } else {
232     // Ensure the first element has an in-range value and the rest of the
233     // elements in the bottom 64 bits are zero.
234     assert(AmtVT->isVectorTy() && AmtVT->getPrimitiveSizeInBits() == 128 &&
235            cast<VectorType>(AmtVT)->getElementType() == SVT &&
236            "Unexpected shift-by-scalar type");
237     unsigned NumAmtElts = cast<FixedVectorType>(AmtVT)->getNumElements();
238     APInt DemandedLower = APInt::getOneBitSet(NumAmtElts, 0);
239     APInt DemandedUpper = APInt::getBitsSet(NumAmtElts, 1, NumAmtElts / 2);
240     KnownBits KnownLowerBits = llvm::computeKnownBits(
241         Amt, DemandedLower, II.getModule()->getDataLayout());
242     KnownBits KnownUpperBits = llvm::computeKnownBits(
243         Amt, DemandedUpper, II.getModule()->getDataLayout());
244     if (KnownLowerBits.getMaxValue().ult(BitWidth) &&
245         (DemandedUpper.isNullValue() || KnownUpperBits.isZero())) {
246       SmallVector<int, 16> ZeroSplat(VWidth, 0);
247       Amt = Builder.CreateShuffleVector(Amt, Amt, ZeroSplat);
248       return (LogicalShift ? (ShiftLeft ? Builder.CreateShl(Vec, Amt)
249                                         : Builder.CreateLShr(Vec, Amt))
250                            : Builder.CreateAShr(Vec, Amt));
251     }
252   }
253 
254   // Simplify if count is constant vector.
255   auto CDV = dyn_cast<ConstantDataVector>(Amt);
256   if (!CDV)
257     return nullptr;
258 
259   // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
260   // operand to compute the shift amount.
261   assert(AmtVT->isVectorTy() && AmtVT->getPrimitiveSizeInBits() == 128 &&
262          cast<VectorType>(AmtVT)->getElementType() == SVT &&
263          "Unexpected shift-by-scalar type");
264 
265   // Concatenate the sub-elements to create the 64-bit value.
266   APInt Count(64, 0);
267   for (unsigned i = 0, NumSubElts = 64 / BitWidth; i != NumSubElts; ++i) {
268     unsigned SubEltIdx = (NumSubElts - 1) - i;
269     auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
270     Count <<= BitWidth;
271     Count |= SubElt->getValue().zextOrTrunc(64);
272   }
273 
274   // If shift-by-zero then just return the original value.
275   if (Count.isNullValue())
276     return Vec;
277 
278   // Handle cases when Shift >= BitWidth.
279   if (Count.uge(BitWidth)) {
280     // If LogicalShift - just return zero.
281     if (LogicalShift)
282       return ConstantAggregateZero::get(VT);
283 
284     // If ArithmeticShift - clamp Shift to (BitWidth - 1).
285     Count = APInt(64, BitWidth - 1);
286   }
287 
288   // Get a constant vector of the same type as the first operand.
289   auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
290   auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
291 
292   if (ShiftLeft)
293     return Builder.CreateShl(Vec, ShiftVec);
294 
295   if (LogicalShift)
296     return Builder.CreateLShr(Vec, ShiftVec);
297 
298   return Builder.CreateAShr(Vec, ShiftVec);
299 }
300 
301 // Attempt to simplify AVX2 per-element shift intrinsics to a generic IR shift.
302 // Unlike the generic IR shifts, the intrinsics have defined behaviour for out
303 // of range shift amounts (logical - set to zero, arithmetic - splat sign bit).
304 static Value *simplifyX86varShift(const IntrinsicInst &II,
305                                   InstCombiner::BuilderTy &Builder) {
306   bool LogicalShift = false;
307   bool ShiftLeft = false;
308 
309   switch (II.getIntrinsicID()) {
310   default:
311     llvm_unreachable("Unexpected intrinsic!");
312   case Intrinsic::x86_avx2_psrav_d:
313   case Intrinsic::x86_avx2_psrav_d_256:
314   case Intrinsic::x86_avx512_psrav_q_128:
315   case Intrinsic::x86_avx512_psrav_q_256:
316   case Intrinsic::x86_avx512_psrav_d_512:
317   case Intrinsic::x86_avx512_psrav_q_512:
318   case Intrinsic::x86_avx512_psrav_w_128:
319   case Intrinsic::x86_avx512_psrav_w_256:
320   case Intrinsic::x86_avx512_psrav_w_512:
321     LogicalShift = false;
322     ShiftLeft = false;
323     break;
324   case Intrinsic::x86_avx2_psrlv_d:
325   case Intrinsic::x86_avx2_psrlv_d_256:
326   case Intrinsic::x86_avx2_psrlv_q:
327   case Intrinsic::x86_avx2_psrlv_q_256:
328   case Intrinsic::x86_avx512_psrlv_d_512:
329   case Intrinsic::x86_avx512_psrlv_q_512:
330   case Intrinsic::x86_avx512_psrlv_w_128:
331   case Intrinsic::x86_avx512_psrlv_w_256:
332   case Intrinsic::x86_avx512_psrlv_w_512:
333     LogicalShift = true;
334     ShiftLeft = false;
335     break;
336   case Intrinsic::x86_avx2_psllv_d:
337   case Intrinsic::x86_avx2_psllv_d_256:
338   case Intrinsic::x86_avx2_psllv_q:
339   case Intrinsic::x86_avx2_psllv_q_256:
340   case Intrinsic::x86_avx512_psllv_d_512:
341   case Intrinsic::x86_avx512_psllv_q_512:
342   case Intrinsic::x86_avx512_psllv_w_128:
343   case Intrinsic::x86_avx512_psllv_w_256:
344   case Intrinsic::x86_avx512_psllv_w_512:
345     LogicalShift = true;
346     ShiftLeft = true;
347     break;
348   }
349   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
350 
351   auto Vec = II.getArgOperand(0);
352   auto Amt = II.getArgOperand(1);
353   auto VT = cast<FixedVectorType>(II.getType());
354   auto SVT = VT->getElementType();
355   int NumElts = VT->getNumElements();
356   int BitWidth = SVT->getIntegerBitWidth();
357 
358   // If the shift amount is guaranteed to be in-range we can replace it with a
359   // generic shift.
360   APInt UpperBits =
361       APInt::getHighBitsSet(BitWidth, BitWidth - Log2_32(BitWidth));
362   if (llvm::MaskedValueIsZero(Amt, UpperBits,
363                               II.getModule()->getDataLayout())) {
364     return (LogicalShift ? (ShiftLeft ? Builder.CreateShl(Vec, Amt)
365                                       : Builder.CreateLShr(Vec, Amt))
366                          : Builder.CreateAShr(Vec, Amt));
367   }
368 
369   // Simplify if all shift amounts are constant/undef.
370   auto *CShift = dyn_cast<Constant>(Amt);
371   if (!CShift)
372     return nullptr;
373 
374   // Collect each element's shift amount.
375   // We also collect special cases: UNDEF = -1, OUT-OF-RANGE = BitWidth.
376   bool AnyOutOfRange = false;
377   SmallVector<int, 8> ShiftAmts;
378   for (int I = 0; I < NumElts; ++I) {
379     auto *CElt = CShift->getAggregateElement(I);
380     if (isa_and_nonnull<UndefValue>(CElt)) {
381       ShiftAmts.push_back(-1);
382       continue;
383     }
384 
385     auto *COp = dyn_cast_or_null<ConstantInt>(CElt);
386     if (!COp)
387       return nullptr;
388 
389     // Handle out of range shifts.
390     // If LogicalShift - set to BitWidth (special case).
391     // If ArithmeticShift - set to (BitWidth - 1) (sign splat).
392     APInt ShiftVal = COp->getValue();
393     if (ShiftVal.uge(BitWidth)) {
394       AnyOutOfRange = LogicalShift;
395       ShiftAmts.push_back(LogicalShift ? BitWidth : BitWidth - 1);
396       continue;
397     }
398 
399     ShiftAmts.push_back((int)ShiftVal.getZExtValue());
400   }
401 
402   // If all elements out of range or UNDEF, return vector of zeros/undefs.
403   // ArithmeticShift should only hit this if they are all UNDEF.
404   auto OutOfRange = [&](int Idx) { return (Idx < 0) || (BitWidth <= Idx); };
405   if (llvm::all_of(ShiftAmts, OutOfRange)) {
406     SmallVector<Constant *, 8> ConstantVec;
407     for (int Idx : ShiftAmts) {
408       if (Idx < 0) {
409         ConstantVec.push_back(UndefValue::get(SVT));
410       } else {
411         assert(LogicalShift && "Logical shift expected");
412         ConstantVec.push_back(ConstantInt::getNullValue(SVT));
413       }
414     }
415     return ConstantVector::get(ConstantVec);
416   }
417 
418   // We can't handle only some out of range values with generic logical shifts.
419   if (AnyOutOfRange)
420     return nullptr;
421 
422   // Build the shift amount constant vector.
423   SmallVector<Constant *, 8> ShiftVecAmts;
424   for (int Idx : ShiftAmts) {
425     if (Idx < 0)
426       ShiftVecAmts.push_back(UndefValue::get(SVT));
427     else
428       ShiftVecAmts.push_back(ConstantInt::get(SVT, Idx));
429   }
430   auto ShiftVec = ConstantVector::get(ShiftVecAmts);
431 
432   if (ShiftLeft)
433     return Builder.CreateShl(Vec, ShiftVec);
434 
435   if (LogicalShift)
436     return Builder.CreateLShr(Vec, ShiftVec);
437 
438   return Builder.CreateAShr(Vec, ShiftVec);
439 }
440 
441 static Value *simplifyX86pack(IntrinsicInst &II,
442                               InstCombiner::BuilderTy &Builder, bool IsSigned) {
443   Value *Arg0 = II.getArgOperand(0);
444   Value *Arg1 = II.getArgOperand(1);
445   Type *ResTy = II.getType();
446 
447   // Fast all undef handling.
448   if (isa<UndefValue>(Arg0) && isa<UndefValue>(Arg1))
449     return UndefValue::get(ResTy);
450 
451   auto *ArgTy = cast<FixedVectorType>(Arg0->getType());
452   unsigned NumLanes = ResTy->getPrimitiveSizeInBits() / 128;
453   unsigned NumSrcElts = ArgTy->getNumElements();
454   assert(cast<FixedVectorType>(ResTy)->getNumElements() == (2 * NumSrcElts) &&
455          "Unexpected packing types");
456 
457   unsigned NumSrcEltsPerLane = NumSrcElts / NumLanes;
458   unsigned DstScalarSizeInBits = ResTy->getScalarSizeInBits();
459   unsigned SrcScalarSizeInBits = ArgTy->getScalarSizeInBits();
460   assert(SrcScalarSizeInBits == (2 * DstScalarSizeInBits) &&
461          "Unexpected packing types");
462 
463   // Constant folding.
464   if (!isa<Constant>(Arg0) || !isa<Constant>(Arg1))
465     return nullptr;
466 
467   // Clamp Values - signed/unsigned both use signed clamp values, but they
468   // differ on the min/max values.
469   APInt MinValue, MaxValue;
470   if (IsSigned) {
471     // PACKSS: Truncate signed value with signed saturation.
472     // Source values less than dst minint are saturated to minint.
473     // Source values greater than dst maxint are saturated to maxint.
474     MinValue =
475         APInt::getSignedMinValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
476     MaxValue =
477         APInt::getSignedMaxValue(DstScalarSizeInBits).sext(SrcScalarSizeInBits);
478   } else {
479     // PACKUS: Truncate signed value with unsigned saturation.
480     // Source values less than zero are saturated to zero.
481     // Source values greater than dst maxuint are saturated to maxuint.
482     MinValue = APInt::getNullValue(SrcScalarSizeInBits);
483     MaxValue = APInt::getLowBitsSet(SrcScalarSizeInBits, DstScalarSizeInBits);
484   }
485 
486   auto *MinC = Constant::getIntegerValue(ArgTy, MinValue);
487   auto *MaxC = Constant::getIntegerValue(ArgTy, MaxValue);
488   Arg0 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg0, MinC), MinC, Arg0);
489   Arg1 = Builder.CreateSelect(Builder.CreateICmpSLT(Arg1, MinC), MinC, Arg1);
490   Arg0 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg0, MaxC), MaxC, Arg0);
491   Arg1 = Builder.CreateSelect(Builder.CreateICmpSGT(Arg1, MaxC), MaxC, Arg1);
492 
493   // Shuffle clamped args together at the lane level.
494   SmallVector<int, 32> PackMask;
495   for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
496     for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
497       PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane));
498     for (unsigned Elt = 0; Elt != NumSrcEltsPerLane; ++Elt)
499       PackMask.push_back(Elt + (Lane * NumSrcEltsPerLane) + NumSrcElts);
500   }
501   auto *Shuffle = Builder.CreateShuffleVector(Arg0, Arg1, PackMask);
502 
503   // Truncate to dst size.
504   return Builder.CreateTrunc(Shuffle, ResTy);
505 }
506 
507 static Value *simplifyX86movmsk(const IntrinsicInst &II,
508                                 InstCombiner::BuilderTy &Builder) {
509   Value *Arg = II.getArgOperand(0);
510   Type *ResTy = II.getType();
511 
512   // movmsk(undef) -> zero as we must ensure the upper bits are zero.
513   if (isa<UndefValue>(Arg))
514     return Constant::getNullValue(ResTy);
515 
516   auto *ArgTy = dyn_cast<FixedVectorType>(Arg->getType());
517   // We can't easily peek through x86_mmx types.
518   if (!ArgTy)
519     return nullptr;
520 
521   // Expand MOVMSK to compare/bitcast/zext:
522   // e.g. PMOVMSKB(v16i8 x):
523   // %cmp = icmp slt <16 x i8> %x, zeroinitializer
524   // %int = bitcast <16 x i1> %cmp to i16
525   // %res = zext i16 %int to i32
526   unsigned NumElts = ArgTy->getNumElements();
527   Type *IntegerVecTy = VectorType::getInteger(ArgTy);
528   Type *IntegerTy = Builder.getIntNTy(NumElts);
529 
530   Value *Res = Builder.CreateBitCast(Arg, IntegerVecTy);
531   Res = Builder.CreateICmpSLT(Res, Constant::getNullValue(IntegerVecTy));
532   Res = Builder.CreateBitCast(Res, IntegerTy);
533   Res = Builder.CreateZExtOrTrunc(Res, ResTy);
534   return Res;
535 }
536 
537 static Value *simplifyX86addcarry(const IntrinsicInst &II,
538                                   InstCombiner::BuilderTy &Builder) {
539   Value *CarryIn = II.getArgOperand(0);
540   Value *Op1 = II.getArgOperand(1);
541   Value *Op2 = II.getArgOperand(2);
542   Type *RetTy = II.getType();
543   Type *OpTy = Op1->getType();
544   assert(RetTy->getStructElementType(0)->isIntegerTy(8) &&
545          RetTy->getStructElementType(1) == OpTy && OpTy == Op2->getType() &&
546          "Unexpected types for x86 addcarry");
547 
548   // If carry-in is zero, this is just an unsigned add with overflow.
549   if (match(CarryIn, PatternMatch::m_ZeroInt())) {
550     Value *UAdd = Builder.CreateIntrinsic(Intrinsic::uadd_with_overflow, OpTy,
551                                           {Op1, Op2});
552     // The types have to be adjusted to match the x86 call types.
553     Value *UAddResult = Builder.CreateExtractValue(UAdd, 0);
554     Value *UAddOV = Builder.CreateZExt(Builder.CreateExtractValue(UAdd, 1),
555                                        Builder.getInt8Ty());
556     Value *Res = UndefValue::get(RetTy);
557     Res = Builder.CreateInsertValue(Res, UAddOV, 0);
558     return Builder.CreateInsertValue(Res, UAddResult, 1);
559   }
560 
561   return nullptr;
562 }
563 
564 static Value *simplifyX86insertps(const IntrinsicInst &II,
565                                   InstCombiner::BuilderTy &Builder) {
566   auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2));
567   if (!CInt)
568     return nullptr;
569 
570   auto *VecTy = cast<FixedVectorType>(II.getType());
571   assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
572 
573   // The immediate permute control byte looks like this:
574   //    [3:0] - zero mask for each 32-bit lane
575   //    [5:4] - select one 32-bit destination lane
576   //    [7:6] - select one 32-bit source lane
577 
578   uint8_t Imm = CInt->getZExtValue();
579   uint8_t ZMask = Imm & 0xf;
580   uint8_t DestLane = (Imm >> 4) & 0x3;
581   uint8_t SourceLane = (Imm >> 6) & 0x3;
582 
583   ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
584 
585   // If all zero mask bits are set, this was just a weird way to
586   // generate a zero vector.
587   if (ZMask == 0xf)
588     return ZeroVector;
589 
590   // Initialize by passing all of the first source bits through.
591   int ShuffleMask[4] = {0, 1, 2, 3};
592 
593   // We may replace the second operand with the zero vector.
594   Value *V1 = II.getArgOperand(1);
595 
596   if (ZMask) {
597     // If the zero mask is being used with a single input or the zero mask
598     // overrides the destination lane, this is a shuffle with the zero vector.
599     if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
600         (ZMask & (1 << DestLane))) {
601       V1 = ZeroVector;
602       // We may still move 32-bits of the first source vector from one lane
603       // to another.
604       ShuffleMask[DestLane] = SourceLane;
605       // The zero mask may override the previous insert operation.
606       for (unsigned i = 0; i < 4; ++i)
607         if ((ZMask >> i) & 0x1)
608           ShuffleMask[i] = i + 4;
609     } else {
610       // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
611       return nullptr;
612     }
613   } else {
614     // Replace the selected destination lane with the selected source lane.
615     ShuffleMask[DestLane] = SourceLane + 4;
616   }
617 
618   return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
619 }
620 
621 /// Attempt to simplify SSE4A EXTRQ/EXTRQI instructions using constant folding
622 /// or conversion to a shuffle vector.
623 static Value *simplifyX86extrq(IntrinsicInst &II, Value *Op0,
624                                ConstantInt *CILength, ConstantInt *CIIndex,
625                                InstCombiner::BuilderTy &Builder) {
626   auto LowConstantHighUndef = [&](uint64_t Val) {
627     Type *IntTy64 = Type::getInt64Ty(II.getContext());
628     Constant *Args[] = {ConstantInt::get(IntTy64, Val),
629                         UndefValue::get(IntTy64)};
630     return ConstantVector::get(Args);
631   };
632 
633   // See if we're dealing with constant values.
634   Constant *C0 = dyn_cast<Constant>(Op0);
635   ConstantInt *CI0 =
636       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
637          : nullptr;
638 
639   // Attempt to constant fold.
640   if (CILength && CIIndex) {
641     // From AMD documentation: "The bit index and field length are each six
642     // bits in length other bits of the field are ignored."
643     APInt APIndex = CIIndex->getValue().zextOrTrunc(6);
644     APInt APLength = CILength->getValue().zextOrTrunc(6);
645 
646     unsigned Index = APIndex.getZExtValue();
647 
648     // From AMD documentation: "a value of zero in the field length is
649     // defined as length of 64".
650     unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
651 
652     // From AMD documentation: "If the sum of the bit index + length field
653     // is greater than 64, the results are undefined".
654     unsigned End = Index + Length;
655 
656     // Note that both field index and field length are 8-bit quantities.
657     // Since variables 'Index' and 'Length' are unsigned values
658     // obtained from zero-extending field index and field length
659     // respectively, their sum should never wrap around.
660     if (End > 64)
661       return UndefValue::get(II.getType());
662 
663     // If we are inserting whole bytes, we can convert this to a shuffle.
664     // Lowering can recognize EXTRQI shuffle masks.
665     if ((Length % 8) == 0 && (Index % 8) == 0) {
666       // Convert bit indices to byte indices.
667       Length /= 8;
668       Index /= 8;
669 
670       Type *IntTy8 = Type::getInt8Ty(II.getContext());
671       auto *ShufTy = FixedVectorType::get(IntTy8, 16);
672 
673       SmallVector<int, 16> ShuffleMask;
674       for (int i = 0; i != (int)Length; ++i)
675         ShuffleMask.push_back(i + Index);
676       for (int i = Length; i != 8; ++i)
677         ShuffleMask.push_back(i + 16);
678       for (int i = 8; i != 16; ++i)
679         ShuffleMask.push_back(-1);
680 
681       Value *SV = Builder.CreateShuffleVector(
682           Builder.CreateBitCast(Op0, ShufTy),
683           ConstantAggregateZero::get(ShufTy), ShuffleMask);
684       return Builder.CreateBitCast(SV, II.getType());
685     }
686 
687     // Constant Fold - shift Index'th bit to lowest position and mask off
688     // Length bits.
689     if (CI0) {
690       APInt Elt = CI0->getValue();
691       Elt.lshrInPlace(Index);
692       Elt = Elt.zextOrTrunc(Length);
693       return LowConstantHighUndef(Elt.getZExtValue());
694     }
695 
696     // If we were an EXTRQ call, we'll save registers if we convert to EXTRQI.
697     if (II.getIntrinsicID() == Intrinsic::x86_sse4a_extrq) {
698       Value *Args[] = {Op0, CILength, CIIndex};
699       Module *M = II.getModule();
700       Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_extrqi);
701       return Builder.CreateCall(F, Args);
702     }
703   }
704 
705   // Constant Fold - extraction from zero is always {zero, undef}.
706   if (CI0 && CI0->isZero())
707     return LowConstantHighUndef(0);
708 
709   return nullptr;
710 }
711 
712 /// Attempt to simplify SSE4A INSERTQ/INSERTQI instructions using constant
713 /// folding or conversion to a shuffle vector.
714 static Value *simplifyX86insertq(IntrinsicInst &II, Value *Op0, Value *Op1,
715                                  APInt APLength, APInt APIndex,
716                                  InstCombiner::BuilderTy &Builder) {
717   // From AMD documentation: "The bit index and field length are each six bits
718   // in length other bits of the field are ignored."
719   APIndex = APIndex.zextOrTrunc(6);
720   APLength = APLength.zextOrTrunc(6);
721 
722   // Attempt to constant fold.
723   unsigned Index = APIndex.getZExtValue();
724 
725   // From AMD documentation: "a value of zero in the field length is
726   // defined as length of 64".
727   unsigned Length = APLength == 0 ? 64 : APLength.getZExtValue();
728 
729   // From AMD documentation: "If the sum of the bit index + length field
730   // is greater than 64, the results are undefined".
731   unsigned End = Index + Length;
732 
733   // Note that both field index and field length are 8-bit quantities.
734   // Since variables 'Index' and 'Length' are unsigned values
735   // obtained from zero-extending field index and field length
736   // respectively, their sum should never wrap around.
737   if (End > 64)
738     return UndefValue::get(II.getType());
739 
740   // If we are inserting whole bytes, we can convert this to a shuffle.
741   // Lowering can recognize INSERTQI shuffle masks.
742   if ((Length % 8) == 0 && (Index % 8) == 0) {
743     // Convert bit indices to byte indices.
744     Length /= 8;
745     Index /= 8;
746 
747     Type *IntTy8 = Type::getInt8Ty(II.getContext());
748     auto *ShufTy = FixedVectorType::get(IntTy8, 16);
749 
750     SmallVector<int, 16> ShuffleMask;
751     for (int i = 0; i != (int)Index; ++i)
752       ShuffleMask.push_back(i);
753     for (int i = 0; i != (int)Length; ++i)
754       ShuffleMask.push_back(i + 16);
755     for (int i = Index + Length; i != 8; ++i)
756       ShuffleMask.push_back(i);
757     for (int i = 8; i != 16; ++i)
758       ShuffleMask.push_back(-1);
759 
760     Value *SV = Builder.CreateShuffleVector(Builder.CreateBitCast(Op0, ShufTy),
761                                             Builder.CreateBitCast(Op1, ShufTy),
762                                             ShuffleMask);
763     return Builder.CreateBitCast(SV, II.getType());
764   }
765 
766   // See if we're dealing with constant values.
767   Constant *C0 = dyn_cast<Constant>(Op0);
768   Constant *C1 = dyn_cast<Constant>(Op1);
769   ConstantInt *CI00 =
770       C0 ? dyn_cast_or_null<ConstantInt>(C0->getAggregateElement((unsigned)0))
771          : nullptr;
772   ConstantInt *CI10 =
773       C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
774          : nullptr;
775 
776   // Constant Fold - insert bottom Length bits starting at the Index'th bit.
777   if (CI00 && CI10) {
778     APInt V00 = CI00->getValue();
779     APInt V10 = CI10->getValue();
780     APInt Mask = APInt::getLowBitsSet(64, Length).shl(Index);
781     V00 = V00 & ~Mask;
782     V10 = V10.zextOrTrunc(Length).zextOrTrunc(64).shl(Index);
783     APInt Val = V00 | V10;
784     Type *IntTy64 = Type::getInt64Ty(II.getContext());
785     Constant *Args[] = {ConstantInt::get(IntTy64, Val.getZExtValue()),
786                         UndefValue::get(IntTy64)};
787     return ConstantVector::get(Args);
788   }
789 
790   // If we were an INSERTQ call, we'll save demanded elements if we convert to
791   // INSERTQI.
792   if (II.getIntrinsicID() == Intrinsic::x86_sse4a_insertq) {
793     Type *IntTy8 = Type::getInt8Ty(II.getContext());
794     Constant *CILength = ConstantInt::get(IntTy8, Length, false);
795     Constant *CIIndex = ConstantInt::get(IntTy8, Index, false);
796 
797     Value *Args[] = {Op0, Op1, CILength, CIIndex};
798     Module *M = II.getModule();
799     Function *F = Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
800     return Builder.CreateCall(F, Args);
801   }
802 
803   return nullptr;
804 }
805 
806 /// Attempt to convert pshufb* to shufflevector if the mask is constant.
807 static Value *simplifyX86pshufb(const IntrinsicInst &II,
808                                 InstCombiner::BuilderTy &Builder) {
809   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
810   if (!V)
811     return nullptr;
812 
813   auto *VecTy = cast<FixedVectorType>(II.getType());
814   unsigned NumElts = VecTy->getNumElements();
815   assert((NumElts == 16 || NumElts == 32 || NumElts == 64) &&
816          "Unexpected number of elements in shuffle mask!");
817 
818   // Construct a shuffle mask from constant integers or UNDEFs.
819   int Indexes[64];
820 
821   // Each byte in the shuffle control mask forms an index to permute the
822   // corresponding byte in the destination operand.
823   for (unsigned I = 0; I < NumElts; ++I) {
824     Constant *COp = V->getAggregateElement(I);
825     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
826       return nullptr;
827 
828     if (isa<UndefValue>(COp)) {
829       Indexes[I] = -1;
830       continue;
831     }
832 
833     int8_t Index = cast<ConstantInt>(COp)->getValue().getZExtValue();
834 
835     // If the most significant bit (bit[7]) of each byte of the shuffle
836     // control mask is set, then zero is written in the result byte.
837     // The zero vector is in the right-hand side of the resulting
838     // shufflevector.
839 
840     // The value of each index for the high 128-bit lane is the least
841     // significant 4 bits of the respective shuffle control byte.
842     Index = ((Index < 0) ? NumElts : Index & 0x0F) + (I & 0xF0);
843     Indexes[I] = Index;
844   }
845 
846   auto V1 = II.getArgOperand(0);
847   auto V2 = Constant::getNullValue(VecTy);
848   return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes, NumElts));
849 }
850 
851 /// Attempt to convert vpermilvar* to shufflevector if the mask is constant.
852 static Value *simplifyX86vpermilvar(const IntrinsicInst &II,
853                                     InstCombiner::BuilderTy &Builder) {
854   Constant *V = dyn_cast<Constant>(II.getArgOperand(1));
855   if (!V)
856     return nullptr;
857 
858   auto *VecTy = cast<FixedVectorType>(II.getType());
859   unsigned NumElts = VecTy->getNumElements();
860   bool IsPD = VecTy->getScalarType()->isDoubleTy();
861   unsigned NumLaneElts = IsPD ? 2 : 4;
862   assert(NumElts == 16 || NumElts == 8 || NumElts == 4 || NumElts == 2);
863 
864   // Construct a shuffle mask from constant integers or UNDEFs.
865   int Indexes[16];
866 
867   // The intrinsics only read one or two bits, clear the rest.
868   for (unsigned I = 0; I < NumElts; ++I) {
869     Constant *COp = V->getAggregateElement(I);
870     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
871       return nullptr;
872 
873     if (isa<UndefValue>(COp)) {
874       Indexes[I] = -1;
875       continue;
876     }
877 
878     APInt Index = cast<ConstantInt>(COp)->getValue();
879     Index = Index.zextOrTrunc(32).getLoBits(2);
880 
881     // The PD variants uses bit 1 to select per-lane element index, so
882     // shift down to convert to generic shuffle mask index.
883     if (IsPD)
884       Index.lshrInPlace(1);
885 
886     // The _256 variants are a bit trickier since the mask bits always index
887     // into the corresponding 128 half. In order to convert to a generic
888     // shuffle, we have to make that explicit.
889     Index += APInt(32, (I / NumLaneElts) * NumLaneElts);
890 
891     Indexes[I] = Index.getZExtValue();
892   }
893 
894   auto V1 = II.getArgOperand(0);
895   auto V2 = UndefValue::get(V1->getType());
896   return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes, NumElts));
897 }
898 
899 /// Attempt to convert vpermd/vpermps to shufflevector if the mask is constant.
900 static Value *simplifyX86vpermv(const IntrinsicInst &II,
901                                 InstCombiner::BuilderTy &Builder) {
902   auto *V = dyn_cast<Constant>(II.getArgOperand(1));
903   if (!V)
904     return nullptr;
905 
906   auto *VecTy = cast<FixedVectorType>(II.getType());
907   unsigned Size = VecTy->getNumElements();
908   assert((Size == 4 || Size == 8 || Size == 16 || Size == 32 || Size == 64) &&
909          "Unexpected shuffle mask size");
910 
911   // Construct a shuffle mask from constant integers or UNDEFs.
912   int Indexes[64];
913 
914   for (unsigned I = 0; I < Size; ++I) {
915     Constant *COp = V->getAggregateElement(I);
916     if (!COp || (!isa<UndefValue>(COp) && !isa<ConstantInt>(COp)))
917       return nullptr;
918 
919     if (isa<UndefValue>(COp)) {
920       Indexes[I] = -1;
921       continue;
922     }
923 
924     uint32_t Index = cast<ConstantInt>(COp)->getZExtValue();
925     Index &= Size - 1;
926     Indexes[I] = Index;
927   }
928 
929   auto V1 = II.getArgOperand(0);
930   auto V2 = UndefValue::get(VecTy);
931   return Builder.CreateShuffleVector(V1, V2, makeArrayRef(Indexes, Size));
932 }
933 
934 Optional<Instruction *>
935 X86TTIImpl::instCombineIntrinsic(InstCombiner &IC, IntrinsicInst &II) const {
936   auto SimplifyDemandedVectorEltsLow = [&IC](Value *Op, unsigned Width,
937                                              unsigned DemandedWidth) {
938     APInt UndefElts(Width, 0);
939     APInt DemandedElts = APInt::getLowBitsSet(Width, DemandedWidth);
940     return IC.SimplifyDemandedVectorElts(Op, DemandedElts, UndefElts);
941   };
942 
943   Intrinsic::ID IID = II.getIntrinsicID();
944   switch (IID) {
945   case Intrinsic::x86_bmi_bextr_32:
946   case Intrinsic::x86_bmi_bextr_64:
947   case Intrinsic::x86_tbm_bextri_u32:
948   case Intrinsic::x86_tbm_bextri_u64:
949     // If the RHS is a constant we can try some simplifications.
950     if (auto *C = dyn_cast<ConstantInt>(II.getArgOperand(1))) {
951       uint64_t Shift = C->getZExtValue();
952       uint64_t Length = (Shift >> 8) & 0xff;
953       Shift &= 0xff;
954       unsigned BitWidth = II.getType()->getIntegerBitWidth();
955       // If the length is 0 or the shift is out of range, replace with zero.
956       if (Length == 0 || Shift >= BitWidth) {
957         return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), 0));
958       }
959       // If the LHS is also a constant, we can completely constant fold this.
960       if (auto *InC = dyn_cast<ConstantInt>(II.getArgOperand(0))) {
961         uint64_t Result = InC->getZExtValue() >> Shift;
962         if (Length > BitWidth)
963           Length = BitWidth;
964         Result &= maskTrailingOnes<uint64_t>(Length);
965         return IC.replaceInstUsesWith(II,
966                                       ConstantInt::get(II.getType(), Result));
967       }
968       // TODO should we turn this into 'and' if shift is 0? Or 'shl' if we
969       // are only masking bits that a shift already cleared?
970     }
971     break;
972 
973   case Intrinsic::x86_bmi_bzhi_32:
974   case Intrinsic::x86_bmi_bzhi_64:
975     // If the RHS is a constant we can try some simplifications.
976     if (auto *C = dyn_cast<ConstantInt>(II.getArgOperand(1))) {
977       uint64_t Index = C->getZExtValue() & 0xff;
978       unsigned BitWidth = II.getType()->getIntegerBitWidth();
979       if (Index >= BitWidth) {
980         return IC.replaceInstUsesWith(II, II.getArgOperand(0));
981       }
982       if (Index == 0) {
983         return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), 0));
984       }
985       // If the LHS is also a constant, we can completely constant fold this.
986       if (auto *InC = dyn_cast<ConstantInt>(II.getArgOperand(0))) {
987         uint64_t Result = InC->getZExtValue();
988         Result &= maskTrailingOnes<uint64_t>(Index);
989         return IC.replaceInstUsesWith(II,
990                                       ConstantInt::get(II.getType(), Result));
991       }
992       // TODO should we convert this to an AND if the RHS is constant?
993     }
994     break;
995   case Intrinsic::x86_bmi_pext_32:
996   case Intrinsic::x86_bmi_pext_64:
997     if (auto *MaskC = dyn_cast<ConstantInt>(II.getArgOperand(1))) {
998       if (MaskC->isNullValue()) {
999         return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), 0));
1000       }
1001       if (MaskC->isAllOnesValue()) {
1002         return IC.replaceInstUsesWith(II, II.getArgOperand(0));
1003       }
1004 
1005       if (auto *SrcC = dyn_cast<ConstantInt>(II.getArgOperand(0))) {
1006         uint64_t Src = SrcC->getZExtValue();
1007         uint64_t Mask = MaskC->getZExtValue();
1008         uint64_t Result = 0;
1009         uint64_t BitToSet = 1;
1010 
1011         while (Mask) {
1012           // Isolate lowest set bit.
1013           uint64_t BitToTest = Mask & -Mask;
1014           if (BitToTest & Src)
1015             Result |= BitToSet;
1016 
1017           BitToSet <<= 1;
1018           // Clear lowest set bit.
1019           Mask &= Mask - 1;
1020         }
1021 
1022         return IC.replaceInstUsesWith(II,
1023                                       ConstantInt::get(II.getType(), Result));
1024       }
1025     }
1026     break;
1027   case Intrinsic::x86_bmi_pdep_32:
1028   case Intrinsic::x86_bmi_pdep_64:
1029     if (auto *MaskC = dyn_cast<ConstantInt>(II.getArgOperand(1))) {
1030       if (MaskC->isNullValue()) {
1031         return IC.replaceInstUsesWith(II, ConstantInt::get(II.getType(), 0));
1032       }
1033       if (MaskC->isAllOnesValue()) {
1034         return IC.replaceInstUsesWith(II, II.getArgOperand(0));
1035       }
1036 
1037       if (auto *SrcC = dyn_cast<ConstantInt>(II.getArgOperand(0))) {
1038         uint64_t Src = SrcC->getZExtValue();
1039         uint64_t Mask = MaskC->getZExtValue();
1040         uint64_t Result = 0;
1041         uint64_t BitToTest = 1;
1042 
1043         while (Mask) {
1044           // Isolate lowest set bit.
1045           uint64_t BitToSet = Mask & -Mask;
1046           if (BitToTest & Src)
1047             Result |= BitToSet;
1048 
1049           BitToTest <<= 1;
1050           // Clear lowest set bit;
1051           Mask &= Mask - 1;
1052         }
1053 
1054         return IC.replaceInstUsesWith(II,
1055                                       ConstantInt::get(II.getType(), Result));
1056       }
1057     }
1058     break;
1059 
1060   case Intrinsic::x86_sse_cvtss2si:
1061   case Intrinsic::x86_sse_cvtss2si64:
1062   case Intrinsic::x86_sse_cvttss2si:
1063   case Intrinsic::x86_sse_cvttss2si64:
1064   case Intrinsic::x86_sse2_cvtsd2si:
1065   case Intrinsic::x86_sse2_cvtsd2si64:
1066   case Intrinsic::x86_sse2_cvttsd2si:
1067   case Intrinsic::x86_sse2_cvttsd2si64:
1068   case Intrinsic::x86_avx512_vcvtss2si32:
1069   case Intrinsic::x86_avx512_vcvtss2si64:
1070   case Intrinsic::x86_avx512_vcvtss2usi32:
1071   case Intrinsic::x86_avx512_vcvtss2usi64:
1072   case Intrinsic::x86_avx512_vcvtsd2si32:
1073   case Intrinsic::x86_avx512_vcvtsd2si64:
1074   case Intrinsic::x86_avx512_vcvtsd2usi32:
1075   case Intrinsic::x86_avx512_vcvtsd2usi64:
1076   case Intrinsic::x86_avx512_cvttss2si:
1077   case Intrinsic::x86_avx512_cvttss2si64:
1078   case Intrinsic::x86_avx512_cvttss2usi:
1079   case Intrinsic::x86_avx512_cvttss2usi64:
1080   case Intrinsic::x86_avx512_cvttsd2si:
1081   case Intrinsic::x86_avx512_cvttsd2si64:
1082   case Intrinsic::x86_avx512_cvttsd2usi:
1083   case Intrinsic::x86_avx512_cvttsd2usi64: {
1084     // These intrinsics only demand the 0th element of their input vectors. If
1085     // we can simplify the input based on that, do so now.
1086     Value *Arg = II.getArgOperand(0);
1087     unsigned VWidth = cast<FixedVectorType>(Arg->getType())->getNumElements();
1088     if (Value *V = SimplifyDemandedVectorEltsLow(Arg, VWidth, 1)) {
1089       return IC.replaceOperand(II, 0, V);
1090     }
1091     break;
1092   }
1093 
1094   case Intrinsic::x86_mmx_pmovmskb:
1095   case Intrinsic::x86_sse_movmsk_ps:
1096   case Intrinsic::x86_sse2_movmsk_pd:
1097   case Intrinsic::x86_sse2_pmovmskb_128:
1098   case Intrinsic::x86_avx_movmsk_pd_256:
1099   case Intrinsic::x86_avx_movmsk_ps_256:
1100   case Intrinsic::x86_avx2_pmovmskb:
1101     if (Value *V = simplifyX86movmsk(II, IC.Builder)) {
1102       return IC.replaceInstUsesWith(II, V);
1103     }
1104     break;
1105 
1106   case Intrinsic::x86_sse_comieq_ss:
1107   case Intrinsic::x86_sse_comige_ss:
1108   case Intrinsic::x86_sse_comigt_ss:
1109   case Intrinsic::x86_sse_comile_ss:
1110   case Intrinsic::x86_sse_comilt_ss:
1111   case Intrinsic::x86_sse_comineq_ss:
1112   case Intrinsic::x86_sse_ucomieq_ss:
1113   case Intrinsic::x86_sse_ucomige_ss:
1114   case Intrinsic::x86_sse_ucomigt_ss:
1115   case Intrinsic::x86_sse_ucomile_ss:
1116   case Intrinsic::x86_sse_ucomilt_ss:
1117   case Intrinsic::x86_sse_ucomineq_ss:
1118   case Intrinsic::x86_sse2_comieq_sd:
1119   case Intrinsic::x86_sse2_comige_sd:
1120   case Intrinsic::x86_sse2_comigt_sd:
1121   case Intrinsic::x86_sse2_comile_sd:
1122   case Intrinsic::x86_sse2_comilt_sd:
1123   case Intrinsic::x86_sse2_comineq_sd:
1124   case Intrinsic::x86_sse2_ucomieq_sd:
1125   case Intrinsic::x86_sse2_ucomige_sd:
1126   case Intrinsic::x86_sse2_ucomigt_sd:
1127   case Intrinsic::x86_sse2_ucomile_sd:
1128   case Intrinsic::x86_sse2_ucomilt_sd:
1129   case Intrinsic::x86_sse2_ucomineq_sd:
1130   case Intrinsic::x86_avx512_vcomi_ss:
1131   case Intrinsic::x86_avx512_vcomi_sd:
1132   case Intrinsic::x86_avx512_mask_cmp_ss:
1133   case Intrinsic::x86_avx512_mask_cmp_sd: {
1134     // These intrinsics only demand the 0th element of their input vectors. If
1135     // we can simplify the input based on that, do so now.
1136     bool MadeChange = false;
1137     Value *Arg0 = II.getArgOperand(0);
1138     Value *Arg1 = II.getArgOperand(1);
1139     unsigned VWidth = cast<FixedVectorType>(Arg0->getType())->getNumElements();
1140     if (Value *V = SimplifyDemandedVectorEltsLow(Arg0, VWidth, 1)) {
1141       IC.replaceOperand(II, 0, V);
1142       MadeChange = true;
1143     }
1144     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, 1)) {
1145       IC.replaceOperand(II, 1, V);
1146       MadeChange = true;
1147     }
1148     if (MadeChange) {
1149       return &II;
1150     }
1151     break;
1152   }
1153 
1154   case Intrinsic::x86_avx512_add_ps_512:
1155   case Intrinsic::x86_avx512_div_ps_512:
1156   case Intrinsic::x86_avx512_mul_ps_512:
1157   case Intrinsic::x86_avx512_sub_ps_512:
1158   case Intrinsic::x86_avx512_add_pd_512:
1159   case Intrinsic::x86_avx512_div_pd_512:
1160   case Intrinsic::x86_avx512_mul_pd_512:
1161   case Intrinsic::x86_avx512_sub_pd_512:
1162     // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
1163     // IR operations.
1164     if (auto *R = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1165       if (R->getValue() == 4) {
1166         Value *Arg0 = II.getArgOperand(0);
1167         Value *Arg1 = II.getArgOperand(1);
1168 
1169         Value *V;
1170         switch (IID) {
1171         default:
1172           llvm_unreachable("Case stmts out of sync!");
1173         case Intrinsic::x86_avx512_add_ps_512:
1174         case Intrinsic::x86_avx512_add_pd_512:
1175           V = IC.Builder.CreateFAdd(Arg0, Arg1);
1176           break;
1177         case Intrinsic::x86_avx512_sub_ps_512:
1178         case Intrinsic::x86_avx512_sub_pd_512:
1179           V = IC.Builder.CreateFSub(Arg0, Arg1);
1180           break;
1181         case Intrinsic::x86_avx512_mul_ps_512:
1182         case Intrinsic::x86_avx512_mul_pd_512:
1183           V = IC.Builder.CreateFMul(Arg0, Arg1);
1184           break;
1185         case Intrinsic::x86_avx512_div_ps_512:
1186         case Intrinsic::x86_avx512_div_pd_512:
1187           V = IC.Builder.CreateFDiv(Arg0, Arg1);
1188           break;
1189         }
1190 
1191         return IC.replaceInstUsesWith(II, V);
1192       }
1193     }
1194     break;
1195 
1196   case Intrinsic::x86_avx512_mask_add_ss_round:
1197   case Intrinsic::x86_avx512_mask_div_ss_round:
1198   case Intrinsic::x86_avx512_mask_mul_ss_round:
1199   case Intrinsic::x86_avx512_mask_sub_ss_round:
1200   case Intrinsic::x86_avx512_mask_add_sd_round:
1201   case Intrinsic::x86_avx512_mask_div_sd_round:
1202   case Intrinsic::x86_avx512_mask_mul_sd_round:
1203   case Intrinsic::x86_avx512_mask_sub_sd_round:
1204     // If the rounding mode is CUR_DIRECTION(4) we can turn these into regular
1205     // IR operations.
1206     if (auto *R = dyn_cast<ConstantInt>(II.getArgOperand(4))) {
1207       if (R->getValue() == 4) {
1208         // Extract the element as scalars.
1209         Value *Arg0 = II.getArgOperand(0);
1210         Value *Arg1 = II.getArgOperand(1);
1211         Value *LHS = IC.Builder.CreateExtractElement(Arg0, (uint64_t)0);
1212         Value *RHS = IC.Builder.CreateExtractElement(Arg1, (uint64_t)0);
1213 
1214         Value *V;
1215         switch (IID) {
1216         default:
1217           llvm_unreachable("Case stmts out of sync!");
1218         case Intrinsic::x86_avx512_mask_add_ss_round:
1219         case Intrinsic::x86_avx512_mask_add_sd_round:
1220           V = IC.Builder.CreateFAdd(LHS, RHS);
1221           break;
1222         case Intrinsic::x86_avx512_mask_sub_ss_round:
1223         case Intrinsic::x86_avx512_mask_sub_sd_round:
1224           V = IC.Builder.CreateFSub(LHS, RHS);
1225           break;
1226         case Intrinsic::x86_avx512_mask_mul_ss_round:
1227         case Intrinsic::x86_avx512_mask_mul_sd_round:
1228           V = IC.Builder.CreateFMul(LHS, RHS);
1229           break;
1230         case Intrinsic::x86_avx512_mask_div_ss_round:
1231         case Intrinsic::x86_avx512_mask_div_sd_round:
1232           V = IC.Builder.CreateFDiv(LHS, RHS);
1233           break;
1234         }
1235 
1236         // Handle the masking aspect of the intrinsic.
1237         Value *Mask = II.getArgOperand(3);
1238         auto *C = dyn_cast<ConstantInt>(Mask);
1239         // We don't need a select if we know the mask bit is a 1.
1240         if (!C || !C->getValue()[0]) {
1241           // Cast the mask to an i1 vector and then extract the lowest element.
1242           auto *MaskTy = FixedVectorType::get(
1243               IC.Builder.getInt1Ty(),
1244               cast<IntegerType>(Mask->getType())->getBitWidth());
1245           Mask = IC.Builder.CreateBitCast(Mask, MaskTy);
1246           Mask = IC.Builder.CreateExtractElement(Mask, (uint64_t)0);
1247           // Extract the lowest element from the passthru operand.
1248           Value *Passthru =
1249               IC.Builder.CreateExtractElement(II.getArgOperand(2), (uint64_t)0);
1250           V = IC.Builder.CreateSelect(Mask, V, Passthru);
1251         }
1252 
1253         // Insert the result back into the original argument 0.
1254         V = IC.Builder.CreateInsertElement(Arg0, V, (uint64_t)0);
1255 
1256         return IC.replaceInstUsesWith(II, V);
1257       }
1258     }
1259     break;
1260 
1261   // Constant fold ashr( <A x Bi>, Ci ).
1262   // Constant fold lshr( <A x Bi>, Ci ).
1263   // Constant fold shl( <A x Bi>, Ci ).
1264   case Intrinsic::x86_sse2_psrai_d:
1265   case Intrinsic::x86_sse2_psrai_w:
1266   case Intrinsic::x86_avx2_psrai_d:
1267   case Intrinsic::x86_avx2_psrai_w:
1268   case Intrinsic::x86_avx512_psrai_q_128:
1269   case Intrinsic::x86_avx512_psrai_q_256:
1270   case Intrinsic::x86_avx512_psrai_d_512:
1271   case Intrinsic::x86_avx512_psrai_q_512:
1272   case Intrinsic::x86_avx512_psrai_w_512:
1273   case Intrinsic::x86_sse2_psrli_d:
1274   case Intrinsic::x86_sse2_psrli_q:
1275   case Intrinsic::x86_sse2_psrli_w:
1276   case Intrinsic::x86_avx2_psrli_d:
1277   case Intrinsic::x86_avx2_psrli_q:
1278   case Intrinsic::x86_avx2_psrli_w:
1279   case Intrinsic::x86_avx512_psrli_d_512:
1280   case Intrinsic::x86_avx512_psrli_q_512:
1281   case Intrinsic::x86_avx512_psrli_w_512:
1282   case Intrinsic::x86_sse2_pslli_d:
1283   case Intrinsic::x86_sse2_pslli_q:
1284   case Intrinsic::x86_sse2_pslli_w:
1285   case Intrinsic::x86_avx2_pslli_d:
1286   case Intrinsic::x86_avx2_pslli_q:
1287   case Intrinsic::x86_avx2_pslli_w:
1288   case Intrinsic::x86_avx512_pslli_d_512:
1289   case Intrinsic::x86_avx512_pslli_q_512:
1290   case Intrinsic::x86_avx512_pslli_w_512:
1291     if (Value *V = simplifyX86immShift(II, IC.Builder)) {
1292       return IC.replaceInstUsesWith(II, V);
1293     }
1294     break;
1295 
1296   case Intrinsic::x86_sse2_psra_d:
1297   case Intrinsic::x86_sse2_psra_w:
1298   case Intrinsic::x86_avx2_psra_d:
1299   case Intrinsic::x86_avx2_psra_w:
1300   case Intrinsic::x86_avx512_psra_q_128:
1301   case Intrinsic::x86_avx512_psra_q_256:
1302   case Intrinsic::x86_avx512_psra_d_512:
1303   case Intrinsic::x86_avx512_psra_q_512:
1304   case Intrinsic::x86_avx512_psra_w_512:
1305   case Intrinsic::x86_sse2_psrl_d:
1306   case Intrinsic::x86_sse2_psrl_q:
1307   case Intrinsic::x86_sse2_psrl_w:
1308   case Intrinsic::x86_avx2_psrl_d:
1309   case Intrinsic::x86_avx2_psrl_q:
1310   case Intrinsic::x86_avx2_psrl_w:
1311   case Intrinsic::x86_avx512_psrl_d_512:
1312   case Intrinsic::x86_avx512_psrl_q_512:
1313   case Intrinsic::x86_avx512_psrl_w_512:
1314   case Intrinsic::x86_sse2_psll_d:
1315   case Intrinsic::x86_sse2_psll_q:
1316   case Intrinsic::x86_sse2_psll_w:
1317   case Intrinsic::x86_avx2_psll_d:
1318   case Intrinsic::x86_avx2_psll_q:
1319   case Intrinsic::x86_avx2_psll_w:
1320   case Intrinsic::x86_avx512_psll_d_512:
1321   case Intrinsic::x86_avx512_psll_q_512:
1322   case Intrinsic::x86_avx512_psll_w_512: {
1323     if (Value *V = simplifyX86immShift(II, IC.Builder)) {
1324       return IC.replaceInstUsesWith(II, V);
1325     }
1326 
1327     // SSE2/AVX2 uses only the first 64-bits of the 128-bit vector
1328     // operand to compute the shift amount.
1329     Value *Arg1 = II.getArgOperand(1);
1330     assert(Arg1->getType()->getPrimitiveSizeInBits() == 128 &&
1331            "Unexpected packed shift size");
1332     unsigned VWidth = cast<FixedVectorType>(Arg1->getType())->getNumElements();
1333 
1334     if (Value *V = SimplifyDemandedVectorEltsLow(Arg1, VWidth, VWidth / 2)) {
1335       return IC.replaceOperand(II, 1, V);
1336     }
1337     break;
1338   }
1339 
1340   case Intrinsic::x86_avx2_psllv_d:
1341   case Intrinsic::x86_avx2_psllv_d_256:
1342   case Intrinsic::x86_avx2_psllv_q:
1343   case Intrinsic::x86_avx2_psllv_q_256:
1344   case Intrinsic::x86_avx512_psllv_d_512:
1345   case Intrinsic::x86_avx512_psllv_q_512:
1346   case Intrinsic::x86_avx512_psllv_w_128:
1347   case Intrinsic::x86_avx512_psllv_w_256:
1348   case Intrinsic::x86_avx512_psllv_w_512:
1349   case Intrinsic::x86_avx2_psrav_d:
1350   case Intrinsic::x86_avx2_psrav_d_256:
1351   case Intrinsic::x86_avx512_psrav_q_128:
1352   case Intrinsic::x86_avx512_psrav_q_256:
1353   case Intrinsic::x86_avx512_psrav_d_512:
1354   case Intrinsic::x86_avx512_psrav_q_512:
1355   case Intrinsic::x86_avx512_psrav_w_128:
1356   case Intrinsic::x86_avx512_psrav_w_256:
1357   case Intrinsic::x86_avx512_psrav_w_512:
1358   case Intrinsic::x86_avx2_psrlv_d:
1359   case Intrinsic::x86_avx2_psrlv_d_256:
1360   case Intrinsic::x86_avx2_psrlv_q:
1361   case Intrinsic::x86_avx2_psrlv_q_256:
1362   case Intrinsic::x86_avx512_psrlv_d_512:
1363   case Intrinsic::x86_avx512_psrlv_q_512:
1364   case Intrinsic::x86_avx512_psrlv_w_128:
1365   case Intrinsic::x86_avx512_psrlv_w_256:
1366   case Intrinsic::x86_avx512_psrlv_w_512:
1367     if (Value *V = simplifyX86varShift(II, IC.Builder)) {
1368       return IC.replaceInstUsesWith(II, V);
1369     }
1370     break;
1371 
1372   case Intrinsic::x86_sse2_packssdw_128:
1373   case Intrinsic::x86_sse2_packsswb_128:
1374   case Intrinsic::x86_avx2_packssdw:
1375   case Intrinsic::x86_avx2_packsswb:
1376   case Intrinsic::x86_avx512_packssdw_512:
1377   case Intrinsic::x86_avx512_packsswb_512:
1378     if (Value *V = simplifyX86pack(II, IC.Builder, true)) {
1379       return IC.replaceInstUsesWith(II, V);
1380     }
1381     break;
1382 
1383   case Intrinsic::x86_sse2_packuswb_128:
1384   case Intrinsic::x86_sse41_packusdw:
1385   case Intrinsic::x86_avx2_packusdw:
1386   case Intrinsic::x86_avx2_packuswb:
1387   case Intrinsic::x86_avx512_packusdw_512:
1388   case Intrinsic::x86_avx512_packuswb_512:
1389     if (Value *V = simplifyX86pack(II, IC.Builder, false)) {
1390       return IC.replaceInstUsesWith(II, V);
1391     }
1392     break;
1393 
1394   case Intrinsic::x86_pclmulqdq:
1395   case Intrinsic::x86_pclmulqdq_256:
1396   case Intrinsic::x86_pclmulqdq_512: {
1397     if (auto *C = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
1398       unsigned Imm = C->getZExtValue();
1399 
1400       bool MadeChange = false;
1401       Value *Arg0 = II.getArgOperand(0);
1402       Value *Arg1 = II.getArgOperand(1);
1403       unsigned VWidth =
1404           cast<FixedVectorType>(Arg0->getType())->getNumElements();
1405 
1406       APInt UndefElts1(VWidth, 0);
1407       APInt DemandedElts1 =
1408           APInt::getSplat(VWidth, APInt(2, (Imm & 0x01) ? 2 : 1));
1409       if (Value *V =
1410               IC.SimplifyDemandedVectorElts(Arg0, DemandedElts1, UndefElts1)) {
1411         IC.replaceOperand(II, 0, V);
1412         MadeChange = true;
1413       }
1414 
1415       APInt UndefElts2(VWidth, 0);
1416       APInt DemandedElts2 =
1417           APInt::getSplat(VWidth, APInt(2, (Imm & 0x10) ? 2 : 1));
1418       if (Value *V =
1419               IC.SimplifyDemandedVectorElts(Arg1, DemandedElts2, UndefElts2)) {
1420         IC.replaceOperand(II, 1, V);
1421         MadeChange = true;
1422       }
1423 
1424       // If either input elements are undef, the result is zero.
1425       if (DemandedElts1.isSubsetOf(UndefElts1) ||
1426           DemandedElts2.isSubsetOf(UndefElts2)) {
1427         return IC.replaceInstUsesWith(II,
1428                                       ConstantAggregateZero::get(II.getType()));
1429       }
1430 
1431       if (MadeChange) {
1432         return &II;
1433       }
1434     }
1435     break;
1436   }
1437 
1438   case Intrinsic::x86_sse41_insertps:
1439     if (Value *V = simplifyX86insertps(II, IC.Builder)) {
1440       return IC.replaceInstUsesWith(II, V);
1441     }
1442     break;
1443 
1444   case Intrinsic::x86_sse4a_extrq: {
1445     Value *Op0 = II.getArgOperand(0);
1446     Value *Op1 = II.getArgOperand(1);
1447     unsigned VWidth0 = cast<FixedVectorType>(Op0->getType())->getNumElements();
1448     unsigned VWidth1 = cast<FixedVectorType>(Op1->getType())->getNumElements();
1449     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1450            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1451            VWidth1 == 16 && "Unexpected operand sizes");
1452 
1453     // See if we're dealing with constant values.
1454     Constant *C1 = dyn_cast<Constant>(Op1);
1455     ConstantInt *CILength =
1456         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)0))
1457            : nullptr;
1458     ConstantInt *CIIndex =
1459         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
1460            : nullptr;
1461 
1462     // Attempt to simplify to a constant, shuffle vector or EXTRQI call.
1463     if (Value *V = simplifyX86extrq(II, Op0, CILength, CIIndex, IC.Builder)) {
1464       return IC.replaceInstUsesWith(II, V);
1465     }
1466 
1467     // EXTRQ only uses the lowest 64-bits of the first 128-bit vector
1468     // operands and the lowest 16-bits of the second.
1469     bool MadeChange = false;
1470     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1471       IC.replaceOperand(II, 0, V);
1472       MadeChange = true;
1473     }
1474     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 2)) {
1475       IC.replaceOperand(II, 1, V);
1476       MadeChange = true;
1477     }
1478     if (MadeChange) {
1479       return &II;
1480     }
1481     break;
1482   }
1483 
1484   case Intrinsic::x86_sse4a_extrqi: {
1485     // EXTRQI: Extract Length bits starting from Index. Zero pad the remaining
1486     // bits of the lower 64-bits. The upper 64-bits are undefined.
1487     Value *Op0 = II.getArgOperand(0);
1488     unsigned VWidth = cast<FixedVectorType>(Op0->getType())->getNumElements();
1489     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1490            "Unexpected operand size");
1491 
1492     // See if we're dealing with constant values.
1493     ConstantInt *CILength = dyn_cast<ConstantInt>(II.getArgOperand(1));
1494     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II.getArgOperand(2));
1495 
1496     // Attempt to simplify to a constant or shuffle vector.
1497     if (Value *V = simplifyX86extrq(II, Op0, CILength, CIIndex, IC.Builder)) {
1498       return IC.replaceInstUsesWith(II, V);
1499     }
1500 
1501     // EXTRQI only uses the lowest 64-bits of the first 128-bit vector
1502     // operand.
1503     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
1504       return IC.replaceOperand(II, 0, V);
1505     }
1506     break;
1507   }
1508 
1509   case Intrinsic::x86_sse4a_insertq: {
1510     Value *Op0 = II.getArgOperand(0);
1511     Value *Op1 = II.getArgOperand(1);
1512     unsigned VWidth = cast<FixedVectorType>(Op0->getType())->getNumElements();
1513     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1514            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth == 2 &&
1515            cast<FixedVectorType>(Op1->getType())->getNumElements() == 2 &&
1516            "Unexpected operand size");
1517 
1518     // See if we're dealing with constant values.
1519     Constant *C1 = dyn_cast<Constant>(Op1);
1520     ConstantInt *CI11 =
1521         C1 ? dyn_cast_or_null<ConstantInt>(C1->getAggregateElement((unsigned)1))
1522            : nullptr;
1523 
1524     // Attempt to simplify to a constant, shuffle vector or INSERTQI call.
1525     if (CI11) {
1526       const APInt &V11 = CI11->getValue();
1527       APInt Len = V11.zextOrTrunc(6);
1528       APInt Idx = V11.lshr(8).zextOrTrunc(6);
1529       if (Value *V = simplifyX86insertq(II, Op0, Op1, Len, Idx, IC.Builder)) {
1530         return IC.replaceInstUsesWith(II, V);
1531       }
1532     }
1533 
1534     // INSERTQ only uses the lowest 64-bits of the first 128-bit vector
1535     // operand.
1536     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth, 1)) {
1537       return IC.replaceOperand(II, 0, V);
1538     }
1539     break;
1540   }
1541 
1542   case Intrinsic::x86_sse4a_insertqi: {
1543     // INSERTQI: Extract lowest Length bits from lower half of second source and
1544     // insert over first source starting at Index bit. The upper 64-bits are
1545     // undefined.
1546     Value *Op0 = II.getArgOperand(0);
1547     Value *Op1 = II.getArgOperand(1);
1548     unsigned VWidth0 = cast<FixedVectorType>(Op0->getType())->getNumElements();
1549     unsigned VWidth1 = cast<FixedVectorType>(Op1->getType())->getNumElements();
1550     assert(Op0->getType()->getPrimitiveSizeInBits() == 128 &&
1551            Op1->getType()->getPrimitiveSizeInBits() == 128 && VWidth0 == 2 &&
1552            VWidth1 == 2 && "Unexpected operand sizes");
1553 
1554     // See if we're dealing with constant values.
1555     ConstantInt *CILength = dyn_cast<ConstantInt>(II.getArgOperand(2));
1556     ConstantInt *CIIndex = dyn_cast<ConstantInt>(II.getArgOperand(3));
1557 
1558     // Attempt to simplify to a constant or shuffle vector.
1559     if (CILength && CIIndex) {
1560       APInt Len = CILength->getValue().zextOrTrunc(6);
1561       APInt Idx = CIIndex->getValue().zextOrTrunc(6);
1562       if (Value *V = simplifyX86insertq(II, Op0, Op1, Len, Idx, IC.Builder)) {
1563         return IC.replaceInstUsesWith(II, V);
1564       }
1565     }
1566 
1567     // INSERTQI only uses the lowest 64-bits of the first two 128-bit vector
1568     // operands.
1569     bool MadeChange = false;
1570     if (Value *V = SimplifyDemandedVectorEltsLow(Op0, VWidth0, 1)) {
1571       IC.replaceOperand(II, 0, V);
1572       MadeChange = true;
1573     }
1574     if (Value *V = SimplifyDemandedVectorEltsLow(Op1, VWidth1, 1)) {
1575       IC.replaceOperand(II, 1, V);
1576       MadeChange = true;
1577     }
1578     if (MadeChange) {
1579       return &II;
1580     }
1581     break;
1582   }
1583 
1584   case Intrinsic::x86_sse41_pblendvb:
1585   case Intrinsic::x86_sse41_blendvps:
1586   case Intrinsic::x86_sse41_blendvpd:
1587   case Intrinsic::x86_avx_blendv_ps_256:
1588   case Intrinsic::x86_avx_blendv_pd_256:
1589   case Intrinsic::x86_avx2_pblendvb: {
1590     // fold (blend A, A, Mask) -> A
1591     Value *Op0 = II.getArgOperand(0);
1592     Value *Op1 = II.getArgOperand(1);
1593     Value *Mask = II.getArgOperand(2);
1594     if (Op0 == Op1) {
1595       return IC.replaceInstUsesWith(II, Op0);
1596     }
1597 
1598     // Zero Mask - select 1st argument.
1599     if (isa<ConstantAggregateZero>(Mask)) {
1600       return IC.replaceInstUsesWith(II, Op0);
1601     }
1602 
1603     // Constant Mask - select 1st/2nd argument lane based on top bit of mask.
1604     if (auto *ConstantMask = dyn_cast<ConstantDataVector>(Mask)) {
1605       Constant *NewSelector = getNegativeIsTrueBoolVec(ConstantMask);
1606       return SelectInst::Create(NewSelector, Op1, Op0, "blendv");
1607     }
1608 
1609     // Convert to a vector select if we can bypass casts and find a boolean
1610     // vector condition value.
1611     Value *BoolVec;
1612     Mask = InstCombiner::peekThroughBitcast(Mask);
1613     if (match(Mask, PatternMatch::m_SExt(PatternMatch::m_Value(BoolVec))) &&
1614         BoolVec->getType()->isVectorTy() &&
1615         BoolVec->getType()->getScalarSizeInBits() == 1) {
1616       assert(Mask->getType()->getPrimitiveSizeInBits() ==
1617                  II.getType()->getPrimitiveSizeInBits() &&
1618              "Not expecting mask and operands with different sizes");
1619 
1620       unsigned NumMaskElts =
1621           cast<FixedVectorType>(Mask->getType())->getNumElements();
1622       unsigned NumOperandElts =
1623           cast<FixedVectorType>(II.getType())->getNumElements();
1624       if (NumMaskElts == NumOperandElts) {
1625         return SelectInst::Create(BoolVec, Op1, Op0);
1626       }
1627 
1628       // If the mask has less elements than the operands, each mask bit maps to
1629       // multiple elements of the operands. Bitcast back and forth.
1630       if (NumMaskElts < NumOperandElts) {
1631         Value *CastOp0 = IC.Builder.CreateBitCast(Op0, Mask->getType());
1632         Value *CastOp1 = IC.Builder.CreateBitCast(Op1, Mask->getType());
1633         Value *Sel = IC.Builder.CreateSelect(BoolVec, CastOp1, CastOp0);
1634         return new BitCastInst(Sel, II.getType());
1635       }
1636     }
1637 
1638     break;
1639   }
1640 
1641   case Intrinsic::x86_ssse3_pshuf_b_128:
1642   case Intrinsic::x86_avx2_pshuf_b:
1643   case Intrinsic::x86_avx512_pshuf_b_512:
1644     if (Value *V = simplifyX86pshufb(II, IC.Builder)) {
1645       return IC.replaceInstUsesWith(II, V);
1646     }
1647     break;
1648 
1649   case Intrinsic::x86_avx_vpermilvar_ps:
1650   case Intrinsic::x86_avx_vpermilvar_ps_256:
1651   case Intrinsic::x86_avx512_vpermilvar_ps_512:
1652   case Intrinsic::x86_avx_vpermilvar_pd:
1653   case Intrinsic::x86_avx_vpermilvar_pd_256:
1654   case Intrinsic::x86_avx512_vpermilvar_pd_512:
1655     if (Value *V = simplifyX86vpermilvar(II, IC.Builder)) {
1656       return IC.replaceInstUsesWith(II, V);
1657     }
1658     break;
1659 
1660   case Intrinsic::x86_avx2_permd:
1661   case Intrinsic::x86_avx2_permps:
1662   case Intrinsic::x86_avx512_permvar_df_256:
1663   case Intrinsic::x86_avx512_permvar_df_512:
1664   case Intrinsic::x86_avx512_permvar_di_256:
1665   case Intrinsic::x86_avx512_permvar_di_512:
1666   case Intrinsic::x86_avx512_permvar_hi_128:
1667   case Intrinsic::x86_avx512_permvar_hi_256:
1668   case Intrinsic::x86_avx512_permvar_hi_512:
1669   case Intrinsic::x86_avx512_permvar_qi_128:
1670   case Intrinsic::x86_avx512_permvar_qi_256:
1671   case Intrinsic::x86_avx512_permvar_qi_512:
1672   case Intrinsic::x86_avx512_permvar_sf_512:
1673   case Intrinsic::x86_avx512_permvar_si_512:
1674     if (Value *V = simplifyX86vpermv(II, IC.Builder)) {
1675       return IC.replaceInstUsesWith(II, V);
1676     }
1677     break;
1678 
1679   case Intrinsic::x86_avx_maskload_ps:
1680   case Intrinsic::x86_avx_maskload_pd:
1681   case Intrinsic::x86_avx_maskload_ps_256:
1682   case Intrinsic::x86_avx_maskload_pd_256:
1683   case Intrinsic::x86_avx2_maskload_d:
1684   case Intrinsic::x86_avx2_maskload_q:
1685   case Intrinsic::x86_avx2_maskload_d_256:
1686   case Intrinsic::x86_avx2_maskload_q_256:
1687     if (Instruction *I = simplifyX86MaskedLoad(II, IC)) {
1688       return I;
1689     }
1690     break;
1691 
1692   case Intrinsic::x86_sse2_maskmov_dqu:
1693   case Intrinsic::x86_avx_maskstore_ps:
1694   case Intrinsic::x86_avx_maskstore_pd:
1695   case Intrinsic::x86_avx_maskstore_ps_256:
1696   case Intrinsic::x86_avx_maskstore_pd_256:
1697   case Intrinsic::x86_avx2_maskstore_d:
1698   case Intrinsic::x86_avx2_maskstore_q:
1699   case Intrinsic::x86_avx2_maskstore_d_256:
1700   case Intrinsic::x86_avx2_maskstore_q_256:
1701     if (simplifyX86MaskedStore(II, IC)) {
1702       return nullptr;
1703     }
1704     break;
1705 
1706   case Intrinsic::x86_addcarry_32:
1707   case Intrinsic::x86_addcarry_64:
1708     if (Value *V = simplifyX86addcarry(II, IC.Builder)) {
1709       return IC.replaceInstUsesWith(II, V);
1710     }
1711     break;
1712 
1713   default:
1714     break;
1715   }
1716   return None;
1717 }
1718 
1719 Optional<Value *> X86TTIImpl::simplifyDemandedUseBitsIntrinsic(
1720     InstCombiner &IC, IntrinsicInst &II, APInt DemandedMask, KnownBits &Known,
1721     bool &KnownBitsComputed) const {
1722   switch (II.getIntrinsicID()) {
1723   default:
1724     break;
1725   case Intrinsic::x86_mmx_pmovmskb:
1726   case Intrinsic::x86_sse_movmsk_ps:
1727   case Intrinsic::x86_sse2_movmsk_pd:
1728   case Intrinsic::x86_sse2_pmovmskb_128:
1729   case Intrinsic::x86_avx_movmsk_ps_256:
1730   case Intrinsic::x86_avx_movmsk_pd_256:
1731   case Intrinsic::x86_avx2_pmovmskb: {
1732     // MOVMSK copies the vector elements' sign bits to the low bits
1733     // and zeros the high bits.
1734     unsigned ArgWidth;
1735     if (II.getIntrinsicID() == Intrinsic::x86_mmx_pmovmskb) {
1736       ArgWidth = 8; // Arg is x86_mmx, but treated as <8 x i8>.
1737     } else {
1738       auto Arg = II.getArgOperand(0);
1739       auto ArgType = cast<FixedVectorType>(Arg->getType());
1740       ArgWidth = ArgType->getNumElements();
1741     }
1742 
1743     // If we don't need any of low bits then return zero,
1744     // we know that DemandedMask is non-zero already.
1745     APInt DemandedElts = DemandedMask.zextOrTrunc(ArgWidth);
1746     Type *VTy = II.getType();
1747     if (DemandedElts.isNullValue()) {
1748       return ConstantInt::getNullValue(VTy);
1749     }
1750 
1751     // We know that the upper bits are set to zero.
1752     Known.Zero.setBitsFrom(ArgWidth);
1753     KnownBitsComputed = true;
1754     break;
1755   }
1756   }
1757   return None;
1758 }
1759 
1760 Optional<Value *> X86TTIImpl::simplifyDemandedVectorEltsIntrinsic(
1761     InstCombiner &IC, IntrinsicInst &II, APInt DemandedElts, APInt &UndefElts,
1762     APInt &UndefElts2, APInt &UndefElts3,
1763     std::function<void(Instruction *, unsigned, APInt, APInt &)>
1764         simplifyAndSetOp) const {
1765   unsigned VWidth = cast<FixedVectorType>(II.getType())->getNumElements();
1766   switch (II.getIntrinsicID()) {
1767   default:
1768     break;
1769   case Intrinsic::x86_xop_vfrcz_ss:
1770   case Intrinsic::x86_xop_vfrcz_sd:
1771     // The instructions for these intrinsics are speced to zero upper bits not
1772     // pass them through like other scalar intrinsics. So we shouldn't just
1773     // use Arg0 if DemandedElts[0] is clear like we do for other intrinsics.
1774     // Instead we should return a zero vector.
1775     if (!DemandedElts[0]) {
1776       IC.addToWorklist(&II);
1777       return ConstantAggregateZero::get(II.getType());
1778     }
1779 
1780     // Only the lower element is used.
1781     DemandedElts = 1;
1782     simplifyAndSetOp(&II, 0, DemandedElts, UndefElts);
1783 
1784     // Only the lower element is undefined. The high elements are zero.
1785     UndefElts = UndefElts[0];
1786     break;
1787 
1788   // Unary scalar-as-vector operations that work column-wise.
1789   case Intrinsic::x86_sse_rcp_ss:
1790   case Intrinsic::x86_sse_rsqrt_ss:
1791     simplifyAndSetOp(&II, 0, DemandedElts, UndefElts);
1792 
1793     // If lowest element of a scalar op isn't used then use Arg0.
1794     if (!DemandedElts[0]) {
1795       IC.addToWorklist(&II);
1796       return II.getArgOperand(0);
1797     }
1798     // TODO: If only low elt lower SQRT to FSQRT (with rounding/exceptions
1799     // checks).
1800     break;
1801 
1802   // Binary scalar-as-vector operations that work column-wise. The high
1803   // elements come from operand 0. The low element is a function of both
1804   // operands.
1805   case Intrinsic::x86_sse_min_ss:
1806   case Intrinsic::x86_sse_max_ss:
1807   case Intrinsic::x86_sse_cmp_ss:
1808   case Intrinsic::x86_sse2_min_sd:
1809   case Intrinsic::x86_sse2_max_sd:
1810   case Intrinsic::x86_sse2_cmp_sd: {
1811     simplifyAndSetOp(&II, 0, DemandedElts, UndefElts);
1812 
1813     // If lowest element of a scalar op isn't used then use Arg0.
1814     if (!DemandedElts[0]) {
1815       IC.addToWorklist(&II);
1816       return II.getArgOperand(0);
1817     }
1818 
1819     // Only lower element is used for operand 1.
1820     DemandedElts = 1;
1821     simplifyAndSetOp(&II, 1, DemandedElts, UndefElts2);
1822 
1823     // Lower element is undefined if both lower elements are undefined.
1824     // Consider things like undef&0.  The result is known zero, not undef.
1825     if (!UndefElts2[0])
1826       UndefElts.clearBit(0);
1827 
1828     break;
1829   }
1830 
1831   // Binary scalar-as-vector operations that work column-wise. The high
1832   // elements come from operand 0 and the low element comes from operand 1.
1833   case Intrinsic::x86_sse41_round_ss:
1834   case Intrinsic::x86_sse41_round_sd: {
1835     // Don't use the low element of operand 0.
1836     APInt DemandedElts2 = DemandedElts;
1837     DemandedElts2.clearBit(0);
1838     simplifyAndSetOp(&II, 0, DemandedElts2, UndefElts);
1839 
1840     // If lowest element of a scalar op isn't used then use Arg0.
1841     if (!DemandedElts[0]) {
1842       IC.addToWorklist(&II);
1843       return II.getArgOperand(0);
1844     }
1845 
1846     // Only lower element is used for operand 1.
1847     DemandedElts = 1;
1848     simplifyAndSetOp(&II, 1, DemandedElts, UndefElts2);
1849 
1850     // Take the high undef elements from operand 0 and take the lower element
1851     // from operand 1.
1852     UndefElts.clearBit(0);
1853     UndefElts |= UndefElts2[0];
1854     break;
1855   }
1856 
1857   // Three input scalar-as-vector operations that work column-wise. The high
1858   // elements come from operand 0 and the low element is a function of all
1859   // three inputs.
1860   case Intrinsic::x86_avx512_mask_add_ss_round:
1861   case Intrinsic::x86_avx512_mask_div_ss_round:
1862   case Intrinsic::x86_avx512_mask_mul_ss_round:
1863   case Intrinsic::x86_avx512_mask_sub_ss_round:
1864   case Intrinsic::x86_avx512_mask_max_ss_round:
1865   case Intrinsic::x86_avx512_mask_min_ss_round:
1866   case Intrinsic::x86_avx512_mask_add_sd_round:
1867   case Intrinsic::x86_avx512_mask_div_sd_round:
1868   case Intrinsic::x86_avx512_mask_mul_sd_round:
1869   case Intrinsic::x86_avx512_mask_sub_sd_round:
1870   case Intrinsic::x86_avx512_mask_max_sd_round:
1871   case Intrinsic::x86_avx512_mask_min_sd_round:
1872     simplifyAndSetOp(&II, 0, DemandedElts, UndefElts);
1873 
1874     // If lowest element of a scalar op isn't used then use Arg0.
1875     if (!DemandedElts[0]) {
1876       IC.addToWorklist(&II);
1877       return II.getArgOperand(0);
1878     }
1879 
1880     // Only lower element is used for operand 1 and 2.
1881     DemandedElts = 1;
1882     simplifyAndSetOp(&II, 1, DemandedElts, UndefElts2);
1883     simplifyAndSetOp(&II, 2, DemandedElts, UndefElts3);
1884 
1885     // Lower element is undefined if all three lower elements are undefined.
1886     // Consider things like undef&0.  The result is known zero, not undef.
1887     if (!UndefElts2[0] || !UndefElts3[0])
1888       UndefElts.clearBit(0);
1889 
1890     break;
1891 
1892   case Intrinsic::x86_sse2_packssdw_128:
1893   case Intrinsic::x86_sse2_packsswb_128:
1894   case Intrinsic::x86_sse2_packuswb_128:
1895   case Intrinsic::x86_sse41_packusdw:
1896   case Intrinsic::x86_avx2_packssdw:
1897   case Intrinsic::x86_avx2_packsswb:
1898   case Intrinsic::x86_avx2_packusdw:
1899   case Intrinsic::x86_avx2_packuswb:
1900   case Intrinsic::x86_avx512_packssdw_512:
1901   case Intrinsic::x86_avx512_packsswb_512:
1902   case Intrinsic::x86_avx512_packusdw_512:
1903   case Intrinsic::x86_avx512_packuswb_512: {
1904     auto *Ty0 = II.getArgOperand(0)->getType();
1905     unsigned InnerVWidth = cast<FixedVectorType>(Ty0)->getNumElements();
1906     assert(VWidth == (InnerVWidth * 2) && "Unexpected input size");
1907 
1908     unsigned NumLanes = Ty0->getPrimitiveSizeInBits() / 128;
1909     unsigned VWidthPerLane = VWidth / NumLanes;
1910     unsigned InnerVWidthPerLane = InnerVWidth / NumLanes;
1911 
1912     // Per lane, pack the elements of the first input and then the second.
1913     // e.g.
1914     // v8i16 PACK(v4i32 X, v4i32 Y) - (X[0..3],Y[0..3])
1915     // v32i8 PACK(v16i16 X, v16i16 Y) - (X[0..7],Y[0..7]),(X[8..15],Y[8..15])
1916     for (int OpNum = 0; OpNum != 2; ++OpNum) {
1917       APInt OpDemandedElts(InnerVWidth, 0);
1918       for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1919         unsigned LaneIdx = Lane * VWidthPerLane;
1920         for (unsigned Elt = 0; Elt != InnerVWidthPerLane; ++Elt) {
1921           unsigned Idx = LaneIdx + Elt + InnerVWidthPerLane * OpNum;
1922           if (DemandedElts[Idx])
1923             OpDemandedElts.setBit((Lane * InnerVWidthPerLane) + Elt);
1924         }
1925       }
1926 
1927       // Demand elements from the operand.
1928       APInt OpUndefElts(InnerVWidth, 0);
1929       simplifyAndSetOp(&II, OpNum, OpDemandedElts, OpUndefElts);
1930 
1931       // Pack the operand's UNDEF elements, one lane at a time.
1932       OpUndefElts = OpUndefElts.zext(VWidth);
1933       for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1934         APInt LaneElts = OpUndefElts.lshr(InnerVWidthPerLane * Lane);
1935         LaneElts = LaneElts.getLoBits(InnerVWidthPerLane);
1936         LaneElts <<= InnerVWidthPerLane * (2 * Lane + OpNum);
1937         UndefElts |= LaneElts;
1938       }
1939     }
1940     break;
1941   }
1942 
1943   // PSHUFB
1944   case Intrinsic::x86_ssse3_pshuf_b_128:
1945   case Intrinsic::x86_avx2_pshuf_b:
1946   case Intrinsic::x86_avx512_pshuf_b_512:
1947   // PERMILVAR
1948   case Intrinsic::x86_avx_vpermilvar_ps:
1949   case Intrinsic::x86_avx_vpermilvar_ps_256:
1950   case Intrinsic::x86_avx512_vpermilvar_ps_512:
1951   case Intrinsic::x86_avx_vpermilvar_pd:
1952   case Intrinsic::x86_avx_vpermilvar_pd_256:
1953   case Intrinsic::x86_avx512_vpermilvar_pd_512:
1954   // PERMV
1955   case Intrinsic::x86_avx2_permd:
1956   case Intrinsic::x86_avx2_permps: {
1957     simplifyAndSetOp(&II, 1, DemandedElts, UndefElts);
1958     break;
1959   }
1960 
1961   // SSE4A instructions leave the upper 64-bits of the 128-bit result
1962   // in an undefined state.
1963   case Intrinsic::x86_sse4a_extrq:
1964   case Intrinsic::x86_sse4a_extrqi:
1965   case Intrinsic::x86_sse4a_insertq:
1966   case Intrinsic::x86_sse4a_insertqi:
1967     UndefElts.setHighBits(VWidth / 2);
1968     break;
1969   }
1970   return None;
1971 }
1972