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