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