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/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"
23 STATISTIC(NumSimplified, "Number of library calls simplified");
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());
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);
44 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
45 if (ATy->getNumElements() == 1)
46 T = ATy->getElementType();
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();
62 if (CopyAlign < MinAlign) {
63 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
68 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
70 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
71 if (MemOpLength == 0) return 0;
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
77 uint64_t Size = MemOpLength->getLimitedValue();
78 assert(Size && "0-sized memory transfering should be removed already.");
80 if (Size > 8 || (Size&(Size-1)))
81 return 0; // If not 1/2/4/8 bytes, exit.
83 // Use an integer load+store unless we can find something better.
85 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
87 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
89 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
90 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
91 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
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
99 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
101 if (StrippedDest != MI->getArgOperand(0)) {
102 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
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);
109 if (SrcETy->isSingleValueType()) {
110 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
111 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
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 &&
118 isa<ConstantInt>(M->getOperand(0)) &&
119 cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
121 isa<ConstantInt>(M->getOperand(1)) &&
122 cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
124 isa<MDNode>(M->getOperand(2)))
125 CopyMD = cast<MDNode>(M->getOperand(2));
131 // If the memcpy/memmove provides better alignment info than we can
133 SrcAlign = std::max(SrcAlign, CopyAlign);
134 DstAlign = std::max(DstAlign, CopyAlign);
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);
141 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
142 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
143 S->setAlignment(DstAlign);
145 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
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()));
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(),
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))
165 uint64_t Len = LenC->getLimitedValue();
166 Alignment = MI->getAlignment();
167 assert(Len && "0-sized memory setting should be removed already.");
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.
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);
178 // Alignment 0 is identity for alignment 1 for memset, but not store.
179 if (Alignment == 0) Alignment = 1;
181 // Extract the fill value and store.
182 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
183 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
185 S->setAlignment(Alignment);
187 // Set the size of the copy to 0, it will be deleted on the next iteration.
188 MI->setLength(Constant::getNullValue(LenC->getType()));
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.
199 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
200 if (isFreeCall(&CI, TLI))
201 return visitFree(CI);
203 // If the caller function is nounwind, mark the call as nounwind, even if the
205 if (CI.getParent()->getParent()->doesNotThrow() &&
206 !CI.doesNotThrow()) {
207 CI.setDoesNotThrow();
211 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
212 if (!II) return visitCallSite(&CI);
214 // Intrinsics cannot occur in an invoke, so handle them here instead of in
216 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
217 bool Changed = false;
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);
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.
232 // No other transformations apply to volatile transfers.
233 if (MI->isVolatile())
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));
252 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
253 // memmove(x,x,size) -> noop.
254 if (MTI->getSource() == MTI->getDest())
255 return EraseInstFromFunction(CI);
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))
263 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
264 if (Instruction *I = SimplifyMemSet(MSI))
268 if (Changed) return II;
271 switch (II->getIntrinsicID()) {
273 case Intrinsic::objectsize: {
275 if (getObjectSize(II->getArgOperand(0), Size, TD, TLI))
276 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
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));
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());
298 case Intrinsic::powi:
299 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
302 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
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));
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.
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)));
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.
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)));
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];
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);
370 UndefValue::get(LHS->getType()),
371 ConstantInt::getTrue(II->getContext())
373 StructType *ST = cast<StructType>(II->getType());
374 Constant *Struct = ConstantStruct::get(ST, V);
375 return InsertValueInst::Create(Struct, Add, 0);
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);
384 UndefValue::get(LHS->getType()),
385 ConstantInt::getFalse(II->getContext())
387 StructType *ST = cast<StructType>(II->getType());
388 Constant *Struct = ConstantStruct::get(ST, V);
389 return InsertValueInst::Create(Struct, Add, 0);
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);
404 // X + undef -> undef
405 if (isa<UndefValue>(II->getArgOperand(1)))
406 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
408 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
409 // X + 0 -> {X, false}
412 UndefValue::get(II->getArgOperand(0)->getType()),
413 ConstantInt::getFalse(II->getContext())
416 ConstantStruct::get(cast<StructType>(II->getType()), V);
417 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
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()));
429 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
430 // X - 0 -> {X, false}
433 UndefValue::get(II->getArgOperand(0)->getType()),
434 ConstantInt::getFalse(II->getContext())
437 ConstantStruct::get(cast<StructType>(II->getType()), V);
438 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
442 case Intrinsic::umul_with_overflow: {
443 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
444 unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
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);
453 // Get the largest possible values for each operand.
454 APInt LHSMax = ~LHSKnownZero;
455 APInt RHSMax = ~RHSKnownZero;
457 // If multiplying the maximum values does not overflow then we can turn
458 // this into a plain NUW mul.
460 LHSMax.umul_ov(RHSMax, Overflow);
462 Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
464 UndefValue::get(LHS->getType()),
467 Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
468 return InsertValueInst::Create(Struct, Mul, 0);
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);
481 // X * undef -> undef
482 if (isa<UndefValue>(II->getArgOperand(1)))
483 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
485 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
488 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
490 // X * 1 -> {X, false}
491 if (RHSI->equalsInt(1)) {
493 UndefValue::get(II->getArgOperand(0)->getType()),
494 ConstantInt::getFalse(II->getContext())
497 ConstantStruct::get(cast<StructType>(II->getType()), V);
498 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
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);
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) {
516 PointerType::getUnqual(II->getArgOperand(0)->getType());
517 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
518 return new StoreInst(II->getArgOperand(0), Ptr);
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) {
527 PointerType::getUnqual(II->getArgOperand(1)->getType());
528 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
529 return new StoreInst(II->getArgOperand(1), Ptr);
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.
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);
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.
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),
571 II->setArgOperand(0, TmpV);
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!");
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);
588 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
595 // Cast the input vectors to byte vectors.
596 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
598 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
600 Value *Result = UndefValue::get(Op0->getType());
602 // Only extract each element once.
603 Value *ExtractedElts[32];
604 memset(ExtractedElts, 0, sizeof(ExtractedElts));
606 for (unsigned i = 0; i != 16; ++i) {
607 if (isa<UndefValue>(Mask->getAggregateElement(i)))
610 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
611 Idx &= 31; // Match the hardware behavior.
613 if (ExtractedElts[Idx] == 0) {
615 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
616 Builder->getInt32(Idx&15));
619 // Insert this value into the result vector.
620 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
621 Builder->getInt32(i));
623 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
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()),
654 case Intrinsic::arm_neon_vmulls:
655 case Intrinsic::arm_neon_vmullu: {
656 Value *Arg0 = II->getArgOperand(0);
657 Value *Arg1 = II->getArgOperand(1);
659 // Handle mul by zero first:
660 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
661 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
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) {
674 (cast<ConstantInt>(CV0->getAggregateElement(i)))->getValue();
675 CV0E = Zext ? CV0E.zext(NewWidth) : CV0E.sext(NewWidth);
677 (cast<ConstantInt>(CV1->getAggregateElement(i)))->getValue();
678 CV1E = Zext ? CV1E.zext(NewWidth) : CV1E.sext(NewWidth);
680 ConstantInt::get(NewVT->getElementType(), CV0E * CV1E));
682 return ReplaceInstUsesWith(CI, ConstantVector::get(NewElems));
685 // Couldn't simplify - cannonicalize constant to the RHS.
686 std::swap(Arg0, Arg1);
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()) {
695 return CastInst::CreateZExtOrBitCast(Arg0, II->getType());
697 return CastInst::CreateSExtOrBitCast(Arg0, II->getType());
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;
712 return EraseInstFromFunction(CI);
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)) {
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.
733 // If we found a non-intrinsic call, we can't remove the stack
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
744 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
745 return EraseInstFromFunction(CI);
750 return visitCallSite(II);
753 // InvokeInst simplification
755 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
756 return visitCallSite(&II);
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,
765 if (!CI->isLosslessCast())
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))
775 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
776 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
777 if (!SrcTy->isSized() || !DstTy->isSized())
779 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
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;
791 if (Value *With = Simplifier->optimizeCall(CI)) {
793 return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
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))
806 if (!isa<AllocaInst>(Underlying))
809 IntrinsicInst *InitTrampoline = 0;
810 for (Value::use_iterator I = TrampMem->use_begin(), E = TrampMem->use_end();
812 IntrinsicInst *II = dyn_cast<IntrinsicInst>(*I);
815 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
817 // More than one init_trampoline writes to this value. Give up.
822 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
823 // Allow any number of calls to adjust.trampoline.
828 // No call to init.trampoline found.
832 // Check that the alloca is being used in the expected way.
833 if (InitTrampoline->getOperand(0) != TrampMem)
836 return InitTrampoline;
839 static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
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)
850 if (Inst->mayWriteToMemory())
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.
860 static IntrinsicInst *FindInitTrampoline(Value *Callee) {
861 Callee = Callee->stripPointerCasts();
862 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
864 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
867 Value *TrampMem = AdjustTramp->getOperand(0);
869 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
871 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
876 // visitCallSite - Improvements for call and invoke instructions.
878 Instruction *InstCombiner::visitCallSite(CallSite CS) {
879 if (isAllocLikeFn(CS.getInstruction(), TLI))
880 return visitAllocSite(*CS.getInstruction());
882 bool Changed = false;
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))
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())),
902 // If OldCall does 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);
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()));
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()));
923 if (isa<InvokeInst>(CS.getInstruction())) {
924 // Can't remove an invoke because we cannot change the CFG.
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());
935 return EraseInstFromFunction(*CS.getInstruction());
938 if (IntrinsicInst *II = FindInitTrampoline(Callee))
939 return transformCallThroughTrampoline(CS, II);
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
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);
957 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
958 // Inline asm calls cannot throw - mark them 'nounwind'.
959 CS.setDoesNotThrow();
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);
973 return Changed ? CS.getInstruction() : 0;
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.
979 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
981 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
984 Instruction *Caller = CS.getInstruction();
985 const AttributeSet &CallerPAL = CS.getAttributes();
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.
991 FunctionType *FT = Callee->getFunctionType();
992 Type *OldRetTy = Caller->getType();
993 Type *NewRetTy = FT->getReturnType();
995 if (NewRetTy->isStructTy())
996 return false; // TODO: Handle multiple return values.
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.
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.
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.
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();
1028 if (PHINode *PN = dyn_cast<PHINode>(*UI))
1029 if (PN->getParent() == II->getNormalDest() ||
1030 PN->getParent() == II->getUnwindDest())
1034 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1035 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
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();
1042 if (!CastInst::isCastable(ActTy, ParamTy))
1043 return false; // Cannot transform this parameter value.
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.
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)
1057 Type *CurElTy = cast<PointerType>(ActTy)->getElementType();
1058 if (TD->getTypeAllocSize(CurElTy) !=
1059 TD->getTypeAllocSize(ParamPTy->getElementType()))
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;
1073 if (Callee->isDeclaration()) {
1074 // Do not delete arguments unless we have a function body.
1075 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
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
1081 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
1082 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
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())
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())
1103 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1104 if (PAttrs.hasIncompatibleWithVarArgsAttrs())
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);
1116 // Get any return attributes.
1117 AttrBuilder RAttrs = CallerPAL.getRetAttributes();
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));
1123 // Add the new return attributes.
1124 if (RAttrs.hasAttributes())
1126 AttributeWithIndex::get(AttributeSet::ReturnIndex,
1127 Attributes::get(FT->getContext(), RAttrs)));
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);
1135 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1136 false, ParamTy, false);
1137 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy));
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));
1146 // If the function takes more arguments than the call was taking, add them
1148 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1149 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
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";
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));
1166 Args.push_back(*AI);
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));
1177 Attributes FnAttrs = CallerPAL.getFnAttributes();
1178 if (FnAttrs.hasAttributes())
1179 attrVec.push_back(AttributeWithIndex::get(AttributeSet::FunctionIndex,
1182 if (NewRetTy->isVoidTy())
1183 Caller->setName(""); // Void type should not have a name.
1185 const AttributeSet &NewCallerPAL = AttributeSet::get(Callee->getContext(),
1189 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1190 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
1191 II->getUnwindDest(), Args);
1193 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1194 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1196 CallInst *CI = cast<CallInst>(Caller);
1197 NC = Builder->CreateCall(Callee, Args);
1199 if (CI->isTailCall())
1200 cast<CallInst>(NC)->setTailCall();
1201 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1202 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1205 // Insert a cast of the return type as necessary.
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());
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);
1220 // Otherwise, it's a call, just insert cast right after the call.
1221 InsertNewInstBefore(NC, *Caller);
1223 Worklist.AddUsersToWorkList(*Caller);
1225 NV = UndefValue::get(Caller->getType());
1229 if (!Caller->use_empty())
1230 ReplaceInstUsesWith(*Caller, NV);
1232 EraseInstFromFunction(*Caller);
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.
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 AttributeSet &Attrs = CS.getAttributes();
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))
1255 "transformCallThroughTrampoline called with incorrect CallSite.");
1257 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
1258 PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1259 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1261 const AttributeSet &NestAttrs = NestF->getAttributes();
1262 if (!NestAttrs.isEmpty()) {
1263 unsigned NestIdx = 1;
1265 Attributes NestAttr;
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.
1273 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1278 Instruction *Caller = CS.getInstruction();
1279 std::vector<Value*> NewArgs;
1280 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1282 SmallVector<AttributeWithIndex, 8> NewAttrs;
1283 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1285 // Insert the nest argument into the call argument list, which may
1286 // mean appending it. Likewise for attributes.
1288 // Add any result attributes.
1289 Attributes Attr = Attrs.getRetAttributes();
1290 if (Attr.hasAttributes())
1291 NewAttrs.push_back(AttributeWithIndex::get(AttributeSet::ReturnIndex,
1296 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
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));
1310 // Add the original argument and attributes.
1311 NewArgs.push_back(*I);
1312 Attr = Attrs.getParamAttributes(Idx);
1313 if (Attr.hasAttributes())
1315 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1321 // Add any function attributes.
1322 Attr = Attrs.getFnAttributes();
1323 if (Attr.hasAttributes())
1324 NewAttrs.push_back(AttributeWithIndex::get(AttributeSet::FunctionIndex,
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.
1331 std::vector<Type*> NewTypes;
1332 NewTypes.reserve(FTy->getNumParams()+1);
1334 // Insert the chain's type into the list of parameter types, which may
1335 // mean appending it.
1338 FunctionType::param_iterator I = FTy->param_begin(),
1339 E = FTy->param_end();
1343 // Add the chain's type.
1344 NewTypes.push_back(NestTy);
1349 // Add the original type.
1350 NewTypes.push_back(*I);
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,
1360 Constant *NewCallee =
1361 NestF->getType() == PointerType::getUnqual(NewFTy) ?
1362 NestF : ConstantExpr::getBitCast(NestF,
1363 PointerType::getUnqual(NewFTy));
1364 const AttributeSet &NewPAL = AttributeSet::get(FTy->getContext(), NewAttrs);
1366 Instruction *NewCaller;
1367 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1368 NewCaller = InvokeInst::Create(NewCallee,
1369 II->getNormalDest(), II->getUnwindDest(),
1371 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1372 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
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);
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();