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