[InstCombine] Move SSE2/AVX2 arithmetic vector shift folding to instcombiner
[oota-llvm.git] / 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/Statistic.h"
16 #include "llvm/Analysis/InstructionSimplify.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/Dominators.h"
20 #include "llvm/IR/PatternMatch.h"
21 #include "llvm/IR/Statepoint.h"
22 #include "llvm/Transforms/Utils/BuildLibCalls.h"
23 #include "llvm/Transforms/Utils/Local.h"
24 #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
25 using namespace llvm;
26 using namespace PatternMatch;
27
28 #define DEBUG_TYPE "instcombine"
29
30 STATISTIC(NumSimplified, "Number of library calls simplified");
31
32 /// getPromotedType - Return the specified type promoted as it would be to pass
33 /// though a va_arg area.
34 static Type *getPromotedType(Type *Ty) {
35   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
36     if (ITy->getBitWidth() < 32)
37       return Type::getInt32Ty(Ty->getContext());
38   }
39   return Ty;
40 }
41
42 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
43 /// single scalar element, like {{{type}}} or [1 x type], return type.
44 static Type *reduceToSingleValueType(Type *T) {
45   while (!T->isSingleValueType()) {
46     if (StructType *STy = dyn_cast<StructType>(T)) {
47       if (STy->getNumElements() == 1)
48         T = STy->getElementType(0);
49       else
50         break;
51     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
52       if (ATy->getNumElements() == 1)
53         T = ATy->getElementType();
54       else
55         break;
56     } else
57       break;
58   }
59
60   return T;
61 }
62
63 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
64   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL, MI, AC, DT);
65   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL, MI, AC, DT);
66   unsigned MinAlign = std::min(DstAlign, SrcAlign);
67   unsigned CopyAlign = MI->getAlignment();
68
69   if (CopyAlign < MinAlign) {
70     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), MinAlign, false));
71     return MI;
72   }
73
74   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
75   // load/store.
76   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
77   if (!MemOpLength) return nullptr;
78
79   // Source and destination pointer types are always "i8*" for intrinsic.  See
80   // if the size is something we can handle with a single primitive load/store.
81   // A single load+store correctly handles overlapping memory in the memmove
82   // case.
83   uint64_t Size = MemOpLength->getLimitedValue();
84   assert(Size && "0-sized memory transferring should be removed already.");
85
86   if (Size > 8 || (Size&(Size-1)))
87     return nullptr;  // If not 1/2/4/8 bytes, exit.
88
89   // Use an integer load+store unless we can find something better.
90   unsigned SrcAddrSp =
91     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
92   unsigned DstAddrSp =
93     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
94
95   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
96   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
97   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
98
99   // Memcpy forces the use of i8* for the source and destination.  That means
100   // that if you're using memcpy to move one double around, you'll get a cast
101   // from double* to i8*.  We'd much rather use a double load+store rather than
102   // an i64 load+store, here because this improves the odds that the source or
103   // dest address will be promotable.  See if we can find a better type than the
104   // integer datatype.
105   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
106   MDNode *CopyMD = nullptr;
107   if (StrippedDest != MI->getArgOperand(0)) {
108     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
109                                     ->getElementType();
110     if (SrcETy->isSized() && DL.getTypeStoreSize(SrcETy) == Size) {
111       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
112       // down through these levels if so.
113       SrcETy = reduceToSingleValueType(SrcETy);
114
115       if (SrcETy->isSingleValueType()) {
116         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
117         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
118
119         // If the memcpy has metadata describing the members, see if we can
120         // get the TBAA tag describing our copy.
121         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
122           if (M->getNumOperands() == 3 && M->getOperand(0) &&
123               mdconst::hasa<ConstantInt>(M->getOperand(0)) &&
124               mdconst::extract<ConstantInt>(M->getOperand(0))->isNullValue() &&
125               M->getOperand(1) &&
126               mdconst::hasa<ConstantInt>(M->getOperand(1)) &&
127               mdconst::extract<ConstantInt>(M->getOperand(1))->getValue() ==
128                   Size &&
129               M->getOperand(2) && isa<MDNode>(M->getOperand(2)))
130             CopyMD = cast<MDNode>(M->getOperand(2));
131         }
132       }
133     }
134   }
135
136   // If the memcpy/memmove provides better alignment info than we can
137   // infer, use it.
138   SrcAlign = std::max(SrcAlign, CopyAlign);
139   DstAlign = std::max(DstAlign, CopyAlign);
140
141   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
142   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
143   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
144   L->setAlignment(SrcAlign);
145   if (CopyMD)
146     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
147   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
148   S->setAlignment(DstAlign);
149   if (CopyMD)
150     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
151
152   // Set the size of the copy to 0, it will be deleted on the next iteration.
153   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
154   return MI;
155 }
156
157 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
158   unsigned Alignment = getKnownAlignment(MI->getDest(), DL, MI, AC, DT);
159   if (MI->getAlignment() < Alignment) {
160     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
161                                              Alignment, false));
162     return MI;
163   }
164
165   // Extract the length and alignment and fill if they are constant.
166   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
167   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
168   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
169     return nullptr;
170   uint64_t Len = LenC->getLimitedValue();
171   Alignment = MI->getAlignment();
172   assert(Len && "0-sized memory setting should be removed already.");
173
174   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
175   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
176     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
177
178     Value *Dest = MI->getDest();
179     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
180     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
181     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
182
183     // Alignment 0 is identity for alignment 1 for memset, but not store.
184     if (Alignment == 0) Alignment = 1;
185
186     // Extract the fill value and store.
187     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
188     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
189                                         MI->isVolatile());
190     S->setAlignment(Alignment);
191
192     // Set the size of the copy to 0, it will be deleted on the next iteration.
193     MI->setLength(Constant::getNullValue(LenC->getType()));
194     return MI;
195   }
196
197   return nullptr;
198 }
199
200 static Value *SimplifyX86immshift(const IntrinsicInst &II,
201                                   InstCombiner::BuilderTy &Builder,
202                                   bool LogicalShift, bool ShiftLeft) {
203   assert((LogicalShift || !ShiftLeft) && "Only logical shifts can shift left");
204
205   // Simplify if count is constant.
206   auto Arg1 = II.getArgOperand(1);
207   auto CAZ = dyn_cast<ConstantAggregateZero>(Arg1);
208   auto CDV = dyn_cast<ConstantDataVector>(Arg1);
209   auto CInt = dyn_cast<ConstantInt>(Arg1);
210   if (!CAZ && !CDV && !CInt)
211     return nullptr;
212
213   APInt Count(64, 0);
214   if (CDV) {
215     // SSE2/AVX2 uses all the first 64-bits of the 128-bit vector
216     // operand to compute the shift amount.
217     auto VT = cast<VectorType>(CDV->getType());
218     unsigned BitWidth = VT->getElementType()->getPrimitiveSizeInBits();
219     assert((64 % BitWidth) == 0 && "Unexpected packed shift size");
220     unsigned NumSubElts = 64 / BitWidth;
221
222     // Concatenate the sub-elements to create the 64-bit value.
223     for (unsigned i = 0; i != NumSubElts; ++i) {
224       unsigned SubEltIdx = (NumSubElts - 1) - i;
225       auto SubElt = cast<ConstantInt>(CDV->getElementAsConstant(SubEltIdx));
226       Count = Count.shl(BitWidth);
227       Count |= SubElt->getValue().zextOrTrunc(64);
228     }
229   }
230   else if (CInt)
231     Count = CInt->getValue();
232
233   auto Vec = II.getArgOperand(0);
234   auto VT = cast<VectorType>(Vec->getType());
235   auto SVT = VT->getElementType();
236   unsigned VWidth = VT->getNumElements();
237   unsigned BitWidth = SVT->getPrimitiveSizeInBits();
238
239   // If shift-by-zero then just return the original value.
240   if (Count == 0)
241     return Vec;
242
243   // Handle cases when Shift >= BitWidth.
244   if (Count.uge(BitWidth)) {
245     // If LogicalShift - just return zero.
246     if (LogicalShift)
247       return ConstantAggregateZero::get(VT);
248
249     // If ArithmeticShift - clamp Shift to (BitWidth - 1).
250     Count = APInt(64, BitWidth - 1);
251   }
252
253   // Get a constant vector of the same type as the first operand.
254   auto ShiftAmt = ConstantInt::get(SVT, Count.zextOrTrunc(BitWidth));
255   auto ShiftVec = Builder.CreateVectorSplat(VWidth, ShiftAmt);
256
257   if (ShiftLeft)
258     return Builder.CreateShl(Vec, ShiftVec);
259
260   if (LogicalShift)
261     return Builder.CreateLShr(Vec, ShiftVec);
262
263   return Builder.CreateAShr(Vec, ShiftVec);
264 }
265
266 static Value *SimplifyX86extend(const IntrinsicInst &II,
267                                 InstCombiner::BuilderTy &Builder,
268                                 bool SignExtend) {
269   VectorType *SrcTy = cast<VectorType>(II.getArgOperand(0)->getType());
270   VectorType *DstTy = cast<VectorType>(II.getType());
271   unsigned NumDstElts = DstTy->getNumElements();
272
273   // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
274   SmallVector<int, 8> ShuffleMask;
275   for (int i = 0; i != (int)NumDstElts; ++i)
276     ShuffleMask.push_back(i);
277
278   Value *SV = Builder.CreateShuffleVector(II.getArgOperand(0),
279                                           UndefValue::get(SrcTy), ShuffleMask);
280   return SignExtend ? Builder.CreateSExt(SV, DstTy)
281                     : Builder.CreateZExt(SV, DstTy);
282 }
283
284 static Value *SimplifyX86insertps(const IntrinsicInst &II,
285                                   InstCombiner::BuilderTy &Builder) {
286   if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
287     VectorType *VecTy = cast<VectorType>(II.getType());
288     assert(VecTy->getNumElements() == 4 && "insertps with wrong vector type");
289
290     // The immediate permute control byte looks like this:
291     //    [3:0] - zero mask for each 32-bit lane
292     //    [5:4] - select one 32-bit destination lane
293     //    [7:6] - select one 32-bit source lane
294
295     uint8_t Imm = CInt->getZExtValue();
296     uint8_t ZMask = Imm & 0xf;
297     uint8_t DestLane = (Imm >> 4) & 0x3;
298     uint8_t SourceLane = (Imm >> 6) & 0x3;
299
300     ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
301
302     // If all zero mask bits are set, this was just a weird way to
303     // generate a zero vector.
304     if (ZMask == 0xf)
305       return ZeroVector;
306
307     // Initialize by passing all of the first source bits through.
308     int ShuffleMask[4] = { 0, 1, 2, 3 };
309
310     // We may replace the second operand with the zero vector.
311     Value *V1 = II.getArgOperand(1);
312
313     if (ZMask) {
314       // If the zero mask is being used with a single input or the zero mask
315       // overrides the destination lane, this is a shuffle with the zero vector.
316       if ((II.getArgOperand(0) == II.getArgOperand(1)) ||
317           (ZMask & (1 << DestLane))) {
318         V1 = ZeroVector;
319         // We may still move 32-bits of the first source vector from one lane
320         // to another.
321         ShuffleMask[DestLane] = SourceLane;
322         // The zero mask may override the previous insert operation.
323         for (unsigned i = 0; i < 4; ++i)
324           if ((ZMask >> i) & 0x1)
325             ShuffleMask[i] = i + 4;
326       } else {
327         // TODO: Model this case as 2 shuffles or a 'logical and' plus shuffle?
328         return nullptr;
329       }
330     } else {
331       // Replace the selected destination lane with the selected source lane.
332       ShuffleMask[DestLane] = SourceLane + 4;
333     }
334
335     return Builder.CreateShuffleVector(II.getArgOperand(0), V1, ShuffleMask);
336   }
337   return nullptr;
338 }
339
340 /// The shuffle mask for a perm2*128 selects any two halves of two 256-bit
341 /// source vectors, unless a zero bit is set. If a zero bit is set,
342 /// then ignore that half of the mask and clear that half of the vector.
343 static Value *SimplifyX86vperm2(const IntrinsicInst &II,
344                                 InstCombiner::BuilderTy &Builder) {
345   if (auto *CInt = dyn_cast<ConstantInt>(II.getArgOperand(2))) {
346     VectorType *VecTy = cast<VectorType>(II.getType());
347     ConstantAggregateZero *ZeroVector = ConstantAggregateZero::get(VecTy);
348
349     // The immediate permute control byte looks like this:
350     //    [1:0] - select 128 bits from sources for low half of destination
351     //    [2]   - ignore
352     //    [3]   - zero low half of destination
353     //    [5:4] - select 128 bits from sources for high half of destination
354     //    [6]   - ignore
355     //    [7]   - zero high half of destination
356
357     uint8_t Imm = CInt->getZExtValue();
358
359     bool LowHalfZero = Imm & 0x08;
360     bool HighHalfZero = Imm & 0x80;
361
362     // If both zero mask bits are set, this was just a weird way to
363     // generate a zero vector.
364     if (LowHalfZero && HighHalfZero)
365       return ZeroVector;
366
367     // If 0 or 1 zero mask bits are set, this is a simple shuffle.
368     unsigned NumElts = VecTy->getNumElements();
369     unsigned HalfSize = NumElts / 2;
370     SmallVector<int, 8> ShuffleMask(NumElts);
371
372     // The high bit of the selection field chooses the 1st or 2nd operand.
373     bool LowInputSelect = Imm & 0x02;
374     bool HighInputSelect = Imm & 0x20;
375
376     // The low bit of the selection field chooses the low or high half
377     // of the selected operand.
378     bool LowHalfSelect = Imm & 0x01;
379     bool HighHalfSelect = Imm & 0x10;
380
381     // Determine which operand(s) are actually in use for this instruction.
382     Value *V0 = LowInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
383     Value *V1 = HighInputSelect ? II.getArgOperand(1) : II.getArgOperand(0);
384
385     // If needed, replace operands based on zero mask.
386     V0 = LowHalfZero ? ZeroVector : V0;
387     V1 = HighHalfZero ? ZeroVector : V1;
388
389     // Permute low half of result.
390     unsigned StartIndex = LowHalfSelect ? HalfSize : 0;
391     for (unsigned i = 0; i < HalfSize; ++i)
392       ShuffleMask[i] = StartIndex + i;
393
394     // Permute high half of result.
395     StartIndex = HighHalfSelect ? HalfSize : 0;
396     StartIndex += NumElts;
397     for (unsigned i = 0; i < HalfSize; ++i)
398       ShuffleMask[i + HalfSize] = StartIndex + i;
399
400     return Builder.CreateShuffleVector(V0, V1, ShuffleMask);
401   }
402   return nullptr;
403 }
404
405 /// visitCallInst - CallInst simplification.  This mostly only handles folding
406 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
407 /// the heavy lifting.
408 ///
409 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
410   auto Args = CI.arg_operands();
411   if (Value *V = SimplifyCall(CI.getCalledValue(), Args.begin(), Args.end(), DL,
412                               TLI, DT, AC))
413     return ReplaceInstUsesWith(CI, V);
414
415   if (isFreeCall(&CI, TLI))
416     return visitFree(CI);
417
418   // If the caller function is nounwind, mark the call as nounwind, even if the
419   // callee isn't.
420   if (CI.getParent()->getParent()->doesNotThrow() &&
421       !CI.doesNotThrow()) {
422     CI.setDoesNotThrow();
423     return &CI;
424   }
425
426   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
427   if (!II) return visitCallSite(&CI);
428
429   // Intrinsics cannot occur in an invoke, so handle them here instead of in
430   // visitCallSite.
431   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
432     bool Changed = false;
433
434     // memmove/cpy/set of zero bytes is a noop.
435     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
436       if (NumBytes->isNullValue())
437         return EraseInstFromFunction(CI);
438
439       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
440         if (CI->getZExtValue() == 1) {
441           // Replace the instruction with just byte operations.  We would
442           // transform other cases to loads/stores, but we don't know if
443           // alignment is sufficient.
444         }
445     }
446
447     // No other transformations apply to volatile transfers.
448     if (MI->isVolatile())
449       return nullptr;
450
451     // If we have a memmove and the source operation is a constant global,
452     // then the source and dest pointers can't alias, so we can change this
453     // into a call to memcpy.
454     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
455       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
456         if (GVSrc->isConstant()) {
457           Module *M = CI.getParent()->getParent()->getParent();
458           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
459           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
460                            CI.getArgOperand(1)->getType(),
461                            CI.getArgOperand(2)->getType() };
462           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
463           Changed = true;
464         }
465     }
466
467     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
468       // memmove(x,x,size) -> noop.
469       if (MTI->getSource() == MTI->getDest())
470         return EraseInstFromFunction(CI);
471     }
472
473     // If we can determine a pointer alignment that is bigger than currently
474     // set, update the alignment.
475     if (isa<MemTransferInst>(MI)) {
476       if (Instruction *I = SimplifyMemTransfer(MI))
477         return I;
478     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
479       if (Instruction *I = SimplifyMemSet(MSI))
480         return I;
481     }
482
483     if (Changed) return II;
484   }
485
486   switch (II->getIntrinsicID()) {
487   default: break;
488   case Intrinsic::objectsize: {
489     uint64_t Size;
490     if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
491       return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
492     return nullptr;
493   }
494   case Intrinsic::bswap: {
495     Value *IIOperand = II->getArgOperand(0);
496     Value *X = nullptr;
497
498     // bswap(bswap(x)) -> x
499     if (match(IIOperand, m_BSwap(m_Value(X))))
500         return ReplaceInstUsesWith(CI, X);
501
502     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
503     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
504       unsigned C = X->getType()->getPrimitiveSizeInBits() -
505         IIOperand->getType()->getPrimitiveSizeInBits();
506       Value *CV = ConstantInt::get(X->getType(), C);
507       Value *V = Builder->CreateLShr(X, CV);
508       return new TruncInst(V, IIOperand->getType());
509     }
510     break;
511   }
512
513   case Intrinsic::powi:
514     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
515       // powi(x, 0) -> 1.0
516       if (Power->isZero())
517         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
518       // powi(x, 1) -> x
519       if (Power->isOne())
520         return ReplaceInstUsesWith(CI, II->getArgOperand(0));
521       // powi(x, -1) -> 1/x
522       if (Power->isAllOnesValue())
523         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
524                                           II->getArgOperand(0));
525     }
526     break;
527   case Intrinsic::cttz: {
528     // If all bits below the first known one are known zero,
529     // this value is constant.
530     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
531     // FIXME: Try to simplify vectors of integers.
532     if (!IT) break;
533     uint32_t BitWidth = IT->getBitWidth();
534     APInt KnownZero(BitWidth, 0);
535     APInt KnownOne(BitWidth, 0);
536     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
537     unsigned TrailingZeros = KnownOne.countTrailingZeros();
538     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
539     if ((Mask & KnownZero) == Mask)
540       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
541                                  APInt(BitWidth, TrailingZeros)));
542
543     }
544     break;
545   case Intrinsic::ctlz: {
546     // If all bits above the first known one are known zero,
547     // this value is constant.
548     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
549     // FIXME: Try to simplify vectors of integers.
550     if (!IT) break;
551     uint32_t BitWidth = IT->getBitWidth();
552     APInt KnownZero(BitWidth, 0);
553     APInt KnownOne(BitWidth, 0);
554     computeKnownBits(II->getArgOperand(0), KnownZero, KnownOne, 0, II);
555     unsigned LeadingZeros = KnownOne.countLeadingZeros();
556     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
557     if ((Mask & KnownZero) == Mask)
558       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
559                                  APInt(BitWidth, LeadingZeros)));
560
561     }
562     break;
563
564   case Intrinsic::uadd_with_overflow:
565   case Intrinsic::sadd_with_overflow:
566   case Intrinsic::umul_with_overflow:
567   case Intrinsic::smul_with_overflow:
568     if (isa<Constant>(II->getArgOperand(0)) &&
569         !isa<Constant>(II->getArgOperand(1))) {
570       // Canonicalize constants into the RHS.
571       Value *LHS = II->getArgOperand(0);
572       II->setArgOperand(0, II->getArgOperand(1));
573       II->setArgOperand(1, LHS);
574       return II;
575     }
576     // fall through
577
578   case Intrinsic::usub_with_overflow:
579   case Intrinsic::ssub_with_overflow: {
580     OverflowCheckFlavor OCF =
581         IntrinsicIDToOverflowCheckFlavor(II->getIntrinsicID());
582     assert(OCF != OCF_INVALID && "unexpected!");
583
584     Value *OperationResult = nullptr;
585     Constant *OverflowResult = nullptr;
586     if (OptimizeOverflowCheck(OCF, II->getArgOperand(0), II->getArgOperand(1),
587                               *II, OperationResult, OverflowResult))
588       return CreateOverflowTuple(II, OperationResult, OverflowResult);
589
590     break;
591   }
592
593   case Intrinsic::minnum:
594   case Intrinsic::maxnum: {
595     Value *Arg0 = II->getArgOperand(0);
596     Value *Arg1 = II->getArgOperand(1);
597
598     // fmin(x, x) -> x
599     if (Arg0 == Arg1)
600       return ReplaceInstUsesWith(CI, Arg0);
601
602     const ConstantFP *C0 = dyn_cast<ConstantFP>(Arg0);
603     const ConstantFP *C1 = dyn_cast<ConstantFP>(Arg1);
604
605     // Canonicalize constants into the RHS.
606     if (C0 && !C1) {
607       II->setArgOperand(0, Arg1);
608       II->setArgOperand(1, Arg0);
609       return II;
610     }
611
612     // fmin(x, nan) -> x
613     if (C1 && C1->isNaN())
614       return ReplaceInstUsesWith(CI, Arg0);
615
616     // This is the value because if undef were NaN, we would return the other
617     // value and cannot return a NaN unless both operands are.
618     //
619     // fmin(undef, x) -> x
620     if (isa<UndefValue>(Arg0))
621       return ReplaceInstUsesWith(CI, Arg1);
622
623     // fmin(x, undef) -> x
624     if (isa<UndefValue>(Arg1))
625       return ReplaceInstUsesWith(CI, Arg0);
626
627     Value *X = nullptr;
628     Value *Y = nullptr;
629     if (II->getIntrinsicID() == Intrinsic::minnum) {
630       // fmin(x, fmin(x, y)) -> fmin(x, y)
631       // fmin(y, fmin(x, y)) -> fmin(x, y)
632       if (match(Arg1, m_FMin(m_Value(X), m_Value(Y)))) {
633         if (Arg0 == X || Arg0 == Y)
634           return ReplaceInstUsesWith(CI, Arg1);
635       }
636
637       // fmin(fmin(x, y), x) -> fmin(x, y)
638       // fmin(fmin(x, y), y) -> fmin(x, y)
639       if (match(Arg0, m_FMin(m_Value(X), m_Value(Y)))) {
640         if (Arg1 == X || Arg1 == Y)
641           return ReplaceInstUsesWith(CI, Arg0);
642       }
643
644       // TODO: fmin(nnan x, inf) -> x
645       // TODO: fmin(nnan ninf x, flt_max) -> x
646       if (C1 && C1->isInfinity()) {
647         // fmin(x, -inf) -> -inf
648         if (C1->isNegative())
649           return ReplaceInstUsesWith(CI, Arg1);
650       }
651     } else {
652       assert(II->getIntrinsicID() == Intrinsic::maxnum);
653       // fmax(x, fmax(x, y)) -> fmax(x, y)
654       // fmax(y, fmax(x, y)) -> fmax(x, y)
655       if (match(Arg1, m_FMax(m_Value(X), m_Value(Y)))) {
656         if (Arg0 == X || Arg0 == Y)
657           return ReplaceInstUsesWith(CI, Arg1);
658       }
659
660       // fmax(fmax(x, y), x) -> fmax(x, y)
661       // fmax(fmax(x, y), y) -> fmax(x, y)
662       if (match(Arg0, m_FMax(m_Value(X), m_Value(Y)))) {
663         if (Arg1 == X || Arg1 == Y)
664           return ReplaceInstUsesWith(CI, Arg0);
665       }
666
667       // TODO: fmax(nnan x, -inf) -> x
668       // TODO: fmax(nnan ninf x, -flt_max) -> x
669       if (C1 && C1->isInfinity()) {
670         // fmax(x, inf) -> inf
671         if (!C1->isNegative())
672           return ReplaceInstUsesWith(CI, Arg1);
673       }
674     }
675     break;
676   }
677   case Intrinsic::ppc_altivec_lvx:
678   case Intrinsic::ppc_altivec_lvxl:
679     // Turn PPC lvx -> load if the pointer is known aligned.
680     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
681         16) {
682       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
683                                          PointerType::getUnqual(II->getType()));
684       return new LoadInst(Ptr);
685     }
686     break;
687   case Intrinsic::ppc_vsx_lxvw4x:
688   case Intrinsic::ppc_vsx_lxvd2x: {
689     // Turn PPC VSX loads into normal loads.
690     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
691                                         PointerType::getUnqual(II->getType()));
692     return new LoadInst(Ptr, Twine(""), false, 1);
693   }
694   case Intrinsic::ppc_altivec_stvx:
695   case Intrinsic::ppc_altivec_stvxl:
696     // Turn stvx -> store if the pointer is known aligned.
697     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
698         16) {
699       Type *OpPtrTy =
700         PointerType::getUnqual(II->getArgOperand(0)->getType());
701       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
702       return new StoreInst(II->getArgOperand(0), Ptr);
703     }
704     break;
705   case Intrinsic::ppc_vsx_stxvw4x:
706   case Intrinsic::ppc_vsx_stxvd2x: {
707     // Turn PPC VSX stores into normal stores.
708     Type *OpPtrTy = PointerType::getUnqual(II->getArgOperand(0)->getType());
709     Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
710     return new StoreInst(II->getArgOperand(0), Ptr, false, 1);
711   }
712   case Intrinsic::ppc_qpx_qvlfs:
713     // Turn PPC QPX qvlfs -> load if the pointer is known aligned.
714     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
715         16) {
716       Type *VTy = VectorType::get(Builder->getFloatTy(),
717                                   II->getType()->getVectorNumElements());
718       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
719                                          PointerType::getUnqual(VTy));
720       Value *Load = Builder->CreateLoad(Ptr);
721       return new FPExtInst(Load, II->getType());
722     }
723     break;
724   case Intrinsic::ppc_qpx_qvlfd:
725     // Turn PPC QPX qvlfd -> load if the pointer is known aligned.
726     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 32, DL, II, AC, DT) >=
727         32) {
728       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
729                                          PointerType::getUnqual(II->getType()));
730       return new LoadInst(Ptr);
731     }
732     break;
733   case Intrinsic::ppc_qpx_qvstfs:
734     // Turn PPC QPX qvstfs -> store if the pointer is known aligned.
735     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL, II, AC, DT) >=
736         16) {
737       Type *VTy = VectorType::get(Builder->getFloatTy(),
738           II->getArgOperand(0)->getType()->getVectorNumElements());
739       Value *TOp = Builder->CreateFPTrunc(II->getArgOperand(0), VTy);
740       Type *OpPtrTy = PointerType::getUnqual(VTy);
741       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
742       return new StoreInst(TOp, Ptr);
743     }
744     break;
745   case Intrinsic::ppc_qpx_qvstfd:
746     // Turn PPC QPX qvstfd -> store if the pointer is known aligned.
747     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 32, DL, II, AC, DT) >=
748         32) {
749       Type *OpPtrTy =
750         PointerType::getUnqual(II->getArgOperand(0)->getType());
751       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
752       return new StoreInst(II->getArgOperand(0), Ptr);
753     }
754     break;
755   case Intrinsic::x86_sse_storeu_ps:
756   case Intrinsic::x86_sse2_storeu_pd:
757   case Intrinsic::x86_sse2_storeu_dq:
758     // Turn X86 storeu -> store if the pointer is known aligned.
759     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL, II, AC, DT) >=
760         16) {
761       Type *OpPtrTy =
762         PointerType::getUnqual(II->getArgOperand(1)->getType());
763       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
764       return new StoreInst(II->getArgOperand(1), Ptr);
765     }
766     break;
767
768   case Intrinsic::x86_sse_cvtss2si:
769   case Intrinsic::x86_sse_cvtss2si64:
770   case Intrinsic::x86_sse_cvttss2si:
771   case Intrinsic::x86_sse_cvttss2si64:
772   case Intrinsic::x86_sse2_cvtsd2si:
773   case Intrinsic::x86_sse2_cvtsd2si64:
774   case Intrinsic::x86_sse2_cvttsd2si:
775   case Intrinsic::x86_sse2_cvttsd2si64: {
776     // These intrinsics only demand the 0th element of their input vectors. If
777     // we can simplify the input based on that, do so now.
778     unsigned VWidth =
779       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
780     APInt DemandedElts(VWidth, 1);
781     APInt UndefElts(VWidth, 0);
782     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
783                                               DemandedElts, UndefElts)) {
784       II->setArgOperand(0, V);
785       return II;
786     }
787     break;
788   }
789
790   // Constant fold ashr( <A x Bi>, Ci ).
791   case Intrinsic::x86_sse2_psra_d:
792   case Intrinsic::x86_sse2_psra_w:
793   case Intrinsic::x86_sse2_psrai_d:
794   case Intrinsic::x86_sse2_psrai_w:
795   case Intrinsic::x86_avx2_psra_d:
796   case Intrinsic::x86_avx2_psra_w:
797   case Intrinsic::x86_avx2_psrai_d:
798   case Intrinsic::x86_avx2_psrai_w:
799     if (Value *V = SimplifyX86immshift(*II, *Builder, false, false))
800       return ReplaceInstUsesWith(*II, V);
801     break;
802
803   // Constant fold lshr( <A x Bi>, Ci ).
804   case Intrinsic::x86_sse2_psrl_d:
805   case Intrinsic::x86_sse2_psrl_q:
806   case Intrinsic::x86_sse2_psrl_w:
807   case Intrinsic::x86_sse2_psrli_d:
808   case Intrinsic::x86_sse2_psrli_q:
809   case Intrinsic::x86_sse2_psrli_w:
810   case Intrinsic::x86_avx2_psrl_d:
811   case Intrinsic::x86_avx2_psrl_q:
812   case Intrinsic::x86_avx2_psrl_w:
813   case Intrinsic::x86_avx2_psrli_d:
814   case Intrinsic::x86_avx2_psrli_q:
815   case Intrinsic::x86_avx2_psrli_w:
816     if (Value *V = SimplifyX86immshift(*II, *Builder, true, false))
817       return ReplaceInstUsesWith(*II, V);
818     break;
819
820   // Constant fold shl( <A x Bi>, Ci ).
821   case Intrinsic::x86_sse2_psll_d:
822   case Intrinsic::x86_sse2_psll_q:
823   case Intrinsic::x86_sse2_psll_w:
824   case Intrinsic::x86_sse2_pslli_d:
825   case Intrinsic::x86_sse2_pslli_q:
826   case Intrinsic::x86_sse2_pslli_w:
827   case Intrinsic::x86_avx2_psll_d:
828   case Intrinsic::x86_avx2_psll_q:
829   case Intrinsic::x86_avx2_psll_w:
830   case Intrinsic::x86_avx2_pslli_d:
831   case Intrinsic::x86_avx2_pslli_q:
832   case Intrinsic::x86_avx2_pslli_w:
833     if (Value *V = SimplifyX86immshift(*II, *Builder, true, true))
834       return ReplaceInstUsesWith(*II, V);
835     break;
836
837   case Intrinsic::x86_sse41_pmovsxbd:
838   case Intrinsic::x86_sse41_pmovsxbq:
839   case Intrinsic::x86_sse41_pmovsxbw:
840   case Intrinsic::x86_sse41_pmovsxdq:
841   case Intrinsic::x86_sse41_pmovsxwd:
842   case Intrinsic::x86_sse41_pmovsxwq:
843   case Intrinsic::x86_avx2_pmovsxbd:
844   case Intrinsic::x86_avx2_pmovsxbq:
845   case Intrinsic::x86_avx2_pmovsxbw:
846   case Intrinsic::x86_avx2_pmovsxdq:
847   case Intrinsic::x86_avx2_pmovsxwd:
848   case Intrinsic::x86_avx2_pmovsxwq:
849     if (Value *V = SimplifyX86extend(*II, *Builder, true))
850       return ReplaceInstUsesWith(*II, V);
851     break;
852
853   case Intrinsic::x86_sse41_pmovzxbd:
854   case Intrinsic::x86_sse41_pmovzxbq:
855   case Intrinsic::x86_sse41_pmovzxbw:
856   case Intrinsic::x86_sse41_pmovzxdq:
857   case Intrinsic::x86_sse41_pmovzxwd:
858   case Intrinsic::x86_sse41_pmovzxwq:
859   case Intrinsic::x86_avx2_pmovzxbd:
860   case Intrinsic::x86_avx2_pmovzxbq:
861   case Intrinsic::x86_avx2_pmovzxbw:
862   case Intrinsic::x86_avx2_pmovzxdq:
863   case Intrinsic::x86_avx2_pmovzxwd:
864   case Intrinsic::x86_avx2_pmovzxwq:
865     if (Value *V = SimplifyX86extend(*II, *Builder, false))
866       return ReplaceInstUsesWith(*II, V);
867     break;
868
869   case Intrinsic::x86_sse41_insertps:
870     if (Value *V = SimplifyX86insertps(*II, *Builder))
871       return ReplaceInstUsesWith(*II, V);
872     break;
873
874   case Intrinsic::x86_sse4a_insertqi: {
875     // insertqi x, y, 64, 0 can just copy y's lower bits and leave the top
876     // ones undef
877     // TODO: eventually we should lower this intrinsic to IR
878     if (auto CILength = dyn_cast<ConstantInt>(II->getArgOperand(2))) {
879       if (auto CIIndex = dyn_cast<ConstantInt>(II->getArgOperand(3))) {
880         unsigned Index = CIIndex->getZExtValue();
881         // From AMD documentation: "a value of zero in the field length is
882         // defined as length of 64".
883         unsigned Length = CILength->equalsInt(0) ? 64 : CILength->getZExtValue();
884
885         // From AMD documentation: "If the sum of the bit index + length field
886         // is greater than 64, the results are undefined".
887         unsigned End = Index + Length;
888
889         // Note that both field index and field length are 8-bit quantities.
890         // Since variables 'Index' and 'Length' are unsigned values
891         // obtained from zero-extending field index and field length
892         // respectively, their sum should never wrap around.
893         if (End > 64)
894           return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
895
896         if (Length == 64 && Index == 0) {
897           Value *Vec = II->getArgOperand(1);
898           Value *Undef = UndefValue::get(Vec->getType());
899           const uint32_t Mask[] = { 0, 2 };
900           return ReplaceInstUsesWith(
901               CI,
902               Builder->CreateShuffleVector(
903                   Vec, Undef, ConstantDataVector::get(
904                                   II->getContext(), makeArrayRef(Mask))));
905         } else if (auto Source =
906                        dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
907           if (Source->hasOneUse() &&
908               Source->getArgOperand(1) == II->getArgOperand(1)) {
909             // If the source of the insert has only one use and it's another
910             // insert (and they're both inserting from the same vector), try to
911             // bundle both together.
912             auto CISourceLength =
913                 dyn_cast<ConstantInt>(Source->getArgOperand(2));
914             auto CISourceIndex =
915                 dyn_cast<ConstantInt>(Source->getArgOperand(3));
916             if (CISourceIndex && CISourceLength) {
917               unsigned SourceIndex = CISourceIndex->getZExtValue();
918               unsigned SourceLength = CISourceLength->getZExtValue();
919               unsigned SourceEnd = SourceIndex + SourceLength;
920               unsigned NewIndex, NewLength;
921               bool ShouldReplace = false;
922               if (Index <= SourceIndex && SourceIndex <= End) {
923                 NewIndex = Index;
924                 NewLength = std::max(End, SourceEnd) - NewIndex;
925                 ShouldReplace = true;
926               } else if (SourceIndex <= Index && Index <= SourceEnd) {
927                 NewIndex = SourceIndex;
928                 NewLength = std::max(SourceEnd, End) - NewIndex;
929                 ShouldReplace = true;
930               }
931
932               if (ShouldReplace) {
933                 Constant *ConstantLength = ConstantInt::get(
934                     II->getArgOperand(2)->getType(), NewLength, false);
935                 Constant *ConstantIndex = ConstantInt::get(
936                     II->getArgOperand(3)->getType(), NewIndex, false);
937                 Value *Args[4] = { Source->getArgOperand(0),
938                                    II->getArgOperand(1), ConstantLength,
939                                    ConstantIndex };
940                 Module *M = CI.getParent()->getParent()->getParent();
941                 Value *F =
942                     Intrinsic::getDeclaration(M, Intrinsic::x86_sse4a_insertqi);
943                 return ReplaceInstUsesWith(CI, Builder->CreateCall(F, Args));
944               }
945             }
946           }
947         }
948       }
949     }
950     break;
951   }
952
953   case Intrinsic::x86_sse41_pblendvb:
954   case Intrinsic::x86_sse41_blendvps:
955   case Intrinsic::x86_sse41_blendvpd:
956   case Intrinsic::x86_avx_blendv_ps_256:
957   case Intrinsic::x86_avx_blendv_pd_256:
958   case Intrinsic::x86_avx2_pblendvb: {
959     // Convert blendv* to vector selects if the mask is constant.
960     // This optimization is convoluted because the intrinsic is defined as
961     // getting a vector of floats or doubles for the ps and pd versions.
962     // FIXME: That should be changed.
963     Value *Mask = II->getArgOperand(2);
964     if (auto C = dyn_cast<ConstantDataVector>(Mask)) {
965       auto Tyi1 = Builder->getInt1Ty();
966       auto SelectorType = cast<VectorType>(Mask->getType());
967       auto EltTy = SelectorType->getElementType();
968       unsigned Size = SelectorType->getNumElements();
969       unsigned BitWidth =
970           EltTy->isFloatTy()
971               ? 32
972               : (EltTy->isDoubleTy() ? 64 : EltTy->getIntegerBitWidth());
973       assert((BitWidth == 64 || BitWidth == 32 || BitWidth == 8) &&
974              "Wrong arguments for variable blend intrinsic");
975       SmallVector<Constant *, 32> Selectors;
976       for (unsigned I = 0; I < Size; ++I) {
977         // The intrinsics only read the top bit
978         uint64_t Selector;
979         if (BitWidth == 8)
980           Selector = C->getElementAsInteger(I);
981         else
982           Selector = C->getElementAsAPFloat(I).bitcastToAPInt().getZExtValue();
983         Selectors.push_back(ConstantInt::get(Tyi1, Selector >> (BitWidth - 1)));
984       }
985       auto NewSelector = ConstantVector::get(Selectors);
986       return SelectInst::Create(NewSelector, II->getArgOperand(1),
987                                 II->getArgOperand(0), "blendv");
988     } else {
989       break;
990     }
991   }
992
993   case Intrinsic::x86_avx_vpermilvar_ps:
994   case Intrinsic::x86_avx_vpermilvar_ps_256:
995   case Intrinsic::x86_avx_vpermilvar_pd:
996   case Intrinsic::x86_avx_vpermilvar_pd_256: {
997     // Convert vpermil* to shufflevector if the mask is constant.
998     Value *V = II->getArgOperand(1);
999     unsigned Size = cast<VectorType>(V->getType())->getNumElements();
1000     assert(Size == 8 || Size == 4 || Size == 2);
1001     uint32_t Indexes[8];
1002     if (auto C = dyn_cast<ConstantDataVector>(V)) {
1003       // The intrinsics only read one or two bits, clear the rest.
1004       for (unsigned I = 0; I < Size; ++I) {
1005         uint32_t Index = C->getElementAsInteger(I) & 0x3;
1006         if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd ||
1007             II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256)
1008           Index >>= 1;
1009         Indexes[I] = Index;
1010       }
1011     } else if (isa<ConstantAggregateZero>(V)) {
1012       for (unsigned I = 0; I < Size; ++I)
1013         Indexes[I] = 0;
1014     } else {
1015       break;
1016     }
1017     // The _256 variants are a bit trickier since the mask bits always index
1018     // into the corresponding 128 half. In order to convert to a generic
1019     // shuffle, we have to make that explicit.
1020     if (II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_ps_256 ||
1021         II->getIntrinsicID() == Intrinsic::x86_avx_vpermilvar_pd_256) {
1022       for (unsigned I = Size / 2; I < Size; ++I)
1023         Indexes[I] += Size / 2;
1024     }
1025     auto NewC =
1026         ConstantDataVector::get(V->getContext(), makeArrayRef(Indexes, Size));
1027     auto V1 = II->getArgOperand(0);
1028     auto V2 = UndefValue::get(V1->getType());
1029     auto Shuffle = Builder->CreateShuffleVector(V1, V2, NewC);
1030     return ReplaceInstUsesWith(CI, Shuffle);
1031   }
1032
1033   case Intrinsic::x86_avx_vperm2f128_pd_256:
1034   case Intrinsic::x86_avx_vperm2f128_ps_256:
1035   case Intrinsic::x86_avx_vperm2f128_si_256:
1036   case Intrinsic::x86_avx2_vperm2i128:
1037     if (Value *V = SimplifyX86vperm2(*II, *Builder))
1038       return ReplaceInstUsesWith(*II, V);
1039     break;
1040
1041   case Intrinsic::ppc_altivec_vperm:
1042     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
1043     // Note that ppc_altivec_vperm has a big-endian bias, so when creating
1044     // a vectorshuffle for little endian, we must undo the transformation
1045     // performed on vec_perm in altivec.h.  That is, we must complement
1046     // the permutation mask with respect to 31 and reverse the order of
1047     // V1 and V2.
1048     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
1049       assert(Mask->getType()->getVectorNumElements() == 16 &&
1050              "Bad type for intrinsic!");
1051
1052       // Check that all of the elements are integer constants or undefs.
1053       bool AllEltsOk = true;
1054       for (unsigned i = 0; i != 16; ++i) {
1055         Constant *Elt = Mask->getAggregateElement(i);
1056         if (!Elt || !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
1057           AllEltsOk = false;
1058           break;
1059         }
1060       }
1061
1062       if (AllEltsOk) {
1063         // Cast the input vectors to byte vectors.
1064         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
1065                                             Mask->getType());
1066         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
1067                                             Mask->getType());
1068         Value *Result = UndefValue::get(Op0->getType());
1069
1070         // Only extract each element once.
1071         Value *ExtractedElts[32];
1072         memset(ExtractedElts, 0, sizeof(ExtractedElts));
1073
1074         for (unsigned i = 0; i != 16; ++i) {
1075           if (isa<UndefValue>(Mask->getAggregateElement(i)))
1076             continue;
1077           unsigned Idx =
1078             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
1079           Idx &= 31;  // Match the hardware behavior.
1080           if (DL.isLittleEndian())
1081             Idx = 31 - Idx;
1082
1083           if (!ExtractedElts[Idx]) {
1084             Value *Op0ToUse = (DL.isLittleEndian()) ? Op1 : Op0;
1085             Value *Op1ToUse = (DL.isLittleEndian()) ? Op0 : Op1;
1086             ExtractedElts[Idx] =
1087               Builder->CreateExtractElement(Idx < 16 ? Op0ToUse : Op1ToUse,
1088                                             Builder->getInt32(Idx&15));
1089           }
1090
1091           // Insert this value into the result vector.
1092           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
1093                                                 Builder->getInt32(i));
1094         }
1095         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
1096       }
1097     }
1098     break;
1099
1100   case Intrinsic::arm_neon_vld1:
1101   case Intrinsic::arm_neon_vld2:
1102   case Intrinsic::arm_neon_vld3:
1103   case Intrinsic::arm_neon_vld4:
1104   case Intrinsic::arm_neon_vld2lane:
1105   case Intrinsic::arm_neon_vld3lane:
1106   case Intrinsic::arm_neon_vld4lane:
1107   case Intrinsic::arm_neon_vst1:
1108   case Intrinsic::arm_neon_vst2:
1109   case Intrinsic::arm_neon_vst3:
1110   case Intrinsic::arm_neon_vst4:
1111   case Intrinsic::arm_neon_vst2lane:
1112   case Intrinsic::arm_neon_vst3lane:
1113   case Intrinsic::arm_neon_vst4lane: {
1114     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL, II, AC, DT);
1115     unsigned AlignArg = II->getNumArgOperands() - 1;
1116     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
1117     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
1118       II->setArgOperand(AlignArg,
1119                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
1120                                          MemAlign, false));
1121       return II;
1122     }
1123     break;
1124   }
1125
1126   case Intrinsic::arm_neon_vmulls:
1127   case Intrinsic::arm_neon_vmullu:
1128   case Intrinsic::aarch64_neon_smull:
1129   case Intrinsic::aarch64_neon_umull: {
1130     Value *Arg0 = II->getArgOperand(0);
1131     Value *Arg1 = II->getArgOperand(1);
1132
1133     // Handle mul by zero first:
1134     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
1135       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
1136     }
1137
1138     // Check for constant LHS & RHS - in this case we just simplify.
1139     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
1140                  II->getIntrinsicID() == Intrinsic::aarch64_neon_umull);
1141     VectorType *NewVT = cast<VectorType>(II->getType());
1142     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
1143       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
1144         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
1145         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
1146
1147         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
1148       }
1149
1150       // Couldn't simplify - canonicalize constant to the RHS.
1151       std::swap(Arg0, Arg1);
1152     }
1153
1154     // Handle mul by one:
1155     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
1156       if (ConstantInt *Splat =
1157               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
1158         if (Splat->isOne())
1159           return CastInst::CreateIntegerCast(Arg0, II->getType(),
1160                                              /*isSigned=*/!Zext);
1161
1162     break;
1163   }
1164
1165   case Intrinsic::AMDGPU_rcp: {
1166     if (const ConstantFP *C = dyn_cast<ConstantFP>(II->getArgOperand(0))) {
1167       const APFloat &ArgVal = C->getValueAPF();
1168       APFloat Val(ArgVal.getSemantics(), 1.0);
1169       APFloat::opStatus Status = Val.divide(ArgVal,
1170                                             APFloat::rmNearestTiesToEven);
1171       // Only do this if it was exact and therefore not dependent on the
1172       // rounding mode.
1173       if (Status == APFloat::opOK)
1174         return ReplaceInstUsesWith(CI, ConstantFP::get(II->getContext(), Val));
1175     }
1176
1177     break;
1178   }
1179   case Intrinsic::stackrestore: {
1180     // If the save is right next to the restore, remove the restore.  This can
1181     // happen when variable allocas are DCE'd.
1182     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
1183       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
1184         BasicBlock::iterator BI = SS;
1185         if (&*++BI == II)
1186           return EraseInstFromFunction(CI);
1187       }
1188     }
1189
1190     // Scan down this block to see if there is another stack restore in the
1191     // same block without an intervening call/alloca.
1192     BasicBlock::iterator BI = II;
1193     TerminatorInst *TI = II->getParent()->getTerminator();
1194     bool CannotRemove = false;
1195     for (++BI; &*BI != TI; ++BI) {
1196       if (isa<AllocaInst>(BI)) {
1197         CannotRemove = true;
1198         break;
1199       }
1200       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
1201         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
1202           // If there is a stackrestore below this one, remove this one.
1203           if (II->getIntrinsicID() == Intrinsic::stackrestore)
1204             return EraseInstFromFunction(CI);
1205           // Otherwise, ignore the intrinsic.
1206         } else {
1207           // If we found a non-intrinsic call, we can't remove the stack
1208           // restore.
1209           CannotRemove = true;
1210           break;
1211         }
1212       }
1213     }
1214
1215     // If the stack restore is in a return, resume, or unwind block and if there
1216     // are no allocas or calls between the restore and the return, nuke the
1217     // restore.
1218     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
1219       return EraseInstFromFunction(CI);
1220     break;
1221   }
1222   case Intrinsic::assume: {
1223     // Canonicalize assume(a && b) -> assume(a); assume(b);
1224     // Note: New assumption intrinsics created here are registered by
1225     // the InstCombineIRInserter object.
1226     Value *IIOperand = II->getArgOperand(0), *A, *B,
1227           *AssumeIntrinsic = II->getCalledValue();
1228     if (match(IIOperand, m_And(m_Value(A), m_Value(B)))) {
1229       Builder->CreateCall(AssumeIntrinsic, A, II->getName());
1230       Builder->CreateCall(AssumeIntrinsic, B, II->getName());
1231       return EraseInstFromFunction(*II);
1232     }
1233     // assume(!(a || b)) -> assume(!a); assume(!b);
1234     if (match(IIOperand, m_Not(m_Or(m_Value(A), m_Value(B))))) {
1235       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(A),
1236                           II->getName());
1237       Builder->CreateCall(AssumeIntrinsic, Builder->CreateNot(B),
1238                           II->getName());
1239       return EraseInstFromFunction(*II);
1240     }
1241
1242     // assume( (load addr) != null ) -> add 'nonnull' metadata to load
1243     // (if assume is valid at the load)
1244     if (ICmpInst* ICmp = dyn_cast<ICmpInst>(IIOperand)) {
1245       Value *LHS = ICmp->getOperand(0);
1246       Value *RHS = ICmp->getOperand(1);
1247       if (ICmpInst::ICMP_NE == ICmp->getPredicate() &&
1248           isa<LoadInst>(LHS) &&
1249           isa<Constant>(RHS) &&
1250           RHS->getType()->isPointerTy() &&
1251           cast<Constant>(RHS)->isNullValue()) {
1252         LoadInst* LI = cast<LoadInst>(LHS);
1253         if (isValidAssumeForContext(II, LI, DT)) {
1254           MDNode *MD = MDNode::get(II->getContext(), None);
1255           LI->setMetadata(LLVMContext::MD_nonnull, MD);
1256           return EraseInstFromFunction(*II);
1257         }
1258       }
1259       // TODO: apply nonnull return attributes to calls and invokes
1260       // TODO: apply range metadata for range check patterns?
1261     }
1262     // If there is a dominating assume with the same condition as this one,
1263     // then this one is redundant, and should be removed.
1264     APInt KnownZero(1, 0), KnownOne(1, 0);
1265     computeKnownBits(IIOperand, KnownZero, KnownOne, 0, II);
1266     if (KnownOne.isAllOnesValue())
1267       return EraseInstFromFunction(*II);
1268
1269     break;
1270   }
1271   case Intrinsic::experimental_gc_relocate: {
1272     // Translate facts known about a pointer before relocating into
1273     // facts about the relocate value, while being careful to
1274     // preserve relocation semantics.
1275     GCRelocateOperands Operands(II);
1276     Value *DerivedPtr = Operands.getDerivedPtr();
1277     auto *GCRelocateType = cast<PointerType>(II->getType());
1278
1279     // Remove the relocation if unused, note that this check is required
1280     // to prevent the cases below from looping forever.
1281     if (II->use_empty())
1282       return EraseInstFromFunction(*II);
1283
1284     // Undef is undef, even after relocation.
1285     // TODO: provide a hook for this in GCStrategy.  This is clearly legal for
1286     // most practical collectors, but there was discussion in the review thread
1287     // about whether it was legal for all possible collectors.
1288     if (isa<UndefValue>(DerivedPtr)) {
1289       // gc_relocate is uncasted. Use undef of gc_relocate's type to replace it.
1290       return ReplaceInstUsesWith(*II, UndefValue::get(GCRelocateType));
1291     }
1292
1293     // The relocation of null will be null for most any collector.
1294     // TODO: provide a hook for this in GCStrategy.  There might be some weird
1295     // collector this property does not hold for.
1296     if (isa<ConstantPointerNull>(DerivedPtr)) {
1297       // gc_relocate is uncasted. Use null-pointer of gc_relocate's type to replace it.
1298       return ReplaceInstUsesWith(*II, ConstantPointerNull::get(GCRelocateType));
1299     }
1300
1301     // isKnownNonNull -> nonnull attribute
1302     if (isKnownNonNull(DerivedPtr))
1303       II->addAttribute(AttributeSet::ReturnIndex, Attribute::NonNull);
1304
1305     // isDereferenceablePointer -> deref attribute
1306     if (isDereferenceablePointer(DerivedPtr, DL)) {
1307       if (Argument *A = dyn_cast<Argument>(DerivedPtr)) {
1308         uint64_t Bytes = A->getDereferenceableBytes();
1309         II->addDereferenceableAttr(AttributeSet::ReturnIndex, Bytes);
1310       }
1311     }
1312
1313     // TODO: bitcast(relocate(p)) -> relocate(bitcast(p))
1314     // Canonicalize on the type from the uses to the defs
1315
1316     // TODO: relocate((gep p, C, C2, ...)) -> gep(relocate(p), C, C2, ...)
1317   }
1318   }
1319
1320   return visitCallSite(II);
1321 }
1322
1323 // InvokeInst simplification
1324 //
1325 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1326   return visitCallSite(&II);
1327 }
1328
1329 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
1330 /// passed through the varargs area, we can eliminate the use of the cast.
1331 static bool isSafeToEliminateVarargsCast(const CallSite CS,
1332                                          const DataLayout &DL,
1333                                          const CastInst *const CI,
1334                                          const int ix) {
1335   if (!CI->isLosslessCast())
1336     return false;
1337
1338   // If this is a GC intrinsic, avoid munging types.  We need types for
1339   // statepoint reconstruction in SelectionDAG.
1340   // TODO: This is probably something which should be expanded to all
1341   // intrinsics since the entire point of intrinsics is that
1342   // they are understandable by the optimizer.
1343   if (isStatepoint(CS) || isGCRelocate(CS) || isGCResult(CS))
1344     return false;
1345
1346   // The size of ByVal or InAlloca arguments is derived from the type, so we
1347   // can't change to a type with a different size.  If the size were
1348   // passed explicitly we could avoid this check.
1349   if (!CS.isByValOrInAllocaArgument(ix))
1350     return true;
1351
1352   Type* SrcTy =
1353             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
1354   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
1355   if (!SrcTy->isSized() || !DstTy->isSized())
1356     return false;
1357   if (DL.getTypeAllocSize(SrcTy) != DL.getTypeAllocSize(DstTy))
1358     return false;
1359   return true;
1360 }
1361
1362 // Try to fold some different type of calls here.
1363 // Currently we're only working with the checking functions, memcpy_chk,
1364 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
1365 // strcat_chk and strncat_chk.
1366 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI) {
1367   if (!CI->getCalledFunction()) return nullptr;
1368
1369   auto InstCombineRAUW = [this](Instruction *From, Value *With) {
1370     ReplaceInstUsesWith(*From, With);
1371   };
1372   LibCallSimplifier Simplifier(DL, TLI, InstCombineRAUW);
1373   if (Value *With = Simplifier.optimizeCall(CI)) {
1374     ++NumSimplified;
1375     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
1376   }
1377
1378   return nullptr;
1379 }
1380
1381 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
1382   // Strip off at most one level of pointer casts, looking for an alloca.  This
1383   // is good enough in practice and simpler than handling any number of casts.
1384   Value *Underlying = TrampMem->stripPointerCasts();
1385   if (Underlying != TrampMem &&
1386       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
1387     return nullptr;
1388   if (!isa<AllocaInst>(Underlying))
1389     return nullptr;
1390
1391   IntrinsicInst *InitTrampoline = nullptr;
1392   for (User *U : TrampMem->users()) {
1393     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
1394     if (!II)
1395       return nullptr;
1396     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
1397       if (InitTrampoline)
1398         // More than one init_trampoline writes to this value.  Give up.
1399         return nullptr;
1400       InitTrampoline = II;
1401       continue;
1402     }
1403     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
1404       // Allow any number of calls to adjust.trampoline.
1405       continue;
1406     return nullptr;
1407   }
1408
1409   // No call to init.trampoline found.
1410   if (!InitTrampoline)
1411     return nullptr;
1412
1413   // Check that the alloca is being used in the expected way.
1414   if (InitTrampoline->getOperand(0) != TrampMem)
1415     return nullptr;
1416
1417   return InitTrampoline;
1418 }
1419
1420 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
1421                                                Value *TrampMem) {
1422   // Visit all the previous instructions in the basic block, and try to find a
1423   // init.trampoline which has a direct path to the adjust.trampoline.
1424   for (BasicBlock::iterator I = AdjustTramp,
1425        E = AdjustTramp->getParent()->begin(); I != E; ) {
1426     Instruction *Inst = --I;
1427     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1428       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
1429           II->getOperand(0) == TrampMem)
1430         return II;
1431     if (Inst->mayWriteToMemory())
1432       return nullptr;
1433   }
1434   return nullptr;
1435 }
1436
1437 // Given a call to llvm.adjust.trampoline, find and return the corresponding
1438 // call to llvm.init.trampoline if the call to the trampoline can be optimized
1439 // to a direct call to a function.  Otherwise return NULL.
1440 //
1441 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
1442   Callee = Callee->stripPointerCasts();
1443   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
1444   if (!AdjustTramp ||
1445       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
1446     return nullptr;
1447
1448   Value *TrampMem = AdjustTramp->getOperand(0);
1449
1450   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
1451     return IT;
1452   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
1453     return IT;
1454   return nullptr;
1455 }
1456
1457 // visitCallSite - Improvements for call and invoke instructions.
1458 //
1459 Instruction *InstCombiner::visitCallSite(CallSite CS) {
1460
1461   if (isAllocLikeFn(CS.getInstruction(), TLI))
1462     return visitAllocSite(*CS.getInstruction());
1463
1464   bool Changed = false;
1465
1466   // Mark any parameters that are known to be non-null with the nonnull
1467   // attribute.  This is helpful for inlining calls to functions with null
1468   // checks on their arguments.
1469   unsigned ArgNo = 0;
1470   for (Value *V : CS.args()) {
1471     if (!CS.paramHasAttr(ArgNo+1, Attribute::NonNull) &&
1472         isKnownNonNull(V)) {
1473       AttributeSet AS = CS.getAttributes();
1474       AS = AS.addAttribute(CS.getInstruction()->getContext(), ArgNo+1,
1475                            Attribute::NonNull);
1476       CS.setAttributes(AS);
1477       Changed = true;
1478     }
1479     ArgNo++;
1480   }
1481   assert(ArgNo == CS.arg_size() && "sanity check");
1482
1483   // If the callee is a pointer to a function, attempt to move any casts to the
1484   // arguments of the call/invoke.
1485   Value *Callee = CS.getCalledValue();
1486   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
1487     return nullptr;
1488
1489   if (Function *CalleeF = dyn_cast<Function>(Callee))
1490     // If the call and callee calling conventions don't match, this call must
1491     // be unreachable, as the call is undefined.
1492     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
1493         // Only do this for calls to a function with a body.  A prototype may
1494         // not actually end up matching the implementation's calling conv for a
1495         // variety of reasons (e.g. it may be written in assembly).
1496         !CalleeF->isDeclaration()) {
1497       Instruction *OldCall = CS.getInstruction();
1498       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
1499                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
1500                                   OldCall);
1501       // If OldCall does not return void then replaceAllUsesWith undef.
1502       // This allows ValueHandlers and custom metadata to adjust itself.
1503       if (!OldCall->getType()->isVoidTy())
1504         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
1505       if (isa<CallInst>(OldCall))
1506         return EraseInstFromFunction(*OldCall);
1507
1508       // We cannot remove an invoke, because it would change the CFG, just
1509       // change the callee to a null pointer.
1510       cast<InvokeInst>(OldCall)->setCalledFunction(
1511                                     Constant::getNullValue(CalleeF->getType()));
1512       return nullptr;
1513     }
1514
1515   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
1516     // If CS does not return void then replaceAllUsesWith undef.
1517     // This allows ValueHandlers and custom metadata to adjust itself.
1518     if (!CS.getInstruction()->getType()->isVoidTy())
1519       ReplaceInstUsesWith(*CS.getInstruction(),
1520                           UndefValue::get(CS.getInstruction()->getType()));
1521
1522     if (isa<InvokeInst>(CS.getInstruction())) {
1523       // Can't remove an invoke because we cannot change the CFG.
1524       return nullptr;
1525     }
1526
1527     // This instruction is not reachable, just remove it.  We insert a store to
1528     // undef so that we know that this code is not reachable, despite the fact
1529     // that we can't modify the CFG here.
1530     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
1531                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
1532                   CS.getInstruction());
1533
1534     return EraseInstFromFunction(*CS.getInstruction());
1535   }
1536
1537   if (IntrinsicInst *II = FindInitTrampoline(Callee))
1538     return transformCallThroughTrampoline(CS, II);
1539
1540   PointerType *PTy = cast<PointerType>(Callee->getType());
1541   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1542   if (FTy->isVarArg()) {
1543     int ix = FTy->getNumParams();
1544     // See if we can optimize any arguments passed through the varargs area of
1545     // the call.
1546     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
1547            E = CS.arg_end(); I != E; ++I, ++ix) {
1548       CastInst *CI = dyn_cast<CastInst>(*I);
1549       if (CI && isSafeToEliminateVarargsCast(CS, DL, CI, ix)) {
1550         *I = CI->getOperand(0);
1551         Changed = true;
1552       }
1553     }
1554   }
1555
1556   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
1557     // Inline asm calls cannot throw - mark them 'nounwind'.
1558     CS.setDoesNotThrow();
1559     Changed = true;
1560   }
1561
1562   // Try to optimize the call if possible, we require DataLayout for most of
1563   // this.  None of these calls are seen as possibly dead so go ahead and
1564   // delete the instruction now.
1565   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
1566     Instruction *I = tryOptimizeCall(CI);
1567     // If we changed something return the result, etc. Otherwise let
1568     // the fallthrough check.
1569     if (I) return EraseInstFromFunction(*I);
1570   }
1571
1572   return Changed ? CS.getInstruction() : nullptr;
1573 }
1574
1575 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1576 // attempt to move the cast to the arguments of the call/invoke.
1577 //
1578 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1579   Function *Callee =
1580     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
1581   if (!Callee)
1582     return false;
1583   // The prototype of thunks are a lie, don't try to directly call such
1584   // functions.
1585   if (Callee->hasFnAttribute("thunk"))
1586     return false;
1587   Instruction *Caller = CS.getInstruction();
1588   const AttributeSet &CallerPAL = CS.getAttributes();
1589
1590   // Okay, this is a cast from a function to a different type.  Unless doing so
1591   // would cause a type conversion of one of our arguments, change this call to
1592   // be a direct call with arguments casted to the appropriate types.
1593   //
1594   FunctionType *FT = Callee->getFunctionType();
1595   Type *OldRetTy = Caller->getType();
1596   Type *NewRetTy = FT->getReturnType();
1597
1598   // Check to see if we are changing the return type...
1599   if (OldRetTy != NewRetTy) {
1600
1601     if (NewRetTy->isStructTy())
1602       return false; // TODO: Handle multiple return values.
1603
1604     if (!CastInst::isBitOrNoopPointerCastable(NewRetTy, OldRetTy, DL)) {
1605       if (Callee->isDeclaration())
1606         return false;   // Cannot transform this return value.
1607
1608       if (!Caller->use_empty() &&
1609           // void -> non-void is handled specially
1610           !NewRetTy->isVoidTy())
1611         return false;   // Cannot transform this return value.
1612     }
1613
1614     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
1615       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1616       if (RAttrs.overlaps(AttributeFuncs::typeIncompatible(NewRetTy)))
1617         return false;   // Attribute not compatible with transformed value.
1618     }
1619
1620     // If the callsite is an invoke instruction, and the return value is used by
1621     // a PHI node in a successor, we cannot change the return type of the call
1622     // because there is no place to put the cast instruction (without breaking
1623     // the critical edge).  Bail out in this case.
1624     if (!Caller->use_empty())
1625       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1626         for (User *U : II->users())
1627           if (PHINode *PN = dyn_cast<PHINode>(U))
1628             if (PN->getParent() == II->getNormalDest() ||
1629                 PN->getParent() == II->getUnwindDest())
1630               return false;
1631   }
1632
1633   unsigned NumActualArgs = CS.arg_size();
1634   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1635
1636   // Prevent us turning:
1637   // declare void @takes_i32_inalloca(i32* inalloca)
1638   //  call void bitcast (void (i32*)* @takes_i32_inalloca to void (i32)*)(i32 0)
1639   //
1640   // into:
1641   //  call void @takes_i32_inalloca(i32* null)
1642   //
1643   //  Similarly, avoid folding away bitcasts of byval calls.
1644   if (Callee->getAttributes().hasAttrSomewhere(Attribute::InAlloca) ||
1645       Callee->getAttributes().hasAttrSomewhere(Attribute::ByVal))
1646     return false;
1647
1648   CallSite::arg_iterator AI = CS.arg_begin();
1649   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1650     Type *ParamTy = FT->getParamType(i);
1651     Type *ActTy = (*AI)->getType();
1652
1653     if (!CastInst::isBitOrNoopPointerCastable(ActTy, ParamTy, DL))
1654       return false;   // Cannot transform this parameter value.
1655
1656     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
1657           overlaps(AttributeFuncs::typeIncompatible(ParamTy)))
1658       return false;   // Attribute not compatible with transformed value.
1659
1660     if (CS.isInAllocaArgument(i))
1661       return false;   // Cannot transform to and from inalloca.
1662
1663     // If the parameter is passed as a byval argument, then we have to have a
1664     // sized type and the sized type has to have the same size as the old type.
1665     if (ParamTy != ActTy &&
1666         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
1667                                                          Attribute::ByVal)) {
1668       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
1669       if (!ParamPTy || !ParamPTy->getElementType()->isSized())
1670         return false;
1671
1672       Type *CurElTy = ActTy->getPointerElementType();
1673       if (DL.getTypeAllocSize(CurElTy) !=
1674           DL.getTypeAllocSize(ParamPTy->getElementType()))
1675         return false;
1676     }
1677   }
1678
1679   if (Callee->isDeclaration()) {
1680     // Do not delete arguments unless we have a function body.
1681     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1682       return false;
1683
1684     // If the callee is just a declaration, don't change the varargsness of the
1685     // call.  We don't want to introduce a varargs call where one doesn't
1686     // already exist.
1687     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
1688     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1689       return false;
1690
1691     // If both the callee and the cast type are varargs, we still have to make
1692     // sure the number of fixed parameters are the same or we have the same
1693     // ABI issues as if we introduce a varargs call.
1694     if (FT->isVarArg() &&
1695         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1696         FT->getNumParams() !=
1697         cast<FunctionType>(APTy->getElementType())->getNumParams())
1698       return false;
1699   }
1700
1701   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1702       !CallerPAL.isEmpty())
1703     // In this case we have more arguments than the new function type, but we
1704     // won't be dropping them.  Check that these extra arguments have attributes
1705     // that are compatible with being a vararg call argument.
1706     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1707       unsigned Index = CallerPAL.getSlotIndex(i - 1);
1708       if (Index <= FT->getNumParams())
1709         break;
1710
1711       // Check if it has an attribute that's incompatible with varargs.
1712       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
1713       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
1714         return false;
1715     }
1716
1717
1718   // Okay, we decided that this is a safe thing to do: go ahead and start
1719   // inserting cast instructions as necessary.
1720   std::vector<Value*> Args;
1721   Args.reserve(NumActualArgs);
1722   SmallVector<AttributeSet, 8> attrVec;
1723   attrVec.reserve(NumCommonArgs);
1724
1725   // Get any return attributes.
1726   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1727
1728   // If the return value is not being used, the type may not be compatible
1729   // with the existing attributes.  Wipe out any problematic attributes.
1730   RAttrs.remove(AttributeFuncs::typeIncompatible(NewRetTy));
1731
1732   // Add the new return attributes.
1733   if (RAttrs.hasAttributes())
1734     attrVec.push_back(AttributeSet::get(Caller->getContext(),
1735                                         AttributeSet::ReturnIndex, RAttrs));
1736
1737   AI = CS.arg_begin();
1738   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1739     Type *ParamTy = FT->getParamType(i);
1740
1741     if ((*AI)->getType() == ParamTy) {
1742       Args.push_back(*AI);
1743     } else {
1744       Args.push_back(Builder->CreateBitOrPointerCast(*AI, ParamTy));
1745     }
1746
1747     // Add any parameter attributes.
1748     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1749     if (PAttrs.hasAttributes())
1750       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
1751                                           PAttrs));
1752   }
1753
1754   // If the function takes more arguments than the call was taking, add them
1755   // now.
1756   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1757     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1758
1759   // If we are removing arguments to the function, emit an obnoxious warning.
1760   if (FT->getNumParams() < NumActualArgs) {
1761     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
1762     if (FT->isVarArg()) {
1763       // Add all of the arguments in their promoted form to the arg list.
1764       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1765         Type *PTy = getPromotedType((*AI)->getType());
1766         if (PTy != (*AI)->getType()) {
1767           // Must promote to pass through va_arg area!
1768           Instruction::CastOps opcode =
1769             CastInst::getCastOpcode(*AI, false, PTy, false);
1770           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
1771         } else {
1772           Args.push_back(*AI);
1773         }
1774
1775         // Add any parameter attributes.
1776         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1777         if (PAttrs.hasAttributes())
1778           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
1779                                               PAttrs));
1780       }
1781     }
1782   }
1783
1784   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
1785   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
1786     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
1787
1788   if (NewRetTy->isVoidTy())
1789     Caller->setName("");   // Void type should not have a name.
1790
1791   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
1792                                                        attrVec);
1793
1794   Instruction *NC;
1795   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1796     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1797                                II->getUnwindDest(), Args);
1798     NC->takeName(II);
1799     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1800     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1801   } else {
1802     CallInst *CI = cast<CallInst>(Caller);
1803     NC = Builder->CreateCall(Callee, Args);
1804     NC->takeName(CI);
1805     if (CI->isTailCall())
1806       cast<CallInst>(NC)->setTailCall();
1807     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1808     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1809   }
1810
1811   // Insert a cast of the return type as necessary.
1812   Value *NV = NC;
1813   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1814     if (!NV->getType()->isVoidTy()) {
1815       NV = NC = CastInst::CreateBitOrPointerCast(NC, OldRetTy);
1816       NC->setDebugLoc(Caller->getDebugLoc());
1817
1818       // If this is an invoke instruction, we should insert it after the first
1819       // non-phi, instruction in the normal successor block.
1820       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1821         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
1822         InsertNewInstBefore(NC, *I);
1823       } else {
1824         // Otherwise, it's a call, just insert cast right after the call.
1825         InsertNewInstBefore(NC, *Caller);
1826       }
1827       Worklist.AddUsersToWorkList(*Caller);
1828     } else {
1829       NV = UndefValue::get(Caller->getType());
1830     }
1831   }
1832
1833   if (!Caller->use_empty())
1834     ReplaceInstUsesWith(*Caller, NV);
1835   else if (Caller->hasValueHandle()) {
1836     if (OldRetTy == NV->getType())
1837       ValueHandleBase::ValueIsRAUWd(Caller, NV);
1838     else
1839       // We cannot call ValueIsRAUWd with a different type, and the
1840       // actual tracked value will disappear.
1841       ValueHandleBase::ValueIsDeleted(Caller);
1842   }
1843
1844   EraseInstFromFunction(*Caller);
1845   return true;
1846 }
1847
1848 // transformCallThroughTrampoline - Turn a call to a function created by
1849 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1850 // underlying function.
1851 //
1852 Instruction *
1853 InstCombiner::transformCallThroughTrampoline(CallSite CS,
1854                                              IntrinsicInst *Tramp) {
1855   Value *Callee = CS.getCalledValue();
1856   PointerType *PTy = cast<PointerType>(Callee->getType());
1857   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1858   const AttributeSet &Attrs = CS.getAttributes();
1859
1860   // If the call already has the 'nest' attribute somewhere then give up -
1861   // otherwise 'nest' would occur twice after splicing in the chain.
1862   if (Attrs.hasAttrSomewhere(Attribute::Nest))
1863     return nullptr;
1864
1865   assert(Tramp &&
1866          "transformCallThroughTrampoline called with incorrect CallSite.");
1867
1868   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
1869   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1870   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1871
1872   const AttributeSet &NestAttrs = NestF->getAttributes();
1873   if (!NestAttrs.isEmpty()) {
1874     unsigned NestIdx = 1;
1875     Type *NestTy = nullptr;
1876     AttributeSet NestAttr;
1877
1878     // Look for a parameter marked with the 'nest' attribute.
1879     for (FunctionType::param_iterator I = NestFTy->param_begin(),
1880          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1881       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
1882         // Record the parameter type and any other attributes.
1883         NestTy = *I;
1884         NestAttr = NestAttrs.getParamAttributes(NestIdx);
1885         break;
1886       }
1887
1888     if (NestTy) {
1889       Instruction *Caller = CS.getInstruction();
1890       std::vector<Value*> NewArgs;
1891       NewArgs.reserve(CS.arg_size() + 1);
1892
1893       SmallVector<AttributeSet, 8> NewAttrs;
1894       NewAttrs.reserve(Attrs.getNumSlots() + 1);
1895
1896       // Insert the nest argument into the call argument list, which may
1897       // mean appending it.  Likewise for attributes.
1898
1899       // Add any result attributes.
1900       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1901         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1902                                              Attrs.getRetAttributes()));
1903
1904       {
1905         unsigned Idx = 1;
1906         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1907         do {
1908           if (Idx == NestIdx) {
1909             // Add the chain argument and attributes.
1910             Value *NestVal = Tramp->getArgOperand(2);
1911             if (NestVal->getType() != NestTy)
1912               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
1913             NewArgs.push_back(NestVal);
1914             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1915                                                  NestAttr));
1916           }
1917
1918           if (I == E)
1919             break;
1920
1921           // Add the original argument and attributes.
1922           NewArgs.push_back(*I);
1923           AttributeSet Attr = Attrs.getParamAttributes(Idx);
1924           if (Attr.hasAttributes(Idx)) {
1925             AttrBuilder B(Attr, Idx);
1926             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1927                                                  Idx + (Idx >= NestIdx), B));
1928           }
1929
1930           ++Idx, ++I;
1931         } while (1);
1932       }
1933
1934       // Add any function attributes.
1935       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1936         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
1937                                              Attrs.getFnAttributes()));
1938
1939       // The trampoline may have been bitcast to a bogus type (FTy).
1940       // Handle this by synthesizing a new function type, equal to FTy
1941       // with the chain parameter inserted.
1942
1943       std::vector<Type*> NewTypes;
1944       NewTypes.reserve(FTy->getNumParams()+1);
1945
1946       // Insert the chain's type into the list of parameter types, which may
1947       // mean appending it.
1948       {
1949         unsigned Idx = 1;
1950         FunctionType::param_iterator I = FTy->param_begin(),
1951           E = FTy->param_end();
1952
1953         do {
1954           if (Idx == NestIdx)
1955             // Add the chain's type.
1956             NewTypes.push_back(NestTy);
1957
1958           if (I == E)
1959             break;
1960
1961           // Add the original type.
1962           NewTypes.push_back(*I);
1963
1964           ++Idx, ++I;
1965         } while (1);
1966       }
1967
1968       // Replace the trampoline call with a direct call.  Let the generic
1969       // code sort out any function type mismatches.
1970       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1971                                                 FTy->isVarArg());
1972       Constant *NewCallee =
1973         NestF->getType() == PointerType::getUnqual(NewFTy) ?
1974         NestF : ConstantExpr::getBitCast(NestF,
1975                                          PointerType::getUnqual(NewFTy));
1976       const AttributeSet &NewPAL =
1977           AttributeSet::get(FTy->getContext(), NewAttrs);
1978
1979       Instruction *NewCaller;
1980       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1981         NewCaller = InvokeInst::Create(NewCallee,
1982                                        II->getNormalDest(), II->getUnwindDest(),
1983                                        NewArgs);
1984         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1985         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1986       } else {
1987         NewCaller = CallInst::Create(NewCallee, NewArgs);
1988         if (cast<CallInst>(Caller)->isTailCall())
1989           cast<CallInst>(NewCaller)->setTailCall();
1990         cast<CallInst>(NewCaller)->
1991           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1992         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1993       }
1994
1995       return NewCaller;
1996     }
1997   }
1998
1999   // Replace the trampoline call with a direct call.  Since there is no 'nest'
2000   // parameter, there is no need to adjust the argument list.  Let the generic
2001   // code sort out any function type mismatches.
2002   Constant *NewCallee =
2003     NestF->getType() == PTy ? NestF :
2004                               ConstantExpr::getBitCast(NestF, PTy);
2005   CS.setCalledFunction(NewCallee);
2006   return CS.getInstruction();
2007 }