Simplify a vpermil* with constant mask.
[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 #define DEBUG_TYPE "instcombine"
15 #include "InstCombine.h"
16 #include "llvm/ADT/Statistic.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/IR/CallSite.h"
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/IR/PatternMatch.h"
21 #include "llvm/Transforms/Utils/BuildLibCalls.h"
22 #include "llvm/Transforms/Utils/Local.h"
23 using namespace llvm;
24 using namespace PatternMatch;
25
26 STATISTIC(NumSimplified, "Number of library calls simplified");
27
28 /// getPromotedType - Return the specified type promoted as it would be to pass
29 /// though a va_arg area.
30 static Type *getPromotedType(Type *Ty) {
31   if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
32     if (ITy->getBitWidth() < 32)
33       return Type::getInt32Ty(Ty->getContext());
34   }
35   return Ty;
36 }
37
38 /// reduceToSingleValueType - Given an aggregate type which ultimately holds a
39 /// single scalar element, like {{{type}}} or [1 x type], return type.
40 static Type *reduceToSingleValueType(Type *T) {
41   while (!T->isSingleValueType()) {
42     if (StructType *STy = dyn_cast<StructType>(T)) {
43       if (STy->getNumElements() == 1)
44         T = STy->getElementType(0);
45       else
46         break;
47     } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
48       if (ATy->getNumElements() == 1)
49         T = ATy->getElementType();
50       else
51         break;
52     } else
53       break;
54   }
55
56   return T;
57 }
58
59 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
60   unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), DL);
61   unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), DL);
62   unsigned MinAlign = std::min(DstAlign, SrcAlign);
63   unsigned CopyAlign = MI->getAlignment();
64
65   if (CopyAlign < MinAlign) {
66     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
67                                              MinAlign, false));
68     return MI;
69   }
70
71   // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
72   // load/store.
73   ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
74   if (MemOpLength == 0) return 0;
75
76   // Source and destination pointer types are always "i8*" for intrinsic.  See
77   // if the size is something we can handle with a single primitive load/store.
78   // A single load+store correctly handles overlapping memory in the memmove
79   // case.
80   uint64_t Size = MemOpLength->getLimitedValue();
81   assert(Size && "0-sized memory transferring should be removed already.");
82
83   if (Size > 8 || (Size&(Size-1)))
84     return 0;  // If not 1/2/4/8 bytes, exit.
85
86   // Use an integer load+store unless we can find something better.
87   unsigned SrcAddrSp =
88     cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
89   unsigned DstAddrSp =
90     cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
91
92   IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
93   Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
94   Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
95
96   // Memcpy forces the use of i8* for the source and destination.  That means
97   // that if you're using memcpy to move one double around, you'll get a cast
98   // from double* to i8*.  We'd much rather use a double load+store rather than
99   // an i64 load+store, here because this improves the odds that the source or
100   // dest address will be promotable.  See if we can find a better type than the
101   // integer datatype.
102   Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
103   MDNode *CopyMD = 0;
104   if (StrippedDest != MI->getArgOperand(0)) {
105     Type *SrcETy = cast<PointerType>(StrippedDest->getType())
106                                     ->getElementType();
107     if (DL && SrcETy->isSized() && DL->getTypeStoreSize(SrcETy) == Size) {
108       // The SrcETy might be something like {{{double}}} or [1 x double].  Rip
109       // down through these levels if so.
110       SrcETy = reduceToSingleValueType(SrcETy);
111
112       if (SrcETy->isSingleValueType()) {
113         NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
114         NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
115
116         // If the memcpy has metadata describing the members, see if we can
117         // get the TBAA tag describing our copy.
118         if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
119           if (M->getNumOperands() == 3 &&
120               M->getOperand(0) &&
121               isa<ConstantInt>(M->getOperand(0)) &&
122               cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
123               M->getOperand(1) &&
124               isa<ConstantInt>(M->getOperand(1)) &&
125               cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
126               M->getOperand(2) &&
127               isa<MDNode>(M->getOperand(2)))
128             CopyMD = cast<MDNode>(M->getOperand(2));
129         }
130       }
131     }
132   }
133
134   // If the memcpy/memmove provides better alignment info than we can
135   // infer, use it.
136   SrcAlign = std::max(SrcAlign, CopyAlign);
137   DstAlign = std::max(DstAlign, CopyAlign);
138
139   Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
140   Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
141   LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
142   L->setAlignment(SrcAlign);
143   if (CopyMD)
144     L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
145   StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
146   S->setAlignment(DstAlign);
147   if (CopyMD)
148     S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
149
150   // Set the size of the copy to 0, it will be deleted on the next iteration.
151   MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
152   return MI;
153 }
154
155 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
156   unsigned Alignment = getKnownAlignment(MI->getDest(), DL);
157   if (MI->getAlignment() < Alignment) {
158     MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
159                                              Alignment, false));
160     return MI;
161   }
162
163   // Extract the length and alignment and fill if they are constant.
164   ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
165   ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
166   if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
167     return 0;
168   uint64_t Len = LenC->getLimitedValue();
169   Alignment = MI->getAlignment();
170   assert(Len && "0-sized memory setting should be removed already.");
171
172   // memset(s,c,n) -> store s, c (for n=1,2,4,8)
173   if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
174     Type *ITy = IntegerType::get(MI->getContext(), Len*8);  // n=1 -> i8.
175
176     Value *Dest = MI->getDest();
177     unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
178     Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
179     Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
180
181     // Alignment 0 is identity for alignment 1 for memset, but not store.
182     if (Alignment == 0) Alignment = 1;
183
184     // Extract the fill value and store.
185     uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
186     StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
187                                         MI->isVolatile());
188     S->setAlignment(Alignment);
189
190     // Set the size of the copy to 0, it will be deleted on the next iteration.
191     MI->setLength(Constant::getNullValue(LenC->getType()));
192     return MI;
193   }
194
195   return 0;
196 }
197
198 /// visitCallInst - CallInst simplification.  This mostly only handles folding
199 /// of intrinsic instructions.  For normal calls, it allows visitCallSite to do
200 /// the heavy lifting.
201 ///
202 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
203   if (isFreeCall(&CI, TLI))
204     return visitFree(CI);
205
206   // If the caller function is nounwind, mark the call as nounwind, even if the
207   // callee isn't.
208   if (CI.getParent()->getParent()->doesNotThrow() &&
209       !CI.doesNotThrow()) {
210     CI.setDoesNotThrow();
211     return &CI;
212   }
213
214   IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
215   if (!II) return visitCallSite(&CI);
216
217   // Intrinsics cannot occur in an invoke, so handle them here instead of in
218   // visitCallSite.
219   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
220     bool Changed = false;
221
222     // memmove/cpy/set of zero bytes is a noop.
223     if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
224       if (NumBytes->isNullValue())
225         return EraseInstFromFunction(CI);
226
227       if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
228         if (CI->getZExtValue() == 1) {
229           // Replace the instruction with just byte operations.  We would
230           // transform other cases to loads/stores, but we don't know if
231           // alignment is sufficient.
232         }
233     }
234
235     // No other transformations apply to volatile transfers.
236     if (MI->isVolatile())
237       return 0;
238
239     // If we have a memmove and the source operation is a constant global,
240     // then the source and dest pointers can't alias, so we can change this
241     // into a call to memcpy.
242     if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
243       if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
244         if (GVSrc->isConstant()) {
245           Module *M = CI.getParent()->getParent()->getParent();
246           Intrinsic::ID MemCpyID = Intrinsic::memcpy;
247           Type *Tys[3] = { CI.getArgOperand(0)->getType(),
248                            CI.getArgOperand(1)->getType(),
249                            CI.getArgOperand(2)->getType() };
250           CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
251           Changed = true;
252         }
253     }
254
255     if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
256       // memmove(x,x,size) -> noop.
257       if (MTI->getSource() == MTI->getDest())
258         return EraseInstFromFunction(CI);
259     }
260
261     // If we can determine a pointer alignment that is bigger than currently
262     // set, update the alignment.
263     if (isa<MemTransferInst>(MI)) {
264       if (Instruction *I = SimplifyMemTransfer(MI))
265         return I;
266     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
267       if (Instruction *I = SimplifyMemSet(MSI))
268         return I;
269     }
270
271     if (Changed) return II;
272   }
273
274   switch (II->getIntrinsicID()) {
275   default: break;
276   case Intrinsic::objectsize: {
277     uint64_t Size;
278     if (getObjectSize(II->getArgOperand(0), Size, DL, TLI))
279       return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
280     return 0;
281   }
282   case Intrinsic::bswap: {
283     Value *IIOperand = II->getArgOperand(0);
284     Value *X = 0;
285
286     // bswap(bswap(x)) -> x
287     if (match(IIOperand, m_BSwap(m_Value(X))))
288         return ReplaceInstUsesWith(CI, X);
289
290     // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
291     if (match(IIOperand, m_Trunc(m_BSwap(m_Value(X))))) {
292       unsigned C = X->getType()->getPrimitiveSizeInBits() -
293         IIOperand->getType()->getPrimitiveSizeInBits();
294       Value *CV = ConstantInt::get(X->getType(), C);
295       Value *V = Builder->CreateLShr(X, CV);
296       return new TruncInst(V, IIOperand->getType());
297     }
298     break;
299   }
300
301   case Intrinsic::powi:
302     if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
303       // powi(x, 0) -> 1.0
304       if (Power->isZero())
305         return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
306       // powi(x, 1) -> x
307       if (Power->isOne())
308         return ReplaceInstUsesWith(CI, II->getArgOperand(0));
309       // powi(x, -1) -> 1/x
310       if (Power->isAllOnesValue())
311         return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
312                                           II->getArgOperand(0));
313     }
314     break;
315   case Intrinsic::cttz: {
316     // If all bits below the first known one are known zero,
317     // this value is constant.
318     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
319     // FIXME: Try to simplify vectors of integers.
320     if (!IT) break;
321     uint32_t BitWidth = IT->getBitWidth();
322     APInt KnownZero(BitWidth, 0);
323     APInt KnownOne(BitWidth, 0);
324     ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
325     unsigned TrailingZeros = KnownOne.countTrailingZeros();
326     APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
327     if ((Mask & KnownZero) == Mask)
328       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
329                                  APInt(BitWidth, TrailingZeros)));
330
331     }
332     break;
333   case Intrinsic::ctlz: {
334     // If all bits above the first known one are known zero,
335     // this value is constant.
336     IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
337     // FIXME: Try to simplify vectors of integers.
338     if (!IT) break;
339     uint32_t BitWidth = IT->getBitWidth();
340     APInt KnownZero(BitWidth, 0);
341     APInt KnownOne(BitWidth, 0);
342     ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
343     unsigned LeadingZeros = KnownOne.countLeadingZeros();
344     APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
345     if ((Mask & KnownZero) == Mask)
346       return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
347                                  APInt(BitWidth, LeadingZeros)));
348
349     }
350     break;
351   case Intrinsic::uadd_with_overflow: {
352     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
353     IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
354     uint32_t BitWidth = IT->getBitWidth();
355     APInt LHSKnownZero(BitWidth, 0);
356     APInt LHSKnownOne(BitWidth, 0);
357     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
358     bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
359     bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
360
361     if (LHSKnownNegative || LHSKnownPositive) {
362       APInt RHSKnownZero(BitWidth, 0);
363       APInt RHSKnownOne(BitWidth, 0);
364       ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
365       bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
366       bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
367       if (LHSKnownNegative && RHSKnownNegative) {
368         // The sign bit is set in both cases: this MUST overflow.
369         // Create a simple add instruction, and insert it into the struct.
370         Value *Add = Builder->CreateAdd(LHS, RHS);
371         Add->takeName(&CI);
372         Constant *V[] = {
373           UndefValue::get(LHS->getType()),
374           ConstantInt::getTrue(II->getContext())
375         };
376         StructType *ST = cast<StructType>(II->getType());
377         Constant *Struct = ConstantStruct::get(ST, V);
378         return InsertValueInst::Create(Struct, Add, 0);
379       }
380
381       if (LHSKnownPositive && RHSKnownPositive) {
382         // The sign bit is clear in both cases: this CANNOT overflow.
383         // Create a simple add instruction, and insert it into the struct.
384         Value *Add = Builder->CreateNUWAdd(LHS, RHS);
385         Add->takeName(&CI);
386         Constant *V[] = {
387           UndefValue::get(LHS->getType()),
388           ConstantInt::getFalse(II->getContext())
389         };
390         StructType *ST = cast<StructType>(II->getType());
391         Constant *Struct = ConstantStruct::get(ST, V);
392         return InsertValueInst::Create(Struct, Add, 0);
393       }
394     }
395   }
396   // FALL THROUGH uadd into sadd
397   case Intrinsic::sadd_with_overflow:
398     // Canonicalize constants into the RHS.
399     if (isa<Constant>(II->getArgOperand(0)) &&
400         !isa<Constant>(II->getArgOperand(1))) {
401       Value *LHS = II->getArgOperand(0);
402       II->setArgOperand(0, II->getArgOperand(1));
403       II->setArgOperand(1, LHS);
404       return II;
405     }
406
407     // X + undef -> undef
408     if (isa<UndefValue>(II->getArgOperand(1)))
409       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
410
411     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
412       // X + 0 -> {X, false}
413       if (RHS->isZero()) {
414         Constant *V[] = {
415           UndefValue::get(II->getArgOperand(0)->getType()),
416           ConstantInt::getFalse(II->getContext())
417         };
418         Constant *Struct =
419           ConstantStruct::get(cast<StructType>(II->getType()), V);
420         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
421       }
422     }
423     break;
424   case Intrinsic::usub_with_overflow:
425   case Intrinsic::ssub_with_overflow:
426     // undef - X -> undef
427     // X - undef -> undef
428     if (isa<UndefValue>(II->getArgOperand(0)) ||
429         isa<UndefValue>(II->getArgOperand(1)))
430       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
431
432     if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
433       // X - 0 -> {X, false}
434       if (RHS->isZero()) {
435         Constant *V[] = {
436           UndefValue::get(II->getArgOperand(0)->getType()),
437           ConstantInt::getFalse(II->getContext())
438         };
439         Constant *Struct =
440           ConstantStruct::get(cast<StructType>(II->getType()), V);
441         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
442       }
443     }
444     break;
445   case Intrinsic::umul_with_overflow: {
446     Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
447     unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
448
449     APInt LHSKnownZero(BitWidth, 0);
450     APInt LHSKnownOne(BitWidth, 0);
451     ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
452     APInt RHSKnownZero(BitWidth, 0);
453     APInt RHSKnownOne(BitWidth, 0);
454     ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
455
456     // Get the largest possible values for each operand.
457     APInt LHSMax = ~LHSKnownZero;
458     APInt RHSMax = ~RHSKnownZero;
459
460     // If multiplying the maximum values does not overflow then we can turn
461     // this into a plain NUW mul.
462     bool Overflow;
463     LHSMax.umul_ov(RHSMax, Overflow);
464     if (!Overflow) {
465       Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
466       Constant *V[] = {
467         UndefValue::get(LHS->getType()),
468         Builder->getFalse()
469       };
470       Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
471       return InsertValueInst::Create(Struct, Mul, 0);
472     }
473   } // FALL THROUGH
474   case Intrinsic::smul_with_overflow:
475     // Canonicalize constants into the RHS.
476     if (isa<Constant>(II->getArgOperand(0)) &&
477         !isa<Constant>(II->getArgOperand(1))) {
478       Value *LHS = II->getArgOperand(0);
479       II->setArgOperand(0, II->getArgOperand(1));
480       II->setArgOperand(1, LHS);
481       return II;
482     }
483
484     // X * undef -> undef
485     if (isa<UndefValue>(II->getArgOperand(1)))
486       return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
487
488     if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
489       // X*0 -> {0, false}
490       if (RHSI->isZero())
491         return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
492
493       // X * 1 -> {X, false}
494       if (RHSI->equalsInt(1)) {
495         Constant *V[] = {
496           UndefValue::get(II->getArgOperand(0)->getType()),
497           ConstantInt::getFalse(II->getContext())
498         };
499         Constant *Struct =
500           ConstantStruct::get(cast<StructType>(II->getType()), V);
501         return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
502       }
503     }
504     break;
505   case Intrinsic::ppc_altivec_lvx:
506   case Intrinsic::ppc_altivec_lvxl:
507     // Turn PPC lvx -> load if the pointer is known aligned.
508     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
509       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
510                                          PointerType::getUnqual(II->getType()));
511       return new LoadInst(Ptr);
512     }
513     break;
514   case Intrinsic::ppc_altivec_stvx:
515   case Intrinsic::ppc_altivec_stvxl:
516     // Turn stvx -> store if the pointer is known aligned.
517     if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, DL) >= 16) {
518       Type *OpPtrTy =
519         PointerType::getUnqual(II->getArgOperand(0)->getType());
520       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
521       return new StoreInst(II->getArgOperand(0), Ptr);
522     }
523     break;
524   case Intrinsic::x86_sse_storeu_ps:
525   case Intrinsic::x86_sse2_storeu_pd:
526   case Intrinsic::x86_sse2_storeu_dq:
527     // Turn X86 storeu -> store if the pointer is known aligned.
528     if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, DL) >= 16) {
529       Type *OpPtrTy =
530         PointerType::getUnqual(II->getArgOperand(1)->getType());
531       Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
532       return new StoreInst(II->getArgOperand(1), Ptr);
533     }
534     break;
535
536   case Intrinsic::x86_sse_cvtss2si:
537   case Intrinsic::x86_sse_cvtss2si64:
538   case Intrinsic::x86_sse_cvttss2si:
539   case Intrinsic::x86_sse_cvttss2si64:
540   case Intrinsic::x86_sse2_cvtsd2si:
541   case Intrinsic::x86_sse2_cvtsd2si64:
542   case Intrinsic::x86_sse2_cvttsd2si:
543   case Intrinsic::x86_sse2_cvttsd2si64: {
544     // These intrinsics only demand the 0th element of their input vectors. If
545     // we can simplify the input based on that, do so now.
546     unsigned VWidth =
547       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
548     APInt DemandedElts(VWidth, 1);
549     APInt UndefElts(VWidth, 0);
550     if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
551                                               DemandedElts, UndefElts)) {
552       II->setArgOperand(0, V);
553       return II;
554     }
555     break;
556   }
557
558
559   case Intrinsic::x86_sse41_pmovsxbw:
560   case Intrinsic::x86_sse41_pmovsxwd:
561   case Intrinsic::x86_sse41_pmovsxdq:
562   case Intrinsic::x86_sse41_pmovzxbw:
563   case Intrinsic::x86_sse41_pmovzxwd:
564   case Intrinsic::x86_sse41_pmovzxdq: {
565     // pmov{s|z}x ignores the upper half of their input vectors.
566     unsigned VWidth =
567       cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
568     unsigned LowHalfElts = VWidth / 2;
569     APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
570     APInt UndefElts(VWidth, 0);
571     if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
572                                                  InputDemandedElts,
573                                                  UndefElts)) {
574       II->setArgOperand(0, TmpV);
575       return II;
576     }
577     break;
578   }
579
580   case Intrinsic::x86_avx_vpermilvar_ps:
581   case Intrinsic::x86_avx_vpermilvar_ps_256:
582   case Intrinsic::x86_avx_vpermilvar_pd:
583   case Intrinsic::x86_avx_vpermilvar_pd_256: {
584     // Convert vpermil* to shufflevector if the mask is constant.
585     Value *V = II->getArgOperand(1);
586     if (auto C = dyn_cast<ConstantDataVector>(V)) {
587       auto V1 = II->getArgOperand(0);
588       auto V2 = UndefValue::get(V1->getType());
589       auto Shuffle = Builder->CreateShuffleVector(V1, V2, C);
590       return ReplaceInstUsesWith(CI, Shuffle);
591     }
592     break;
593   }
594
595   case Intrinsic::ppc_altivec_vperm:
596     // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
597     if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
598       assert(Mask->getType()->getVectorNumElements() == 16 &&
599              "Bad type for intrinsic!");
600
601       // Check that all of the elements are integer constants or undefs.
602       bool AllEltsOk = true;
603       for (unsigned i = 0; i != 16; ++i) {
604         Constant *Elt = Mask->getAggregateElement(i);
605         if (Elt == 0 ||
606             !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
607           AllEltsOk = false;
608           break;
609         }
610       }
611
612       if (AllEltsOk) {
613         // Cast the input vectors to byte vectors.
614         Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
615                                             Mask->getType());
616         Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
617                                             Mask->getType());
618         Value *Result = UndefValue::get(Op0->getType());
619
620         // Only extract each element once.
621         Value *ExtractedElts[32];
622         memset(ExtractedElts, 0, sizeof(ExtractedElts));
623
624         for (unsigned i = 0; i != 16; ++i) {
625           if (isa<UndefValue>(Mask->getAggregateElement(i)))
626             continue;
627           unsigned Idx =
628             cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
629           Idx &= 31;  // Match the hardware behavior.
630
631           if (ExtractedElts[Idx] == 0) {
632             ExtractedElts[Idx] =
633               Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
634                                             Builder->getInt32(Idx&15));
635           }
636
637           // Insert this value into the result vector.
638           Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
639                                                 Builder->getInt32(i));
640         }
641         return CastInst::Create(Instruction::BitCast, Result, CI.getType());
642       }
643     }
644     break;
645
646   case Intrinsic::arm_neon_vld1:
647   case Intrinsic::arm_neon_vld2:
648   case Intrinsic::arm_neon_vld3:
649   case Intrinsic::arm_neon_vld4:
650   case Intrinsic::arm_neon_vld2lane:
651   case Intrinsic::arm_neon_vld3lane:
652   case Intrinsic::arm_neon_vld4lane:
653   case Intrinsic::arm_neon_vst1:
654   case Intrinsic::arm_neon_vst2:
655   case Intrinsic::arm_neon_vst3:
656   case Intrinsic::arm_neon_vst4:
657   case Intrinsic::arm_neon_vst2lane:
658   case Intrinsic::arm_neon_vst3lane:
659   case Intrinsic::arm_neon_vst4lane: {
660     unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), DL);
661     unsigned AlignArg = II->getNumArgOperands() - 1;
662     ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
663     if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
664       II->setArgOperand(AlignArg,
665                         ConstantInt::get(Type::getInt32Ty(II->getContext()),
666                                          MemAlign, false));
667       return II;
668     }
669     break;
670   }
671
672   case Intrinsic::arm_neon_vmulls:
673   case Intrinsic::arm_neon_vmullu:
674   case Intrinsic::arm64_neon_smull:
675   case Intrinsic::arm64_neon_umull: {
676     Value *Arg0 = II->getArgOperand(0);
677     Value *Arg1 = II->getArgOperand(1);
678
679     // Handle mul by zero first:
680     if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
681       return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
682     }
683
684     // Check for constant LHS & RHS - in this case we just simplify.
685     bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu ||
686                  II->getIntrinsicID() == Intrinsic::arm64_neon_umull);
687     VectorType *NewVT = cast<VectorType>(II->getType());
688     if (Constant *CV0 = dyn_cast<Constant>(Arg0)) {
689       if (Constant *CV1 = dyn_cast<Constant>(Arg1)) {
690         CV0 = ConstantExpr::getIntegerCast(CV0, NewVT, /*isSigned=*/!Zext);
691         CV1 = ConstantExpr::getIntegerCast(CV1, NewVT, /*isSigned=*/!Zext);
692
693         return ReplaceInstUsesWith(CI, ConstantExpr::getMul(CV0, CV1));
694       }
695
696       // Couldn't simplify - canonicalize constant to the RHS.
697       std::swap(Arg0, Arg1);
698     }
699
700     // Handle mul by one:
701     if (Constant *CV1 = dyn_cast<Constant>(Arg1))
702       if (ConstantInt *Splat =
703               dyn_cast_or_null<ConstantInt>(CV1->getSplatValue()))
704         if (Splat->isOne())
705           return CastInst::CreateIntegerCast(Arg0, II->getType(),
706                                              /*isSigned=*/!Zext);
707
708     break;
709   }
710
711   case Intrinsic::stackrestore: {
712     // If the save is right next to the restore, remove the restore.  This can
713     // happen when variable allocas are DCE'd.
714     if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
715       if (SS->getIntrinsicID() == Intrinsic::stacksave) {
716         BasicBlock::iterator BI = SS;
717         if (&*++BI == II)
718           return EraseInstFromFunction(CI);
719       }
720     }
721
722     // Scan down this block to see if there is another stack restore in the
723     // same block without an intervening call/alloca.
724     BasicBlock::iterator BI = II;
725     TerminatorInst *TI = II->getParent()->getTerminator();
726     bool CannotRemove = false;
727     for (++BI; &*BI != TI; ++BI) {
728       if (isa<AllocaInst>(BI)) {
729         CannotRemove = true;
730         break;
731       }
732       if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
733         if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
734           // If there is a stackrestore below this one, remove this one.
735           if (II->getIntrinsicID() == Intrinsic::stackrestore)
736             return EraseInstFromFunction(CI);
737           // Otherwise, ignore the intrinsic.
738         } else {
739           // If we found a non-intrinsic call, we can't remove the stack
740           // restore.
741           CannotRemove = true;
742           break;
743         }
744       }
745     }
746
747     // If the stack restore is in a return, resume, or unwind block and if there
748     // are no allocas or calls between the restore and the return, nuke the
749     // restore.
750     if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
751       return EraseInstFromFunction(CI);
752     break;
753   }
754   }
755
756   return visitCallSite(II);
757 }
758
759 // InvokeInst simplification
760 //
761 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
762   return visitCallSite(&II);
763 }
764
765 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
766 /// passed through the varargs area, we can eliminate the use of the cast.
767 static bool isSafeToEliminateVarargsCast(const CallSite CS,
768                                          const CastInst * const CI,
769                                          const DataLayout * const DL,
770                                          const int ix) {
771   if (!CI->isLosslessCast())
772     return false;
773
774   // The size of ByVal or InAlloca arguments is derived from the type, so we
775   // can't change to a type with a different size.  If the size were
776   // passed explicitly we could avoid this check.
777   if (!CS.isByValOrInAllocaArgument(ix))
778     return true;
779
780   Type* SrcTy =
781             cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
782   Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
783   if (!SrcTy->isSized() || !DstTy->isSized())
784     return false;
785   if (!DL || DL->getTypeAllocSize(SrcTy) != DL->getTypeAllocSize(DstTy))
786     return false;
787   return true;
788 }
789
790 // Try to fold some different type of calls here.
791 // Currently we're only working with the checking functions, memcpy_chk,
792 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
793 // strcat_chk and strncat_chk.
794 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *DL) {
795   if (CI->getCalledFunction() == 0) return 0;
796
797   if (Value *With = Simplifier->optimizeCall(CI)) {
798     ++NumSimplified;
799     return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
800   }
801
802   return 0;
803 }
804
805 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
806   // Strip off at most one level of pointer casts, looking for an alloca.  This
807   // is good enough in practice and simpler than handling any number of casts.
808   Value *Underlying = TrampMem->stripPointerCasts();
809   if (Underlying != TrampMem &&
810       (!Underlying->hasOneUse() || Underlying->user_back() != TrampMem))
811     return 0;
812   if (!isa<AllocaInst>(Underlying))
813     return 0;
814
815   IntrinsicInst *InitTrampoline = 0;
816   for (User *U : TrampMem->users()) {
817     IntrinsicInst *II = dyn_cast<IntrinsicInst>(U);
818     if (!II)
819       return 0;
820     if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
821       if (InitTrampoline)
822         // More than one init_trampoline writes to this value.  Give up.
823         return 0;
824       InitTrampoline = II;
825       continue;
826     }
827     if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
828       // Allow any number of calls to adjust.trampoline.
829       continue;
830     return 0;
831   }
832
833   // No call to init.trampoline found.
834   if (!InitTrampoline)
835     return 0;
836
837   // Check that the alloca is being used in the expected way.
838   if (InitTrampoline->getOperand(0) != TrampMem)
839     return 0;
840
841   return InitTrampoline;
842 }
843
844 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
845                                                Value *TrampMem) {
846   // Visit all the previous instructions in the basic block, and try to find a
847   // init.trampoline which has a direct path to the adjust.trampoline.
848   for (BasicBlock::iterator I = AdjustTramp,
849        E = AdjustTramp->getParent()->begin(); I != E; ) {
850     Instruction *Inst = --I;
851     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
852       if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
853           II->getOperand(0) == TrampMem)
854         return II;
855     if (Inst->mayWriteToMemory())
856       return 0;
857   }
858   return 0;
859 }
860
861 // Given a call to llvm.adjust.trampoline, find and return the corresponding
862 // call to llvm.init.trampoline if the call to the trampoline can be optimized
863 // to a direct call to a function.  Otherwise return NULL.
864 //
865 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
866   Callee = Callee->stripPointerCasts();
867   IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
868   if (!AdjustTramp ||
869       AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
870     return 0;
871
872   Value *TrampMem = AdjustTramp->getOperand(0);
873
874   if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
875     return IT;
876   if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
877     return IT;
878   return 0;
879 }
880
881 // visitCallSite - Improvements for call and invoke instructions.
882 //
883 Instruction *InstCombiner::visitCallSite(CallSite CS) {
884   if (isAllocLikeFn(CS.getInstruction(), TLI))
885     return visitAllocSite(*CS.getInstruction());
886
887   bool Changed = false;
888
889   // If the callee is a pointer to a function, attempt to move any casts to the
890   // arguments of the call/invoke.
891   Value *Callee = CS.getCalledValue();
892   if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
893     return 0;
894
895   if (Function *CalleeF = dyn_cast<Function>(Callee))
896     // If the call and callee calling conventions don't match, this call must
897     // be unreachable, as the call is undefined.
898     if (CalleeF->getCallingConv() != CS.getCallingConv() &&
899         // Only do this for calls to a function with a body.  A prototype may
900         // not actually end up matching the implementation's calling conv for a
901         // variety of reasons (e.g. it may be written in assembly).
902         !CalleeF->isDeclaration()) {
903       Instruction *OldCall = CS.getInstruction();
904       new StoreInst(ConstantInt::getTrue(Callee->getContext()),
905                 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
906                                   OldCall);
907       // If OldCall does not return void then replaceAllUsesWith undef.
908       // This allows ValueHandlers and custom metadata to adjust itself.
909       if (!OldCall->getType()->isVoidTy())
910         ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
911       if (isa<CallInst>(OldCall))
912         return EraseInstFromFunction(*OldCall);
913
914       // We cannot remove an invoke, because it would change the CFG, just
915       // change the callee to a null pointer.
916       cast<InvokeInst>(OldCall)->setCalledFunction(
917                                     Constant::getNullValue(CalleeF->getType()));
918       return 0;
919     }
920
921   if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
922     // If CS does not return void then replaceAllUsesWith undef.
923     // This allows ValueHandlers and custom metadata to adjust itself.
924     if (!CS.getInstruction()->getType()->isVoidTy())
925       ReplaceInstUsesWith(*CS.getInstruction(),
926                           UndefValue::get(CS.getInstruction()->getType()));
927
928     if (isa<InvokeInst>(CS.getInstruction())) {
929       // Can't remove an invoke because we cannot change the CFG.
930       return 0;
931     }
932
933     // This instruction is not reachable, just remove it.  We insert a store to
934     // undef so that we know that this code is not reachable, despite the fact
935     // that we can't modify the CFG here.
936     new StoreInst(ConstantInt::getTrue(Callee->getContext()),
937                   UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
938                   CS.getInstruction());
939
940     return EraseInstFromFunction(*CS.getInstruction());
941   }
942
943   if (IntrinsicInst *II = FindInitTrampoline(Callee))
944     return transformCallThroughTrampoline(CS, II);
945
946   PointerType *PTy = cast<PointerType>(Callee->getType());
947   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
948   if (FTy->isVarArg()) {
949     int ix = FTy->getNumParams();
950     // See if we can optimize any arguments passed through the varargs area of
951     // the call.
952     for (CallSite::arg_iterator I = CS.arg_begin() + FTy->getNumParams(),
953            E = CS.arg_end(); I != E; ++I, ++ix) {
954       CastInst *CI = dyn_cast<CastInst>(*I);
955       if (CI && isSafeToEliminateVarargsCast(CS, CI, DL, ix)) {
956         *I = CI->getOperand(0);
957         Changed = true;
958       }
959     }
960   }
961
962   if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
963     // Inline asm calls cannot throw - mark them 'nounwind'.
964     CS.setDoesNotThrow();
965     Changed = true;
966   }
967
968   // Try to optimize the call if possible, we require DataLayout for most of
969   // this.  None of these calls are seen as possibly dead so go ahead and
970   // delete the instruction now.
971   if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
972     Instruction *I = tryOptimizeCall(CI, DL);
973     // If we changed something return the result, etc. Otherwise let
974     // the fallthrough check.
975     if (I) return EraseInstFromFunction(*I);
976   }
977
978   return Changed ? CS.getInstruction() : 0;
979 }
980
981 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
982 // attempt to move the cast to the arguments of the call/invoke.
983 //
984 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
985   Function *Callee =
986     dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
987   if (Callee == 0)
988     return false;
989   Instruction *Caller = CS.getInstruction();
990   const AttributeSet &CallerPAL = CS.getAttributes();
991
992   // Okay, this is a cast from a function to a different type.  Unless doing so
993   // would cause a type conversion of one of our arguments, change this call to
994   // be a direct call with arguments casted to the appropriate types.
995   //
996   FunctionType *FT = Callee->getFunctionType();
997   Type *OldRetTy = Caller->getType();
998   Type *NewRetTy = FT->getReturnType();
999
1000   // Check to see if we are changing the return type...
1001   if (OldRetTy != NewRetTy) {
1002
1003     if (NewRetTy->isStructTy())
1004       return false; // TODO: Handle multiple return values.
1005
1006     if (!CastInst::isBitCastable(NewRetTy, OldRetTy)) {
1007       if (Callee->isDeclaration())
1008         return false;   // Cannot transform this return value.
1009
1010       if (!Caller->use_empty() &&
1011           // void -> non-void is handled specially
1012           !NewRetTy->isVoidTy())
1013       return false;   // Cannot transform this return value.
1014     }
1015
1016     if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
1017       AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1018       if (RAttrs.
1019           hasAttributes(AttributeFuncs::
1020                         typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1021                         AttributeSet::ReturnIndex))
1022         return false;   // Attribute not compatible with transformed value.
1023     }
1024
1025     // If the callsite is an invoke instruction, and the return value is used by
1026     // a PHI node in a successor, we cannot change the return type of the call
1027     // because there is no place to put the cast instruction (without breaking
1028     // the critical edge).  Bail out in this case.
1029     if (!Caller->use_empty())
1030       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1031         for (User *U : II->users())
1032           if (PHINode *PN = dyn_cast<PHINode>(U))
1033             if (PN->getParent() == II->getNormalDest() ||
1034                 PN->getParent() == II->getUnwindDest())
1035               return false;
1036   }
1037
1038   unsigned NumActualArgs = CS.arg_size();
1039   unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1040
1041   CallSite::arg_iterator AI = CS.arg_begin();
1042   for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1043     Type *ParamTy = FT->getParamType(i);
1044     Type *ActTy = (*AI)->getType();
1045
1046     if (!CastInst::isBitCastable(ActTy, ParamTy))
1047       return false;   // Cannot transform this parameter value.
1048
1049     if (AttrBuilder(CallerPAL.getParamAttributes(i + 1), i + 1).
1050           hasAttributes(AttributeFuncs::
1051                         typeIncompatible(ParamTy, i + 1), i + 1))
1052       return false;   // Attribute not compatible with transformed value.
1053
1054     if (CS.isInAllocaArgument(i))
1055       return false;   // Cannot transform to and from inalloca.
1056
1057     // If the parameter is passed as a byval argument, then we have to have a
1058     // sized type and the sized type has to have the same size as the old type.
1059     if (ParamTy != ActTy &&
1060         CallerPAL.getParamAttributes(i + 1).hasAttribute(i + 1,
1061                                                          Attribute::ByVal)) {
1062       PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
1063       if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || DL == 0)
1064         return false;
1065
1066       Type *CurElTy = ActTy->getPointerElementType();
1067       if (DL->getTypeAllocSize(CurElTy) !=
1068           DL->getTypeAllocSize(ParamPTy->getElementType()))
1069         return false;
1070     }
1071   }
1072
1073   if (Callee->isDeclaration()) {
1074     // Do not delete arguments unless we have a function body.
1075     if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1076       return false;
1077
1078     // If the callee is just a declaration, don't change the varargsness of the
1079     // call.  We don't want to introduce a varargs call where one doesn't
1080     // already exist.
1081     PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
1082     if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1083       return false;
1084
1085     // If both the callee and the cast type are varargs, we still have to make
1086     // sure the number of fixed parameters are the same or we have the same
1087     // ABI issues as if we introduce a varargs call.
1088     if (FT->isVarArg() &&
1089         cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1090         FT->getNumParams() !=
1091         cast<FunctionType>(APTy->getElementType())->getNumParams())
1092       return false;
1093   }
1094
1095   if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1096       !CallerPAL.isEmpty())
1097     // In this case we have more arguments than the new function type, but we
1098     // won't be dropping them.  Check that these extra arguments have attributes
1099     // that are compatible with being a vararg call argument.
1100     for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1101       unsigned Index = CallerPAL.getSlotIndex(i - 1);
1102       if (Index <= FT->getNumParams())
1103         break;
1104
1105       // Check if it has an attribute that's incompatible with varargs.
1106       AttributeSet PAttrs = CallerPAL.getSlotAttributes(i - 1);
1107       if (PAttrs.hasAttribute(Index, Attribute::StructRet))
1108         return false;
1109     }
1110
1111
1112   // Okay, we decided that this is a safe thing to do: go ahead and start
1113   // inserting cast instructions as necessary.
1114   std::vector<Value*> Args;
1115   Args.reserve(NumActualArgs);
1116   SmallVector<AttributeSet, 8> attrVec;
1117   attrVec.reserve(NumCommonArgs);
1118
1119   // Get any return attributes.
1120   AttrBuilder RAttrs(CallerPAL, AttributeSet::ReturnIndex);
1121
1122   // If the return value is not being used, the type may not be compatible
1123   // with the existing attributes.  Wipe out any problematic attributes.
1124   RAttrs.
1125     removeAttributes(AttributeFuncs::
1126                      typeIncompatible(NewRetTy, AttributeSet::ReturnIndex),
1127                      AttributeSet::ReturnIndex);
1128
1129   // Add the new return attributes.
1130   if (RAttrs.hasAttributes())
1131     attrVec.push_back(AttributeSet::get(Caller->getContext(),
1132                                         AttributeSet::ReturnIndex, RAttrs));
1133
1134   AI = CS.arg_begin();
1135   for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1136     Type *ParamTy = FT->getParamType(i);
1137
1138     if ((*AI)->getType() == ParamTy) {
1139       Args.push_back(*AI);
1140     } else {
1141       Args.push_back(Builder->CreateBitCast(*AI, ParamTy));
1142     }
1143
1144     // Add any parameter attributes.
1145     AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1146     if (PAttrs.hasAttributes())
1147       attrVec.push_back(AttributeSet::get(Caller->getContext(), i + 1,
1148                                           PAttrs));
1149   }
1150
1151   // If the function takes more arguments than the call was taking, add them
1152   // now.
1153   for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1154     Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1155
1156   // If we are removing arguments to the function, emit an obnoxious warning.
1157   if (FT->getNumParams() < NumActualArgs) {
1158     // TODO: if (!FT->isVarArg()) this call may be unreachable. PR14722
1159     if (FT->isVarArg()) {
1160       // Add all of the arguments in their promoted form to the arg list.
1161       for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1162         Type *PTy = getPromotedType((*AI)->getType());
1163         if (PTy != (*AI)->getType()) {
1164           // Must promote to pass through va_arg area!
1165           Instruction::CastOps opcode =
1166             CastInst::getCastOpcode(*AI, false, PTy, false);
1167           Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
1168         } else {
1169           Args.push_back(*AI);
1170         }
1171
1172         // Add any parameter attributes.
1173         AttrBuilder PAttrs(CallerPAL.getParamAttributes(i + 1), i + 1);
1174         if (PAttrs.hasAttributes())
1175           attrVec.push_back(AttributeSet::get(FT->getContext(), i + 1,
1176                                               PAttrs));
1177       }
1178     }
1179   }
1180
1181   AttributeSet FnAttrs = CallerPAL.getFnAttributes();
1182   if (CallerPAL.hasAttributes(AttributeSet::FunctionIndex))
1183     attrVec.push_back(AttributeSet::get(Callee->getContext(), FnAttrs));
1184
1185   if (NewRetTy->isVoidTy())
1186     Caller->setName("");   // Void type should not have a name.
1187
1188   const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
1189                                                        attrVec);
1190
1191   Instruction *NC;
1192   if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1193     NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1194                                II->getUnwindDest(), Args);
1195     NC->takeName(II);
1196     cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1197     cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1198   } else {
1199     CallInst *CI = cast<CallInst>(Caller);
1200     NC = Builder->CreateCall(Callee, Args);
1201     NC->takeName(CI);
1202     if (CI->isTailCall())
1203       cast<CallInst>(NC)->setTailCall();
1204     cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1205     cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1206   }
1207
1208   // Insert a cast of the return type as necessary.
1209   Value *NV = NC;
1210   if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1211     if (!NV->getType()->isVoidTy()) {
1212       NV = NC = CastInst::Create(CastInst::BitCast, NC, OldRetTy);
1213       NC->setDebugLoc(Caller->getDebugLoc());
1214
1215       // If this is an invoke instruction, we should insert it after the first
1216       // non-phi, instruction in the normal successor block.
1217       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1218         BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
1219         InsertNewInstBefore(NC, *I);
1220       } else {
1221         // Otherwise, it's a call, just insert cast right after the call.
1222         InsertNewInstBefore(NC, *Caller);
1223       }
1224       Worklist.AddUsersToWorkList(*Caller);
1225     } else {
1226       NV = UndefValue::get(Caller->getType());
1227     }
1228   }
1229
1230   if (!Caller->use_empty())
1231     ReplaceInstUsesWith(*Caller, NV);
1232   else if (Caller->hasValueHandle())
1233     ValueHandleBase::ValueIsRAUWd(Caller, NV);
1234
1235   EraseInstFromFunction(*Caller);
1236   return true;
1237 }
1238
1239 // transformCallThroughTrampoline - Turn a call to a function created by
1240 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1241 // underlying function.
1242 //
1243 Instruction *
1244 InstCombiner::transformCallThroughTrampoline(CallSite CS,
1245                                              IntrinsicInst *Tramp) {
1246   Value *Callee = CS.getCalledValue();
1247   PointerType *PTy = cast<PointerType>(Callee->getType());
1248   FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1249   const AttributeSet &Attrs = CS.getAttributes();
1250
1251   // If the call already has the 'nest' attribute somewhere then give up -
1252   // otherwise 'nest' would occur twice after splicing in the chain.
1253   if (Attrs.hasAttrSomewhere(Attribute::Nest))
1254     return 0;
1255
1256   assert(Tramp &&
1257          "transformCallThroughTrampoline called with incorrect CallSite.");
1258
1259   Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
1260   PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1261   FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1262
1263   const AttributeSet &NestAttrs = NestF->getAttributes();
1264   if (!NestAttrs.isEmpty()) {
1265     unsigned NestIdx = 1;
1266     Type *NestTy = 0;
1267     AttributeSet NestAttr;
1268
1269     // Look for a parameter marked with the 'nest' attribute.
1270     for (FunctionType::param_iterator I = NestFTy->param_begin(),
1271          E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1272       if (NestAttrs.hasAttribute(NestIdx, Attribute::Nest)) {
1273         // Record the parameter type and any other attributes.
1274         NestTy = *I;
1275         NestAttr = NestAttrs.getParamAttributes(NestIdx);
1276         break;
1277       }
1278
1279     if (NestTy) {
1280       Instruction *Caller = CS.getInstruction();
1281       std::vector<Value*> NewArgs;
1282       NewArgs.reserve(CS.arg_size() + 1);
1283
1284       SmallVector<AttributeSet, 8> NewAttrs;
1285       NewAttrs.reserve(Attrs.getNumSlots() + 1);
1286
1287       // Insert the nest argument into the call argument list, which may
1288       // mean appending it.  Likewise for attributes.
1289
1290       // Add any result attributes.
1291       if (Attrs.hasAttributes(AttributeSet::ReturnIndex))
1292         NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1293                                              Attrs.getRetAttributes()));
1294
1295       {
1296         unsigned Idx = 1;
1297         CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1298         do {
1299           if (Idx == NestIdx) {
1300             // Add the chain argument and attributes.
1301             Value *NestVal = Tramp->getArgOperand(2);
1302             if (NestVal->getType() != NestTy)
1303               NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
1304             NewArgs.push_back(NestVal);
1305             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1306                                                  NestAttr));
1307           }
1308
1309           if (I == E)
1310             break;
1311
1312           // Add the original argument and attributes.
1313           NewArgs.push_back(*I);
1314           AttributeSet Attr = Attrs.getParamAttributes(Idx);
1315           if (Attr.hasAttributes(Idx)) {
1316             AttrBuilder B(Attr, Idx);
1317             NewAttrs.push_back(AttributeSet::get(Caller->getContext(),
1318                                                  Idx + (Idx >= NestIdx), B));
1319           }
1320
1321           ++Idx, ++I;
1322         } while (1);
1323       }
1324
1325       // Add any function attributes.
1326       if (Attrs.hasAttributes(AttributeSet::FunctionIndex))
1327         NewAttrs.push_back(AttributeSet::get(FTy->getContext(),
1328                                              Attrs.getFnAttributes()));
1329
1330       // The trampoline may have been bitcast to a bogus type (FTy).
1331       // Handle this by synthesizing a new function type, equal to FTy
1332       // with the chain parameter inserted.
1333
1334       std::vector<Type*> NewTypes;
1335       NewTypes.reserve(FTy->getNumParams()+1);
1336
1337       // Insert the chain's type into the list of parameter types, which may
1338       // mean appending it.
1339       {
1340         unsigned Idx = 1;
1341         FunctionType::param_iterator I = FTy->param_begin(),
1342           E = FTy->param_end();
1343
1344         do {
1345           if (Idx == NestIdx)
1346             // Add the chain's type.
1347             NewTypes.push_back(NestTy);
1348
1349           if (I == E)
1350             break;
1351
1352           // Add the original type.
1353           NewTypes.push_back(*I);
1354
1355           ++Idx, ++I;
1356         } while (1);
1357       }
1358
1359       // Replace the trampoline call with a direct call.  Let the generic
1360       // code sort out any function type mismatches.
1361       FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1362                                                 FTy->isVarArg());
1363       Constant *NewCallee =
1364         NestF->getType() == PointerType::getUnqual(NewFTy) ?
1365         NestF : ConstantExpr::getBitCast(NestF,
1366                                          PointerType::getUnqual(NewFTy));
1367       const AttributeSet &NewPAL =
1368           AttributeSet::get(FTy->getContext(), NewAttrs);
1369
1370       Instruction *NewCaller;
1371       if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1372         NewCaller = InvokeInst::Create(NewCallee,
1373                                        II->getNormalDest(), II->getUnwindDest(),
1374                                        NewArgs);
1375         cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1376         cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1377       } else {
1378         NewCaller = CallInst::Create(NewCallee, NewArgs);
1379         if (cast<CallInst>(Caller)->isTailCall())
1380           cast<CallInst>(NewCaller)->setTailCall();
1381         cast<CallInst>(NewCaller)->
1382           setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1383         cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1384       }
1385
1386       return NewCaller;
1387     }
1388   }
1389
1390   // Replace the trampoline call with a direct call.  Since there is no 'nest'
1391   // parameter, there is no need to adjust the argument list.  Let the generic
1392   // code sort out any function type mismatches.
1393   Constant *NewCallee =
1394     NestF->getType() == PTy ? NestF :
1395                               ConstantExpr::getBitCast(NestF, PTy);
1396   CS.setCalledFunction(NewCallee);
1397   return CS.getInstruction();
1398 }