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