1 //===- InstCombineCalls.cpp -----------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visitCall and visitInvoke functions.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/Support/CallSite.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/Analysis/MemoryBuiltins.h"
18 #include "llvm/Transforms/Utils/BuildLibCalls.h"
19 #include "llvm/Transforms/Utils/Local.h"
22 /// getPromotedType - Return the specified type promoted as it would be to pass
23 /// though a va_arg area.
24 static Type *getPromotedType(Type *Ty) {
25 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
26 if (ITy->getBitWidth() < 32)
27 return Type::getInt32Ty(Ty->getContext());
33 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
34 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), TD);
35 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), TD);
36 unsigned MinAlign = std::min(DstAlign, SrcAlign);
37 unsigned CopyAlign = MI->getAlignment();
39 if (CopyAlign < MinAlign) {
40 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
45 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
47 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
48 if (MemOpLength == 0) return 0;
50 // Source and destination pointer types are always "i8*" for intrinsic. See
51 // if the size is something we can handle with a single primitive load/store.
52 // A single load+store correctly handles overlapping memory in the memmove
54 unsigned Size = MemOpLength->getZExtValue();
55 if (Size == 0) return MI; // Delete this mem transfer.
57 if (Size > 8 || (Size&(Size-1)))
58 return 0; // If not 1/2/4/8 bytes, exit.
60 // Use an integer load+store unless we can find something better.
62 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
64 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
66 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
67 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
68 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
70 // Memcpy forces the use of i8* for the source and destination. That means
71 // that if you're using memcpy to move one double around, you'll get a cast
72 // from double* to i8*. We'd much rather use a double load+store rather than
73 // an i64 load+store, here because this improves the odds that the source or
74 // dest address will be promotable. See if we can find a better type than the
76 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
77 if (StrippedDest != MI->getArgOperand(0)) {
78 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
80 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
81 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
82 // down through these levels if so.
83 while (!SrcETy->isSingleValueType()) {
84 if (StructType *STy = dyn_cast<StructType>(SrcETy)) {
85 if (STy->getNumElements() == 1)
86 SrcETy = STy->getElementType(0);
89 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
90 if (ATy->getNumElements() == 1)
91 SrcETy = ATy->getElementType();
98 if (SrcETy->isSingleValueType()) {
99 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
100 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
106 // If the memcpy/memmove provides better alignment info than we can
108 SrcAlign = std::max(SrcAlign, CopyAlign);
109 DstAlign = std::max(DstAlign, CopyAlign);
111 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
112 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
113 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
114 L->setAlignment(SrcAlign);
115 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
116 S->setAlignment(DstAlign);
118 // Set the size of the copy to 0, it will be deleted on the next iteration.
119 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
123 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
124 unsigned Alignment = getKnownAlignment(MI->getDest(), TD);
125 if (MI->getAlignment() < Alignment) {
126 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
131 // Extract the length and alignment and fill if they are constant.
132 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
133 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
134 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
136 uint64_t Len = LenC->getZExtValue();
137 Alignment = MI->getAlignment();
139 // If the length is zero, this is a no-op
140 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
142 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
143 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
144 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
146 Value *Dest = MI->getDest();
147 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
148 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
149 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
151 // Alignment 0 is identity for alignment 1 for memset, but not store.
152 if (Alignment == 0) Alignment = 1;
154 // Extract the fill value and store.
155 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
156 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
158 S->setAlignment(Alignment);
160 // Set the size of the copy to 0, it will be deleted on the next iteration.
161 MI->setLength(Constant::getNullValue(LenC->getType()));
168 /// visitCallInst - CallInst simplification. This mostly only handles folding
169 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
170 /// the heavy lifting.
172 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
174 return visitFree(CI);
175 if (isAllocLikeFn(&CI))
176 return visitMalloc(CI);
178 // If the caller function is nounwind, mark the call as nounwind, even if the
180 if (CI.getParent()->getParent()->doesNotThrow() &&
181 !CI.doesNotThrow()) {
182 CI.setDoesNotThrow();
186 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
187 if (!II) return visitCallSite(&CI);
189 // Intrinsics cannot occur in an invoke, so handle them here instead of in
191 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
192 bool Changed = false;
194 // memmove/cpy/set of zero bytes is a noop.
195 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
196 if (NumBytes->isNullValue())
197 return EraseInstFromFunction(CI);
199 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
200 if (CI->getZExtValue() == 1) {
201 // Replace the instruction with just byte operations. We would
202 // transform other cases to loads/stores, but we don't know if
203 // alignment is sufficient.
207 // No other transformations apply to volatile transfers.
208 if (MI->isVolatile())
211 // If we have a memmove and the source operation is a constant global,
212 // then the source and dest pointers can't alias, so we can change this
213 // into a call to memcpy.
214 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
215 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
216 if (GVSrc->isConstant()) {
217 Module *M = CI.getParent()->getParent()->getParent();
218 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
219 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
220 CI.getArgOperand(1)->getType(),
221 CI.getArgOperand(2)->getType() };
222 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
227 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
228 // memmove(x,x,size) -> noop.
229 if (MTI->getSource() == MTI->getDest())
230 return EraseInstFromFunction(CI);
233 // If we can determine a pointer alignment that is bigger than currently
234 // set, update the alignment.
235 if (isa<MemTransferInst>(MI)) {
236 if (Instruction *I = SimplifyMemTransfer(MI))
238 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
239 if (Instruction *I = SimplifyMemSet(MSI))
243 if (Changed) return II;
246 switch (II->getIntrinsicID()) {
248 case Intrinsic::objectsize: {
250 if (getObjectSize(II->getArgOperand(0), Size, TD))
251 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
254 case Intrinsic::bswap:
255 // bswap(bswap(x)) -> x
256 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getArgOperand(0)))
257 if (Operand->getIntrinsicID() == Intrinsic::bswap)
258 return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
260 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
261 if (TruncInst *TI = dyn_cast<TruncInst>(II->getArgOperand(0))) {
262 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
263 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
264 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
265 TI->getType()->getPrimitiveSizeInBits();
266 Value *CV = ConstantInt::get(Operand->getType(), C);
267 Value *V = Builder->CreateLShr(Operand->getArgOperand(0), CV);
268 return new TruncInst(V, TI->getType());
273 case Intrinsic::powi:
274 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
277 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
280 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
281 // powi(x, -1) -> 1/x
282 if (Power->isAllOnesValue())
283 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
284 II->getArgOperand(0));
287 case Intrinsic::cttz: {
288 // If all bits below the first known one are known zero,
289 // this value is constant.
290 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
291 // FIXME: Try to simplify vectors of integers.
293 uint32_t BitWidth = IT->getBitWidth();
294 APInt KnownZero(BitWidth, 0);
295 APInt KnownOne(BitWidth, 0);
296 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
297 unsigned TrailingZeros = KnownOne.countTrailingZeros();
298 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
299 if ((Mask & KnownZero) == Mask)
300 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
301 APInt(BitWidth, TrailingZeros)));
305 case Intrinsic::ctlz: {
306 // If all bits above the first known one are known zero,
307 // this value is constant.
308 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
309 // FIXME: Try to simplify vectors of integers.
311 uint32_t BitWidth = IT->getBitWidth();
312 APInt KnownZero(BitWidth, 0);
313 APInt KnownOne(BitWidth, 0);
314 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
315 unsigned LeadingZeros = KnownOne.countLeadingZeros();
316 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
317 if ((Mask & KnownZero) == Mask)
318 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
319 APInt(BitWidth, LeadingZeros)));
323 case Intrinsic::uadd_with_overflow: {
324 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
325 IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
326 uint32_t BitWidth = IT->getBitWidth();
327 APInt LHSKnownZero(BitWidth, 0);
328 APInt LHSKnownOne(BitWidth, 0);
329 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
330 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
331 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
333 if (LHSKnownNegative || LHSKnownPositive) {
334 APInt RHSKnownZero(BitWidth, 0);
335 APInt RHSKnownOne(BitWidth, 0);
336 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
337 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
338 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
339 if (LHSKnownNegative && RHSKnownNegative) {
340 // The sign bit is set in both cases: this MUST overflow.
341 // Create a simple add instruction, and insert it into the struct.
342 Value *Add = Builder->CreateAdd(LHS, RHS);
345 UndefValue::get(LHS->getType()),
346 ConstantInt::getTrue(II->getContext())
348 StructType *ST = cast<StructType>(II->getType());
349 Constant *Struct = ConstantStruct::get(ST, V);
350 return InsertValueInst::Create(Struct, Add, 0);
353 if (LHSKnownPositive && RHSKnownPositive) {
354 // The sign bit is clear in both cases: this CANNOT overflow.
355 // Create a simple add instruction, and insert it into the struct.
356 Value *Add = Builder->CreateNUWAdd(LHS, RHS);
359 UndefValue::get(LHS->getType()),
360 ConstantInt::getFalse(II->getContext())
362 StructType *ST = cast<StructType>(II->getType());
363 Constant *Struct = ConstantStruct::get(ST, V);
364 return InsertValueInst::Create(Struct, Add, 0);
368 // FALL THROUGH uadd into sadd
369 case Intrinsic::sadd_with_overflow:
370 // Canonicalize constants into the RHS.
371 if (isa<Constant>(II->getArgOperand(0)) &&
372 !isa<Constant>(II->getArgOperand(1))) {
373 Value *LHS = II->getArgOperand(0);
374 II->setArgOperand(0, II->getArgOperand(1));
375 II->setArgOperand(1, LHS);
379 // X + undef -> undef
380 if (isa<UndefValue>(II->getArgOperand(1)))
381 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
383 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
384 // X + 0 -> {X, false}
387 UndefValue::get(II->getArgOperand(0)->getType()),
388 ConstantInt::getFalse(II->getContext())
391 ConstantStruct::get(cast<StructType>(II->getType()), V);
392 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
396 case Intrinsic::usub_with_overflow:
397 case Intrinsic::ssub_with_overflow:
398 // undef - X -> undef
399 // X - undef -> undef
400 if (isa<UndefValue>(II->getArgOperand(0)) ||
401 isa<UndefValue>(II->getArgOperand(1)))
402 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
404 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
405 // X - 0 -> {X, false}
408 UndefValue::get(II->getArgOperand(0)->getType()),
409 ConstantInt::getFalse(II->getContext())
412 ConstantStruct::get(cast<StructType>(II->getType()), V);
413 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
417 case Intrinsic::umul_with_overflow: {
418 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
419 unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
421 APInt LHSKnownZero(BitWidth, 0);
422 APInt LHSKnownOne(BitWidth, 0);
423 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
424 APInt RHSKnownZero(BitWidth, 0);
425 APInt RHSKnownOne(BitWidth, 0);
426 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
428 // Get the largest possible values for each operand.
429 APInt LHSMax = ~LHSKnownZero;
430 APInt RHSMax = ~RHSKnownZero;
432 // If multiplying the maximum values does not overflow then we can turn
433 // this into a plain NUW mul.
435 LHSMax.umul_ov(RHSMax, Overflow);
437 Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
439 UndefValue::get(LHS->getType()),
442 Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
443 return InsertValueInst::Create(Struct, Mul, 0);
446 case Intrinsic::smul_with_overflow:
447 // Canonicalize constants into the RHS.
448 if (isa<Constant>(II->getArgOperand(0)) &&
449 !isa<Constant>(II->getArgOperand(1))) {
450 Value *LHS = II->getArgOperand(0);
451 II->setArgOperand(0, II->getArgOperand(1));
452 II->setArgOperand(1, LHS);
456 // X * undef -> undef
457 if (isa<UndefValue>(II->getArgOperand(1)))
458 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
460 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
463 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
465 // X * 1 -> {X, false}
466 if (RHSI->equalsInt(1)) {
468 UndefValue::get(II->getArgOperand(0)->getType()),
469 ConstantInt::getFalse(II->getContext())
472 ConstantStruct::get(cast<StructType>(II->getType()), V);
473 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
477 case Intrinsic::ppc_altivec_lvx:
478 case Intrinsic::ppc_altivec_lvxl:
479 // Turn PPC lvx -> load if the pointer is known aligned.
480 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
481 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
482 PointerType::getUnqual(II->getType()));
483 return new LoadInst(Ptr);
486 case Intrinsic::ppc_altivec_stvx:
487 case Intrinsic::ppc_altivec_stvxl:
488 // Turn stvx -> store if the pointer is known aligned.
489 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, TD) >= 16) {
491 PointerType::getUnqual(II->getArgOperand(0)->getType());
492 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
493 return new StoreInst(II->getArgOperand(0), Ptr);
496 case Intrinsic::x86_sse_storeu_ps:
497 case Intrinsic::x86_sse2_storeu_pd:
498 case Intrinsic::x86_sse2_storeu_dq:
499 // Turn X86 storeu -> store if the pointer is known aligned.
500 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
502 PointerType::getUnqual(II->getArgOperand(1)->getType());
503 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
504 return new StoreInst(II->getArgOperand(1), Ptr);
508 case Intrinsic::x86_sse_cvtss2si:
509 case Intrinsic::x86_sse_cvtss2si64:
510 case Intrinsic::x86_sse_cvttss2si:
511 case Intrinsic::x86_sse_cvttss2si64:
512 case Intrinsic::x86_sse2_cvtsd2si:
513 case Intrinsic::x86_sse2_cvtsd2si64:
514 case Intrinsic::x86_sse2_cvttsd2si:
515 case Intrinsic::x86_sse2_cvttsd2si64: {
516 // These intrinsics only demand the 0th element of their input vectors. If
517 // we can simplify the input based on that, do so now.
519 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
520 APInt DemandedElts(VWidth, 1);
521 APInt UndefElts(VWidth, 0);
522 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
523 DemandedElts, UndefElts)) {
524 II->setArgOperand(0, V);
531 case Intrinsic::x86_sse41_pmovsxbw:
532 case Intrinsic::x86_sse41_pmovsxwd:
533 case Intrinsic::x86_sse41_pmovsxdq:
534 case Intrinsic::x86_sse41_pmovzxbw:
535 case Intrinsic::x86_sse41_pmovzxwd:
536 case Intrinsic::x86_sse41_pmovzxdq: {
537 // pmov{s|z}x ignores the upper half of their input vectors.
539 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
540 unsigned LowHalfElts = VWidth / 2;
541 APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
542 APInt UndefElts(VWidth, 0);
543 if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
546 II->setArgOperand(0, TmpV);
552 case Intrinsic::ppc_altivec_vperm:
553 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
554 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
555 assert(Mask->getType()->getVectorNumElements() == 16 &&
556 "Bad type for intrinsic!");
558 // Check that all of the elements are integer constants or undefs.
559 bool AllEltsOk = true;
560 for (unsigned i = 0; i != 16; ++i) {
561 Constant *Elt = Mask->getAggregateElement(i);
563 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
570 // Cast the input vectors to byte vectors.
571 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
573 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
575 Value *Result = UndefValue::get(Op0->getType());
577 // Only extract each element once.
578 Value *ExtractedElts[32];
579 memset(ExtractedElts, 0, sizeof(ExtractedElts));
581 for (unsigned i = 0; i != 16; ++i) {
582 if (isa<UndefValue>(Mask->getAggregateElement(i)))
585 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
586 Idx &= 31; // Match the hardware behavior.
588 if (ExtractedElts[Idx] == 0) {
590 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
591 Builder->getInt32(Idx&15));
594 // Insert this value into the result vector.
595 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
596 Builder->getInt32(i));
598 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
603 case Intrinsic::arm_neon_vld1:
604 case Intrinsic::arm_neon_vld2:
605 case Intrinsic::arm_neon_vld3:
606 case Intrinsic::arm_neon_vld4:
607 case Intrinsic::arm_neon_vld2lane:
608 case Intrinsic::arm_neon_vld3lane:
609 case Intrinsic::arm_neon_vld4lane:
610 case Intrinsic::arm_neon_vst1:
611 case Intrinsic::arm_neon_vst2:
612 case Intrinsic::arm_neon_vst3:
613 case Intrinsic::arm_neon_vst4:
614 case Intrinsic::arm_neon_vst2lane:
615 case Intrinsic::arm_neon_vst3lane:
616 case Intrinsic::arm_neon_vst4lane: {
617 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), TD);
618 unsigned AlignArg = II->getNumArgOperands() - 1;
619 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
620 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
621 II->setArgOperand(AlignArg,
622 ConstantInt::get(Type::getInt32Ty(II->getContext()),
629 case Intrinsic::arm_neon_vmulls:
630 case Intrinsic::arm_neon_vmullu: {
631 Value *Arg0 = II->getArgOperand(0);
632 Value *Arg1 = II->getArgOperand(1);
634 // Handle mul by zero first:
635 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
636 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
639 // Check for constant LHS & RHS - in this case we just simplify.
640 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu);
641 VectorType *NewVT = cast<VectorType>(II->getType());
642 unsigned NewWidth = NewVT->getElementType()->getIntegerBitWidth();
643 if (ConstantDataVector *CV0 = dyn_cast<ConstantDataVector>(Arg0)) {
644 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
645 VectorType* VT = cast<VectorType>(CV0->getType());
646 SmallVector<Constant*, 4> NewElems;
647 for (unsigned i = 0; i < VT->getNumElements(); ++i) {
649 (cast<ConstantInt>(CV0->getAggregateElement(i)))->getValue();
650 CV0E = Zext ? CV0E.zext(NewWidth) : CV0E.sext(NewWidth);
652 (cast<ConstantInt>(CV1->getAggregateElement(i)))->getValue();
653 CV1E = Zext ? CV1E.zext(NewWidth) : CV1E.sext(NewWidth);
655 ConstantInt::get(NewVT->getElementType(), CV0E * CV1E));
657 return ReplaceInstUsesWith(CI, ConstantVector::get(NewElems));
660 // Couldn't simplify - cannonicalize constant to the RHS.
661 std::swap(Arg0, Arg1);
664 // Handle mul by one:
665 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
666 if (ConstantInt *Splat =
667 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) {
668 if (Splat->isOne()) {
670 return CastInst::CreateZExtOrBitCast(Arg0, II->getType());
672 return CastInst::CreateSExtOrBitCast(Arg0, II->getType());
680 case Intrinsic::stackrestore: {
681 // If the save is right next to the restore, remove the restore. This can
682 // happen when variable allocas are DCE'd.
683 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
684 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
685 BasicBlock::iterator BI = SS;
687 return EraseInstFromFunction(CI);
691 // Scan down this block to see if there is another stack restore in the
692 // same block without an intervening call/alloca.
693 BasicBlock::iterator BI = II;
694 TerminatorInst *TI = II->getParent()->getTerminator();
695 bool CannotRemove = false;
696 for (++BI; &*BI != TI; ++BI) {
697 if (isa<AllocaInst>(BI)) {
701 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
702 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
703 // If there is a stackrestore below this one, remove this one.
704 if (II->getIntrinsicID() == Intrinsic::stackrestore)
705 return EraseInstFromFunction(CI);
706 // Otherwise, ignore the intrinsic.
708 // If we found a non-intrinsic call, we can't remove the stack
716 // If the stack restore is in a return, resume, or unwind block and if there
717 // are no allocas or calls between the restore and the return, nuke the
719 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
720 return EraseInstFromFunction(CI);
725 return visitCallSite(II);
728 // InvokeInst simplification
730 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
731 return visitCallSite(&II);
734 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
735 /// passed through the varargs area, we can eliminate the use of the cast.
736 static bool isSafeToEliminateVarargsCast(const CallSite CS,
737 const CastInst * const CI,
738 const TargetData * const TD,
740 if (!CI->isLosslessCast())
743 // The size of ByVal arguments is derived from the type, so we
744 // can't change to a type with a different size. If the size were
745 // passed explicitly we could avoid this check.
746 if (!CS.isByValArgument(ix))
750 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
751 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
752 if (!SrcTy->isSized() || !DstTy->isSized())
754 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
760 class InstCombineFortifiedLibCalls : public SimplifyFortifiedLibCalls {
763 void replaceCall(Value *With) {
764 NewInstruction = IC->ReplaceInstUsesWith(*CI, With);
766 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
767 if (CI->getArgOperand(SizeCIOp) == CI->getArgOperand(SizeArgOp))
769 if (ConstantInt *SizeCI =
770 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
771 if (SizeCI->isAllOnesValue())
774 uint64_t Len = GetStringLength(CI->getArgOperand(SizeArgOp));
775 // If the length is 0 we don't know how long it is and so we can't
777 if (Len == 0) return false;
778 return SizeCI->getZExtValue() >= Len;
780 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
781 CI->getArgOperand(SizeArgOp)))
782 return SizeCI->getZExtValue() >= Arg->getZExtValue();
787 InstCombineFortifiedLibCalls(InstCombiner *IC) : IC(IC), NewInstruction(0) { }
788 Instruction *NewInstruction;
790 } // end anonymous namespace
792 // Try to fold some different type of calls here.
793 // Currently we're only working with the checking functions, memcpy_chk,
794 // mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
795 // strcat_chk and strncat_chk.
796 Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData *TD) {
797 if (CI->getCalledFunction() == 0) return 0;
799 InstCombineFortifiedLibCalls Simplifier(this);
800 Simplifier.fold(CI, TD);
801 return Simplifier.NewInstruction;
804 static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
805 // Strip off at most one level of pointer casts, looking for an alloca. This
806 // is good enough in practice and simpler than handling any number of casts.
807 Value *Underlying = TrampMem->stripPointerCasts();
808 if (Underlying != TrampMem &&
809 (!Underlying->hasOneUse() || *Underlying->use_begin() != TrampMem))
811 if (!isa<AllocaInst>(Underlying))
814 IntrinsicInst *InitTrampoline = 0;
815 for (Value::use_iterator I = TrampMem->use_begin(), E = TrampMem->use_end();
817 IntrinsicInst *II = dyn_cast<IntrinsicInst>(*I);
820 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
822 // More than one init_trampoline writes to this value. Give up.
827 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
828 // Allow any number of calls to adjust.trampoline.
833 // No call to init.trampoline found.
837 // Check that the alloca is being used in the expected way.
838 if (InitTrampoline->getOperand(0) != TrampMem)
841 return InitTrampoline;
844 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
846 // Visit all the previous instructions in the basic block, and try to find a
847 // init.trampoline which has a direct path to the adjust.trampoline.
848 for (BasicBlock::iterator I = AdjustTramp,
849 E = AdjustTramp->getParent()->begin(); I != E; ) {
850 Instruction *Inst = --I;
851 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
852 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
853 II->getOperand(0) == TrampMem)
855 if (Inst->mayWriteToMemory())
861 // Given a call to llvm.adjust.trampoline, find and return the corresponding
862 // call to llvm.init.trampoline if the call to the trampoline can be optimized
863 // to a direct call to a function. Otherwise return NULL.
865 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
866 Callee = Callee->stripPointerCasts();
867 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
869 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
872 Value *TrampMem = AdjustTramp->getOperand(0);
874 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
876 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
881 // visitCallSite - Improvements for call and invoke instructions.
883 Instruction *InstCombiner::visitCallSite(CallSite CS) {
884 bool Changed = false;
886 // If the callee is a pointer to a function, attempt to move any casts to the
887 // arguments of the call/invoke.
888 Value *Callee = CS.getCalledValue();
889 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
892 if (Function *CalleeF = dyn_cast<Function>(Callee))
893 // If the call and callee calling conventions don't match, this call must
894 // be unreachable, as the call is undefined.
895 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
896 // Only do this for calls to a function with a body. A prototype may
897 // not actually end up matching the implementation's calling conv for a
898 // variety of reasons (e.g. it may be written in assembly).
899 !CalleeF->isDeclaration()) {
900 Instruction *OldCall = CS.getInstruction();
901 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
902 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
904 // If OldCall dues not return void then replaceAllUsesWith undef.
905 // This allows ValueHandlers and custom metadata to adjust itself.
906 if (!OldCall->getType()->isVoidTy())
907 ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
908 if (isa<CallInst>(OldCall))
909 return EraseInstFromFunction(*OldCall);
911 // We cannot remove an invoke, because it would change the CFG, just
912 // change the callee to a null pointer.
913 cast<InvokeInst>(OldCall)->setCalledFunction(
914 Constant::getNullValue(CalleeF->getType()));
918 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
919 // This instruction is not reachable, just remove it. We insert a store to
920 // undef so that we know that this code is not reachable, despite the fact
921 // that we can't modify the CFG here.
922 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
923 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
924 CS.getInstruction());
926 // If CS does not return void then replaceAllUsesWith undef.
927 // This allows ValueHandlers and custom metadata to adjust itself.
928 if (!CS.getInstruction()->getType()->isVoidTy())
929 ReplaceInstUsesWith(*CS.getInstruction(),
930 UndefValue::get(CS.getInstruction()->getType()));
932 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
933 // Don't break the CFG, insert a dummy cond branch.
934 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
935 ConstantInt::getTrue(Callee->getContext()), II);
937 return EraseInstFromFunction(*CS.getInstruction());
940 if (IntrinsicInst *II = FindInitTrampoline(Callee))
941 return transformCallThroughTrampoline(CS, II);
943 PointerType *PTy = cast<PointerType>(Callee->getType());
944 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
945 if (FTy->isVarArg()) {
946 int ix = FTy->getNumParams();
947 // See if we can optimize any arguments passed through the varargs area of
949 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
950 E = CS.arg_end(); I != E; ++I, ++ix) {
951 CastInst *CI = dyn_cast<CastInst>(*I);
952 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
953 *I = CI->getOperand(0);
959 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
960 // Inline asm calls cannot throw - mark them 'nounwind'.
961 CS.setDoesNotThrow();
965 // Try to optimize the call if possible, we require TargetData for most of
966 // this. None of these calls are seen as possibly dead so go ahead and
967 // delete the instruction now.
968 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
969 Instruction *I = tryOptimizeCall(CI, TD);
970 // If we changed something return the result, etc. Otherwise let
971 // the fallthrough check.
972 if (I) return EraseInstFromFunction(*I);
975 return Changed ? CS.getInstruction() : 0;
978 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
979 // attempt to move the cast to the arguments of the call/invoke.
981 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
983 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
986 Instruction *Caller = CS.getInstruction();
987 const AttrListPtr &CallerPAL = CS.getAttributes();
989 // Okay, this is a cast from a function to a different type. Unless doing so
990 // would cause a type conversion of one of our arguments, change this call to
991 // be a direct call with arguments casted to the appropriate types.
993 FunctionType *FT = Callee->getFunctionType();
994 Type *OldRetTy = Caller->getType();
995 Type *NewRetTy = FT->getReturnType();
997 if (NewRetTy->isStructTy())
998 return false; // TODO: Handle multiple return values.
1000 // Check to see if we are changing the return type...
1001 if (OldRetTy != NewRetTy) {
1002 if (Callee->isDeclaration() &&
1003 // Conversion is ok if changing from one pointer type to another or from
1004 // a pointer to an integer of the same size.
1005 !((OldRetTy->isPointerTy() || !TD ||
1006 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
1007 (NewRetTy->isPointerTy() || !TD ||
1008 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
1009 return false; // Cannot transform this return value.
1011 if (!Caller->use_empty() &&
1012 // void -> non-void is handled specially
1013 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
1014 return false; // Cannot transform this return value.
1016 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
1017 Attributes RAttrs = CallerPAL.getRetAttributes();
1018 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
1019 return false; // Attribute not compatible with transformed value.
1022 // If the callsite is an invoke instruction, and the return value is used by
1023 // a PHI node in a successor, we cannot change the return type of the call
1024 // because there is no place to put the cast instruction (without breaking
1025 // the critical edge). Bail out in this case.
1026 if (!Caller->use_empty())
1027 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1028 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
1030 if (PHINode *PN = dyn_cast<PHINode>(*UI))
1031 if (PN->getParent() == II->getNormalDest() ||
1032 PN->getParent() == II->getUnwindDest())
1036 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1037 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1039 CallSite::arg_iterator AI = CS.arg_begin();
1040 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1041 Type *ParamTy = FT->getParamType(i);
1042 Type *ActTy = (*AI)->getType();
1044 if (!CastInst::isCastable(ActTy, ParamTy))
1045 return false; // Cannot transform this parameter value.
1047 Attributes Attrs = CallerPAL.getParamAttributes(i + 1);
1048 if (Attrs & Attribute::typeIncompatible(ParamTy))
1049 return false; // Attribute not compatible with transformed value.
1051 // If the parameter is passed as a byval argument, then we have to have a
1052 // sized type and the sized type has to have the same size as the old type.
1053 if (ParamTy != ActTy && (Attrs & Attribute::ByVal)) {
1054 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
1055 if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || TD == 0)
1058 Type *CurElTy = cast<PointerType>(ActTy)->getElementType();
1059 if (TD->getTypeAllocSize(CurElTy) !=
1060 TD->getTypeAllocSize(ParamPTy->getElementType()))
1064 // Converting from one pointer type to another or between a pointer and an
1065 // integer of the same size is safe even if we do not have a body.
1066 bool isConvertible = ActTy == ParamTy ||
1067 (TD && ((ParamTy->isPointerTy() ||
1068 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
1069 (ActTy->isPointerTy() ||
1070 ActTy == TD->getIntPtrType(Caller->getContext()))));
1071 if (Callee->isDeclaration() && !isConvertible) return false;
1074 if (Callee->isDeclaration()) {
1075 // Do not delete arguments unless we have a function body.
1076 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1079 // If the callee is just a declaration, don't change the varargsness of the
1080 // call. We don't want to introduce a varargs call where one doesn't
1082 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
1083 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1086 // If both the callee and the cast type are varargs, we still have to make
1087 // sure the number of fixed parameters are the same or we have the same
1088 // ABI issues as if we introduce a varargs call.
1089 if (FT->isVarArg() &&
1090 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1091 FT->getNumParams() !=
1092 cast<FunctionType>(APTy->getElementType())->getNumParams())
1096 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1097 !CallerPAL.isEmpty())
1098 // In this case we have more arguments than the new function type, but we
1099 // won't be dropping them. Check that these extra arguments have attributes
1100 // that are compatible with being a vararg call argument.
1101 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1102 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1104 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1105 if (PAttrs & Attribute::VarArgsIncompatible)
1110 // Okay, we decided that this is a safe thing to do: go ahead and start
1111 // inserting cast instructions as necessary.
1112 std::vector<Value*> Args;
1113 Args.reserve(NumActualArgs);
1114 SmallVector<AttributeWithIndex, 8> attrVec;
1115 attrVec.reserve(NumCommonArgs);
1117 // Get any return attributes.
1118 Attributes RAttrs = CallerPAL.getRetAttributes();
1120 // If the return value is not being used, the type may not be compatible
1121 // with the existing attributes. Wipe out any problematic attributes.
1122 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
1124 // Add the new return attributes.
1126 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
1128 AI = CS.arg_begin();
1129 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1130 Type *ParamTy = FT->getParamType(i);
1131 if ((*AI)->getType() == ParamTy) {
1132 Args.push_back(*AI);
1134 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1135 false, ParamTy, false);
1136 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy));
1139 // Add any parameter attributes.
1140 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1141 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1144 // If the function takes more arguments than the call was taking, add them
1146 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1147 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1149 // If we are removing arguments to the function, emit an obnoxious warning.
1150 if (FT->getNumParams() < NumActualArgs) {
1151 if (!FT->isVarArg()) {
1152 errs() << "WARNING: While resolving call to function '"
1153 << Callee->getName() << "' arguments were dropped!\n";
1155 // Add all of the arguments in their promoted form to the arg list.
1156 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1157 Type *PTy = getPromotedType((*AI)->getType());
1158 if (PTy != (*AI)->getType()) {
1159 // Must promote to pass through va_arg area!
1160 Instruction::CastOps opcode =
1161 CastInst::getCastOpcode(*AI, false, PTy, false);
1162 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
1164 Args.push_back(*AI);
1167 // Add any parameter attributes.
1168 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1169 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1174 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
1175 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1177 if (NewRetTy->isVoidTy())
1178 Caller->setName(""); // Void type should not have a name.
1180 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec);
1183 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1184 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1185 II->getUnwindDest(), Args);
1187 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1188 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1190 CallInst *CI = cast<CallInst>(Caller);
1191 NC = Builder->CreateCall(Callee, Args);
1193 if (CI->isTailCall())
1194 cast<CallInst>(NC)->setTailCall();
1195 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1196 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1199 // Insert a cast of the return type as necessary.
1201 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1202 if (!NV->getType()->isVoidTy()) {
1203 Instruction::CastOps opcode =
1204 CastInst::getCastOpcode(NC, false, OldRetTy, false);
1205 NV = NC = CastInst::Create(opcode, NC, OldRetTy);
1206 NC->setDebugLoc(Caller->getDebugLoc());
1208 // If this is an invoke instruction, we should insert it after the first
1209 // non-phi, instruction in the normal successor block.
1210 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1211 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
1212 InsertNewInstBefore(NC, *I);
1214 // Otherwise, it's a call, just insert cast right after the call.
1215 InsertNewInstBefore(NC, *Caller);
1217 Worklist.AddUsersToWorkList(*Caller);
1219 NV = UndefValue::get(Caller->getType());
1223 if (!Caller->use_empty())
1224 ReplaceInstUsesWith(*Caller, NV);
1226 EraseInstFromFunction(*Caller);
1230 // transformCallThroughTrampoline - Turn a call to a function created by
1231 // init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1232 // underlying function.
1235 InstCombiner::transformCallThroughTrampoline(CallSite CS,
1236 IntrinsicInst *Tramp) {
1237 Value *Callee = CS.getCalledValue();
1238 PointerType *PTy = cast<PointerType>(Callee->getType());
1239 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1240 const AttrListPtr &Attrs = CS.getAttributes();
1242 // If the call already has the 'nest' attribute somewhere then give up -
1243 // otherwise 'nest' would occur twice after splicing in the chain.
1244 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1248 "transformCallThroughTrampoline called with incorrect CallSite.");
1250 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
1251 PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1252 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1254 const AttrListPtr &NestAttrs = NestF->getAttributes();
1255 if (!NestAttrs.isEmpty()) {
1256 unsigned NestIdx = 1;
1258 Attributes NestAttr = Attribute::None;
1260 // Look for a parameter marked with the 'nest' attribute.
1261 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1262 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1263 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1264 // Record the parameter type and any other attributes.
1266 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1271 Instruction *Caller = CS.getInstruction();
1272 std::vector<Value*> NewArgs;
1273 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1275 SmallVector<AttributeWithIndex, 8> NewAttrs;
1276 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1278 // Insert the nest argument into the call argument list, which may
1279 // mean appending it. Likewise for attributes.
1281 // Add any result attributes.
1282 if (Attributes Attr = Attrs.getRetAttributes())
1283 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1287 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1289 if (Idx == NestIdx) {
1290 // Add the chain argument and attributes.
1291 Value *NestVal = Tramp->getArgOperand(2);
1292 if (NestVal->getType() != NestTy)
1293 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
1294 NewArgs.push_back(NestVal);
1295 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1301 // Add the original argument and attributes.
1302 NewArgs.push_back(*I);
1303 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1305 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1311 // Add any function attributes.
1312 if (Attributes Attr = Attrs.getFnAttributes())
1313 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1315 // The trampoline may have been bitcast to a bogus type (FTy).
1316 // Handle this by synthesizing a new function type, equal to FTy
1317 // with the chain parameter inserted.
1319 std::vector<Type*> NewTypes;
1320 NewTypes.reserve(FTy->getNumParams()+1);
1322 // Insert the chain's type into the list of parameter types, which may
1323 // mean appending it.
1326 FunctionType::param_iterator I = FTy->param_begin(),
1327 E = FTy->param_end();
1331 // Add the chain's type.
1332 NewTypes.push_back(NestTy);
1337 // Add the original type.
1338 NewTypes.push_back(*I);
1344 // Replace the trampoline call with a direct call. Let the generic
1345 // code sort out any function type mismatches.
1346 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
1348 Constant *NewCallee =
1349 NestF->getType() == PointerType::getUnqual(NewFTy) ?
1350 NestF : ConstantExpr::getBitCast(NestF,
1351 PointerType::getUnqual(NewFTy));
1352 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs);
1354 Instruction *NewCaller;
1355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1356 NewCaller = InvokeInst::Create(NewCallee,
1357 II->getNormalDest(), II->getUnwindDest(),
1359 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1360 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1362 NewCaller = CallInst::Create(NewCallee, NewArgs);
1363 if (cast<CallInst>(Caller)->isTailCall())
1364 cast<CallInst>(NewCaller)->setTailCall();
1365 cast<CallInst>(NewCaller)->
1366 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1367 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1374 // Replace the trampoline call with a direct call. Since there is no 'nest'
1375 // parameter, there is no need to adjust the argument list. Let the generic
1376 // code sort out any function type mismatches.
1377 Constant *NewCallee =
1378 NestF->getType() == PTy ? NestF :
1379 ConstantExpr::getBitCast(NestF, PTy);
1380 CS.setCalledFunction(NewCallee);
1381 return CS.getInstruction();