blob: fc62bb0cf8491ce6c0df47b6b9a6163026db8693 [file] [log] [blame]
Chris Lattner753a2b42010-01-05 07:32:13 +00001//===- InstCombineCalls.cpp -----------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visitCall and visitInvoke functions.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/IntrinsicInst.h"
16#include "llvm/Support/CallSite.h"
17#include "llvm/Target/TargetData.h"
18#include "llvm/Analysis/MemoryBuiltins.h"
Eric Christopher27ceaa12010-03-06 10:50:38 +000019#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattner753a2b42010-01-05 07:32:13 +000020using namespace llvm;
21
22/// getPromotedType - Return the specified type promoted as it would be to pass
23/// though a va_arg area.
24static const Type *getPromotedType(const Type *Ty) {
25 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
26 if (ITy->getBitWidth() < 32)
27 return Type::getInt32Ty(Ty->getContext());
28 }
29 return Ty;
30}
31
32/// EnforceKnownAlignment - If the specified pointer points to an object that
33/// we control, modify the object's alignment to PrefAlign. This isn't
34/// often possible though. If alignment is important, a more reliable approach
35/// is to simply align all global variables and allocation instructions to
36/// their preferred alignment from the beginning.
37///
38static unsigned EnforceKnownAlignment(Value *V,
39 unsigned Align, unsigned PrefAlign) {
40
41 User *U = dyn_cast<User>(V);
42 if (!U) return Align;
43
44 switch (Operator::getOpcode(U)) {
45 default: break;
46 case Instruction::BitCast:
47 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
48 case Instruction::GetElementPtr: {
49 // If all indexes are zero, it is just the alignment of the base pointer.
50 bool AllZeroOperands = true;
51 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
52 if (!isa<Constant>(*i) ||
53 !cast<Constant>(*i)->isNullValue()) {
54 AllZeroOperands = false;
55 break;
56 }
57
58 if (AllZeroOperands) {
59 // Treat this like a bitcast.
60 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
61 }
Chris Lattner2d4b8ee2010-04-28 00:31:12 +000062 return Align;
63 }
64 case Instruction::Alloca: {
65 AllocaInst *AI = cast<AllocaInst>(V);
66 // If there is a requested alignment and if this is an alloca, round up.
67 if (AI->getAlignment() >= PrefAlign)
68 return AI->getAlignment();
69 AI->setAlignment(PrefAlign);
70 return PrefAlign;
Chris Lattner753a2b42010-01-05 07:32:13 +000071 }
72 }
73
74 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
75 // If there is a large requested alignment and we can, bump up the alignment
76 // of the global.
Chris Lattner2d4b8ee2010-04-28 00:31:12 +000077 if (GV->isDeclaration()) return Align;
78
79 if (GV->getAlignment() >= PrefAlign)
80 return GV->getAlignment();
81 // We can only increase the alignment of the global if it has no alignment
82 // specified or if it is not assigned a section. If it is assigned a
83 // section, the global could be densely packed with other objects in the
84 // section, increasing the alignment could cause padding issues.
85 if (!GV->hasSection() || GV->getAlignment() == 0)
86 GV->setAlignment(PrefAlign);
87 return GV->getAlignment();
Chris Lattner753a2b42010-01-05 07:32:13 +000088 }
89
90 return Align;
91}
92
93/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
94/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
95/// and it is more than the alignment of the ultimate object, see if we can
96/// increase the alignment of the ultimate object, making this check succeed.
97unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
98 unsigned PrefAlign) {
99 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
100 sizeof(PrefAlign) * CHAR_BIT;
101 APInt Mask = APInt::getAllOnesValue(BitWidth);
102 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
103 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
104 unsigned TrailZ = KnownZero.countTrailingOnes();
105 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
106
107 if (PrefAlign > Align)
108 Align = EnforceKnownAlignment(V, Align, PrefAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000109
Chris Lattner753a2b42010-01-05 07:32:13 +0000110 // We don't need to make any adjustment.
111 return Align;
112}
113
114Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Gabor Greifbcda85c2010-06-24 13:54:33 +0000115 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getArgOperand(0));
116 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getArgOperand(1));
Chris Lattner753a2b42010-01-05 07:32:13 +0000117 unsigned MinAlign = std::min(DstAlign, SrcAlign);
118 unsigned CopyAlign = MI->getAlignment();
119
120 if (CopyAlign < MinAlign) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000121 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Chris Lattner753a2b42010-01-05 07:32:13 +0000122 MinAlign, false));
123 return MI;
124 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000125
Chris Lattner753a2b42010-01-05 07:32:13 +0000126 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
127 // load/store.
Gabor Greifbcda85c2010-06-24 13:54:33 +0000128 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Chris Lattner753a2b42010-01-05 07:32:13 +0000129 if (MemOpLength == 0) return 0;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000130
Chris Lattner753a2b42010-01-05 07:32:13 +0000131 // Source and destination pointer types are always "i8*" for intrinsic. See
132 // if the size is something we can handle with a single primitive load/store.
133 // A single load+store correctly handles overlapping memory in the memmove
134 // case.
135 unsigned Size = MemOpLength->getZExtValue();
136 if (Size == 0) return MI; // Delete this mem transfer.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000137
Chris Lattner753a2b42010-01-05 07:32:13 +0000138 if (Size > 8 || (Size&(Size-1)))
139 return 0; // If not 1/2/4/8 bytes, exit.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000140
Chris Lattner753a2b42010-01-05 07:32:13 +0000141 // Use an integer load+store unless we can find something better.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000142 unsigned SrcAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +0000143 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greif4ec22582010-04-16 15:33:14 +0000144 unsigned DstAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +0000145 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000146
147 const IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
148 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
149 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000150
Chris Lattner753a2b42010-01-05 07:32:13 +0000151 // Memcpy forces the use of i8* for the source and destination. That means
152 // that if you're using memcpy to move one double around, you'll get a cast
153 // from double* to i8*. We'd much rather use a double load+store rather than
154 // an i64 load+store, here because this improves the odds that the source or
155 // dest address will be promotable. See if we can find a better type than the
156 // integer datatype.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000157 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
158 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000159 const Type *SrcETy = cast<PointerType>(StrippedDest->getType())
160 ->getElementType();
161 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
162 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
163 // down through these levels if so.
164 while (!SrcETy->isSingleValueType()) {
165 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
166 if (STy->getNumElements() == 1)
167 SrcETy = STy->getElementType(0);
168 else
169 break;
170 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
171 if (ATy->getNumElements() == 1)
172 SrcETy = ATy->getElementType();
173 else
174 break;
175 } else
176 break;
177 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000178
Mon P Wang20adc9d2010-04-04 03:10:48 +0000179 if (SrcETy->isSingleValueType()) {
180 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
181 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
182 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000183 }
184 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000185
186
Chris Lattner753a2b42010-01-05 07:32:13 +0000187 // If the memcpy/memmove provides better alignment info than we can
188 // infer, use it.
189 SrcAlign = std::max(SrcAlign, CopyAlign);
190 DstAlign = std::max(DstAlign, CopyAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000191
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000192 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
193 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000194 Instruction *L = new LoadInst(Src, "tmp", MI->isVolatile(), SrcAlign);
Chris Lattner753a2b42010-01-05 07:32:13 +0000195 InsertNewInstBefore(L, *MI);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000196 InsertNewInstBefore(new StoreInst(L, Dest, MI->isVolatile(), DstAlign),
197 *MI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000198
199 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000200 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000201 return MI;
202}
203
204Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
205 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
206 if (MI->getAlignment() < Alignment) {
207 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
208 Alignment, false));
209 return MI;
210 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000211
Chris Lattner753a2b42010-01-05 07:32:13 +0000212 // Extract the length and alignment and fill if they are constant.
213 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
214 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000215 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Chris Lattner753a2b42010-01-05 07:32:13 +0000216 return 0;
217 uint64_t Len = LenC->getZExtValue();
218 Alignment = MI->getAlignment();
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000219
Chris Lattner753a2b42010-01-05 07:32:13 +0000220 // If the length is zero, this is a no-op
221 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000222
Chris Lattner753a2b42010-01-05 07:32:13 +0000223 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
224 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
225 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000226
Chris Lattner753a2b42010-01-05 07:32:13 +0000227 Value *Dest = MI->getDest();
228 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
229
230 // Alignment 0 is identity for alignment 1 for memset, but not store.
231 if (Alignment == 0) Alignment = 1;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000232
Chris Lattner753a2b42010-01-05 07:32:13 +0000233 // Extract the fill value and store.
234 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
235 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
236 Dest, false, Alignment), *MI);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000237
Chris Lattner753a2b42010-01-05 07:32:13 +0000238 // Set the size of the copy to 0, it will be deleted on the next iteration.
239 MI->setLength(Constant::getNullValue(LenC->getType()));
240 return MI;
241 }
242
243 return 0;
244}
245
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000246/// visitCallInst - CallInst simplification. This mostly only handles folding
Chris Lattner753a2b42010-01-05 07:32:13 +0000247/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
248/// the heavy lifting.
249///
250Instruction *InstCombiner::visitCallInst(CallInst &CI) {
251 if (isFreeCall(&CI))
252 return visitFree(CI);
Duncan Sands1d9b9732010-05-27 19:09:06 +0000253 if (isMalloc(&CI))
254 return visitMalloc(CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000255
256 // If the caller function is nounwind, mark the call as nounwind, even if the
257 // callee isn't.
258 if (CI.getParent()->getParent()->doesNotThrow() &&
259 !CI.doesNotThrow()) {
260 CI.setDoesNotThrow();
261 return &CI;
262 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000263
Chris Lattner753a2b42010-01-05 07:32:13 +0000264 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
265 if (!II) return visitCallSite(&CI);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000266
Chris Lattner753a2b42010-01-05 07:32:13 +0000267 // Intrinsics cannot occur in an invoke, so handle them here instead of in
268 // visitCallSite.
269 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
270 bool Changed = false;
271
272 // memmove/cpy/set of zero bytes is a noop.
273 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
274 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
275
276 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
277 if (CI->getZExtValue() == 1) {
278 // Replace the instruction with just byte operations. We would
279 // transform other cases to loads/stores, but we don't know if
280 // alignment is sufficient.
281 }
282 }
283
284 // If we have a memmove and the source operation is a constant global,
285 // then the source and dest pointers can't alias, so we can change this
286 // into a call to memcpy.
287 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
288 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
289 if (GVSrc->isConstant()) {
Eric Christopher551754c2010-04-16 23:37:20 +0000290 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner753a2b42010-01-05 07:32:13 +0000291 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Gabor Greifc310fcc2010-06-24 13:42:49 +0000292 const Type *Tys[3] = { CI.getArgOperand(0)->getType(),
293 CI.getArgOperand(1)->getType(),
294 CI.getArgOperand(2)->getType() };
295 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys, 3));
Chris Lattner753a2b42010-01-05 07:32:13 +0000296 Changed = true;
297 }
298 }
299
300 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
301 // memmove(x,x,size) -> noop.
302 if (MTI->getSource() == MTI->getDest())
303 return EraseInstFromFunction(CI);
Eric Christopher551754c2010-04-16 23:37:20 +0000304 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000305
Eric Christopher551754c2010-04-16 23:37:20 +0000306 // If we can determine a pointer alignment that is bigger than currently
307 // set, update the alignment.
308 if (isa<MemTransferInst>(MI)) {
309 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner753a2b42010-01-05 07:32:13 +0000310 return I;
311 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
312 if (Instruction *I = SimplifyMemSet(MSI))
313 return I;
314 }
Gabor Greifc310fcc2010-06-24 13:42:49 +0000315
Chris Lattner753a2b42010-01-05 07:32:13 +0000316 if (Changed) return II;
317 }
Eric Christopher551754c2010-04-16 23:37:20 +0000318
Chris Lattner753a2b42010-01-05 07:32:13 +0000319 switch (II->getIntrinsicID()) {
320 default: break;
Eric Christopher415326b2010-02-09 21:24:27 +0000321 case Intrinsic::objectsize: {
Eric Christopher26d0e892010-02-11 01:48:54 +0000322 // We need target data for just about everything so depend on it.
Eric Christopher415326b2010-02-09 21:24:27 +0000323 if (!TD) break;
Eric Christopher26d0e892010-02-11 01:48:54 +0000324
Evan Chenga8623262010-03-05 20:47:23 +0000325 const Type *ReturnTy = CI.getType();
Gabor Greifcea7ac72010-06-24 12:58:35 +0000326 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Evan Chenga8623262010-03-05 20:47:23 +0000327
Eric Christopher26d0e892010-02-11 01:48:54 +0000328 // Get to the real allocated thing and offset as fast as possible.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000329 Value *Op1 = II->getArgOperand(0)->stripPointerCasts();
Eric Christopher415326b2010-02-09 21:24:27 +0000330
Eric Christopher26d0e892010-02-11 01:48:54 +0000331 // If we've stripped down to a single global variable that we
332 // can know the size of then just return that.
Eric Christopher415326b2010-02-09 21:24:27 +0000333 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
334 if (GV->hasDefinitiveInitializer()) {
335 Constant *C = GV->getInitializer();
Evan Chenga8623262010-03-05 20:47:23 +0000336 uint64_t GlobalSize = TD->getTypeAllocSize(C->getType());
337 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, GlobalSize));
Eric Christopher415326b2010-02-09 21:24:27 +0000338 } else {
Evan Chenga8623262010-03-05 20:47:23 +0000339 // Can't determine size of the GV.
Eric Christopher415326b2010-02-09 21:24:27 +0000340 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
341 return ReplaceInstUsesWith(CI, RetVal);
342 }
Evan Chenga8623262010-03-05 20:47:23 +0000343 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
344 // Get alloca size.
345 if (AI->getAllocatedType()->isSized()) {
346 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
347 if (AI->isArrayAllocation()) {
348 const ConstantInt *C = dyn_cast<ConstantInt>(AI->getArraySize());
349 if (!C) break;
350 AllocaSize *= C->getZExtValue();
351 }
352 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, AllocaSize));
353 }
Evan Cheng687fed32010-03-08 22:54:36 +0000354 } else if (CallInst *MI = extractMallocCall(Op1)) {
355 const Type* MallocType = getMallocAllocatedType(MI);
356 // Get alloca size.
357 if (MallocType && MallocType->isSized()) {
358 if (Value *NElems = getMallocArraySize(MI, TD, true)) {
359 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
360 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy,
361 (NElements->getZExtValue() * TD->getTypeAllocSize(MallocType))));
362 }
363 }
Evan Chenga8623262010-03-05 20:47:23 +0000364 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
Eric Christopher26d0e892010-02-11 01:48:54 +0000365 // Only handle constant GEPs here.
366 if (CE->getOpcode() != Instruction::GetElementPtr) break;
367 GEPOperator *GEP = cast<GEPOperator>(CE);
368
Eric Christopherdfdddd82010-02-11 17:44:04 +0000369 // Make sure we're not a constant offset from an external
370 // global.
371 Value *Operand = GEP->getPointerOperand();
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000372 Operand = Operand->stripPointerCasts();
Eric Christopherdfdddd82010-02-11 17:44:04 +0000373 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
374 if (!GV->hasDefinitiveInitializer()) break;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000375
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000376 // Get what we're pointing to and its size.
377 const PointerType *BaseType =
Eric Christopherdfdddd82010-02-11 17:44:04 +0000378 cast<PointerType>(Operand->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000379 uint64_t Size = TD->getTypeAllocSize(BaseType->getElementType());
Eric Christopher26d0e892010-02-11 01:48:54 +0000380
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000381 // Get the current byte offset into the thing. Use the original
382 // operand in case we're looking through a bitcast.
Eric Christopher26d0e892010-02-11 01:48:54 +0000383 SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000384 const PointerType *OffsetType =
385 cast<PointerType>(GEP->getPointerOperand()->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000386 uint64_t Offset = TD->getIndexedOffset(OffsetType, &Ops[0], Ops.size());
Eric Christopher26d0e892010-02-11 01:48:54 +0000387
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000388 if (Size < Offset) {
389 // Out of bound reference? Negative index normalized to large
390 // index? Just return "I don't know".
391 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
392 return ReplaceInstUsesWith(CI, RetVal);
393 }
Eric Christopher26d0e892010-02-11 01:48:54 +0000394
395 Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
396 return ReplaceInstUsesWith(CI, RetVal);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000397 }
Evan Chenga8623262010-03-05 20:47:23 +0000398
399 // Do not return "I don't know" here. Later optimization passes could
400 // make it possible to evaluate objectsize to a constant.
Evan Chengf79d6242010-03-05 01:22:47 +0000401 break;
Eric Christopher415326b2010-02-09 21:24:27 +0000402 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000403 case Intrinsic::bswap:
404 // bswap(bswap(x)) -> x
Gabor Greifcea7ac72010-06-24 12:58:35 +0000405 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getArgOperand(0)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000406 if (Operand->getIntrinsicID() == Intrinsic::bswap)
Gabor Greifcea7ac72010-06-24 12:58:35 +0000407 return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000408
Chris Lattner753a2b42010-01-05 07:32:13 +0000409 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Gabor Greifcea7ac72010-06-24 12:58:35 +0000410 if (TruncInst *TI = dyn_cast<TruncInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000411 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
412 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
413 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
414 TI->getType()->getPrimitiveSizeInBits();
415 Value *CV = ConstantInt::get(Operand->getType(), C);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000416 Value *V = Builder->CreateLShr(Operand->getArgOperand(0), CV);
Chris Lattner753a2b42010-01-05 07:32:13 +0000417 return new TruncInst(V, TI->getType());
418 }
419 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000420
Chris Lattner753a2b42010-01-05 07:32:13 +0000421 break;
422 case Intrinsic::powi:
Gabor Greifcea7ac72010-06-24 12:58:35 +0000423 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000424 // powi(x, 0) -> 1.0
425 if (Power->isZero())
426 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
427 // powi(x, 1) -> x
428 if (Power->isOne())
Gabor Greifcea7ac72010-06-24 12:58:35 +0000429 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000430 // powi(x, -1) -> 1/x
431 if (Power->isAllOnesValue())
432 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greifcea7ac72010-06-24 12:58:35 +0000433 II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000434 }
435 break;
436 case Intrinsic::cttz: {
437 // If all bits below the first known one are known zero,
438 // this value is constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000439 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000440 uint32_t BitWidth = IT->getBitWidth();
441 APInt KnownZero(BitWidth, 0);
442 APInt KnownOne(BitWidth, 0);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000443 ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidth),
Chris Lattner753a2b42010-01-05 07:32:13 +0000444 KnownZero, KnownOne);
445 unsigned TrailingZeros = KnownOne.countTrailingZeros();
446 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
447 if ((Mask & KnownZero) == Mask)
448 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
449 APInt(BitWidth, TrailingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000450
Chris Lattner753a2b42010-01-05 07:32:13 +0000451 }
452 break;
453 case Intrinsic::ctlz: {
454 // If all bits above the first known one are known zero,
455 // this value is constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000456 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000457 uint32_t BitWidth = IT->getBitWidth();
458 APInt KnownZero(BitWidth, 0);
459 APInt KnownOne(BitWidth, 0);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000460 ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidth),
Chris Lattner753a2b42010-01-05 07:32:13 +0000461 KnownZero, KnownOne);
462 unsigned LeadingZeros = KnownOne.countLeadingZeros();
463 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
464 if ((Mask & KnownZero) == Mask)
465 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
466 APInt(BitWidth, LeadingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000467
Chris Lattner753a2b42010-01-05 07:32:13 +0000468 }
469 break;
470 case Intrinsic::uadd_with_overflow: {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000471 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
472 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000473 uint32_t BitWidth = IT->getBitWidth();
474 APInt Mask = APInt::getSignBit(BitWidth);
475 APInt LHSKnownZero(BitWidth, 0);
476 APInt LHSKnownOne(BitWidth, 0);
477 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
478 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
479 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
480
481 if (LHSKnownNegative || LHSKnownPositive) {
482 APInt RHSKnownZero(BitWidth, 0);
483 APInt RHSKnownOne(BitWidth, 0);
484 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
485 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
486 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
487 if (LHSKnownNegative && RHSKnownNegative) {
488 // The sign bit is set in both cases: this MUST overflow.
489 // Create a simple add instruction, and insert it into the struct.
490 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
491 Worklist.Add(Add);
492 Constant *V[] = {
493 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
494 };
495 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
496 return InsertValueInst::Create(Struct, Add, 0);
497 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000498
Chris Lattner753a2b42010-01-05 07:32:13 +0000499 if (LHSKnownPositive && RHSKnownPositive) {
500 // The sign bit is clear in both cases: this CANNOT overflow.
501 // Create a simple add instruction, and insert it into the struct.
502 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
503 Worklist.Add(Add);
504 Constant *V[] = {
505 UndefValue::get(LHS->getType()),
506 ConstantInt::getFalse(II->getContext())
507 };
508 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
509 return InsertValueInst::Create(Struct, Add, 0);
510 }
511 }
512 }
513 // FALL THROUGH uadd into sadd
514 case Intrinsic::sadd_with_overflow:
515 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000516 if (isa<Constant>(II->getArgOperand(0)) &&
517 !isa<Constant>(II->getArgOperand(1))) {
518 Value *LHS = II->getArgOperand(0);
519 II->setArgOperand(0, II->getArgOperand(1));
520 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000521 return II;
522 }
523
524 // X + undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000525 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000526 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000527
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000528 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000529 // X + 0 -> {X, false}
530 if (RHS->isZero()) {
531 Constant *V[] = {
Gabor Greifa9b23132010-04-20 13:13:04 +0000532 UndefValue::get(II->getCalledValue()->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000533 ConstantInt::getFalse(II->getContext())
534 };
535 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000536 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000537 }
538 }
539 break;
540 case Intrinsic::usub_with_overflow:
541 case Intrinsic::ssub_with_overflow:
542 // undef - X -> undef
543 // X - undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000544 if (isa<UndefValue>(II->getArgOperand(0)) ||
545 isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000546 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000547
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000548 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000549 // X - 0 -> {X, false}
550 if (RHS->isZero()) {
551 Constant *V[] = {
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000552 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000553 ConstantInt::getFalse(II->getContext())
554 };
555 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000556 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000557 }
558 }
559 break;
560 case Intrinsic::umul_with_overflow:
561 case Intrinsic::smul_with_overflow:
562 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000563 if (isa<Constant>(II->getArgOperand(0)) &&
564 !isa<Constant>(II->getArgOperand(1))) {
565 Value *LHS = II->getArgOperand(0);
566 II->setArgOperand(0, II->getArgOperand(1));
567 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000568 return II;
569 }
570
571 // X * undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000572 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000573 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000574
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000575 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000576 // X*0 -> {0, false}
577 if (RHSI->isZero())
578 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000579
Chris Lattner753a2b42010-01-05 07:32:13 +0000580 // X * 1 -> {X, false}
581 if (RHSI->equalsInt(1)) {
582 Constant *V[] = {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000583 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000584 ConstantInt::getFalse(II->getContext())
585 };
586 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000587 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000588 }
589 }
590 break;
591 case Intrinsic::ppc_altivec_lvx:
592 case Intrinsic::ppc_altivec_lvxl:
593 case Intrinsic::x86_sse_loadu_ps:
594 case Intrinsic::x86_sse2_loadu_pd:
595 case Intrinsic::x86_sse2_loadu_dq:
596 // Turn PPC lvx -> load if the pointer is known aligned.
597 // Turn X86 loadups -> load if the pointer is known aligned.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000598 if (GetOrEnforceKnownAlignment(II->getArgOperand(0), 16) >= 16) {
599 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner753a2b42010-01-05 07:32:13 +0000600 PointerType::getUnqual(II->getType()));
601 return new LoadInst(Ptr);
602 }
603 break;
604 case Intrinsic::ppc_altivec_stvx:
605 case Intrinsic::ppc_altivec_stvxl:
606 // Turn stvx -> store if the pointer is known aligned.
Gabor Greif2f1ab742010-06-24 15:51:11 +0000607 if (GetOrEnforceKnownAlignment(II->getArgOperand(1), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000608 const Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000609 PointerType::getUnqual(II->getArgOperand(0)->getType());
610 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
611 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000612 }
613 break;
614 case Intrinsic::x86_sse_storeu_ps:
615 case Intrinsic::x86_sse2_storeu_pd:
616 case Intrinsic::x86_sse2_storeu_dq:
617 // Turn X86 storeu -> store if the pointer is known aligned.
Gabor Greif2f1ab742010-06-24 15:51:11 +0000618 if (GetOrEnforceKnownAlignment(II->getArgOperand(0), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000619 const Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000620 PointerType::getUnqual(II->getArgOperand(1)->getType());
621 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
622 return new StoreInst(II->getArgOperand(1), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000623 }
624 break;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000625
Chris Lattner753a2b42010-01-05 07:32:13 +0000626 case Intrinsic::x86_sse_cvttss2si: {
627 // These intrinsics only demands the 0th element of its input vector. If
628 // we can simplify the input based on that, do so now.
629 unsigned VWidth =
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000630 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
Chris Lattner753a2b42010-01-05 07:32:13 +0000631 APInt DemandedElts(VWidth, 1);
632 APInt UndefElts(VWidth, 0);
Gabor Greifa3997812010-07-22 10:37:47 +0000633 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
634 DemandedElts, UndefElts)) {
Gabor Greifa90c5c72010-06-28 16:50:57 +0000635 II->setArgOperand(0, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000636 return II;
637 }
638 break;
639 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000640
Chris Lattner753a2b42010-01-05 07:32:13 +0000641 case Intrinsic::ppc_altivec_vperm:
642 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000643 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getArgOperand(2))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000644 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000645
Chris Lattner753a2b42010-01-05 07:32:13 +0000646 // Check that all of the elements are integer constants or undefs.
647 bool AllEltsOk = true;
648 for (unsigned i = 0; i != 16; ++i) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000649 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
Chris Lattner753a2b42010-01-05 07:32:13 +0000650 !isa<UndefValue>(Mask->getOperand(i))) {
651 AllEltsOk = false;
652 break;
653 }
654 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000655
Chris Lattner753a2b42010-01-05 07:32:13 +0000656 if (AllEltsOk) {
657 // Cast the input vectors to byte vectors.
Gabor Greifa3997812010-07-22 10:37:47 +0000658 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
659 Mask->getType());
660 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
661 Mask->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000662 Value *Result = UndefValue::get(Op0->getType());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000663
Chris Lattner753a2b42010-01-05 07:32:13 +0000664 // Only extract each element once.
665 Value *ExtractedElts[32];
666 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000667
Chris Lattner753a2b42010-01-05 07:32:13 +0000668 for (unsigned i = 0; i != 16; ++i) {
669 if (isa<UndefValue>(Mask->getOperand(i)))
670 continue;
671 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
672 Idx &= 31; // Match the hardware behavior.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000673
Chris Lattner753a2b42010-01-05 07:32:13 +0000674 if (ExtractedElts[Idx] == 0) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000675 ExtractedElts[Idx] =
676 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner753a2b42010-01-05 07:32:13 +0000677 ConstantInt::get(Type::getInt32Ty(II->getContext()),
678 Idx&15, false), "tmp");
679 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000680
Chris Lattner753a2b42010-01-05 07:32:13 +0000681 // Insert this value into the result vector.
682 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
683 ConstantInt::get(Type::getInt32Ty(II->getContext()),
684 i, false), "tmp");
685 }
686 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
687 }
688 }
689 break;
690
691 case Intrinsic::stackrestore: {
692 // If the save is right next to the restore, remove the restore. This can
693 // happen when variable allocas are DCE'd.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000694 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000695 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
696 BasicBlock::iterator BI = SS;
697 if (&*++BI == II)
698 return EraseInstFromFunction(CI);
699 }
700 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000701
Chris Lattner753a2b42010-01-05 07:32:13 +0000702 // Scan down this block to see if there is another stack restore in the
703 // same block without an intervening call/alloca.
704 BasicBlock::iterator BI = II;
705 TerminatorInst *TI = II->getParent()->getTerminator();
706 bool CannotRemove = false;
707 for (++BI; &*BI != TI; ++BI) {
708 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
709 CannotRemove = true;
710 break;
711 }
712 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
713 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
714 // If there is a stackrestore below this one, remove this one.
715 if (II->getIntrinsicID() == Intrinsic::stackrestore)
716 return EraseInstFromFunction(CI);
717 // Otherwise, ignore the intrinsic.
718 } else {
719 // If we found a non-intrinsic call, we can't remove the stack
720 // restore.
721 CannotRemove = true;
722 break;
723 }
724 }
725 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000726
Chris Lattner753a2b42010-01-05 07:32:13 +0000727 // If the stack restore is in a return/unwind block and if there are no
728 // allocas or calls between the restore and the return, nuke the restore.
729 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
730 return EraseInstFromFunction(CI);
731 break;
732 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000733 }
734
735 return visitCallSite(II);
736}
737
738// InvokeInst simplification
739//
740Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
741 return visitCallSite(&II);
742}
743
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000744/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000745/// passed through the varargs area, we can eliminate the use of the cast.
746static bool isSafeToEliminateVarargsCast(const CallSite CS,
747 const CastInst * const CI,
748 const TargetData * const TD,
749 const int ix) {
750 if (!CI->isLosslessCast())
751 return false;
752
753 // The size of ByVal arguments is derived from the type, so we
754 // can't change to a type with a different size. If the size were
755 // passed explicitly we could avoid this check.
756 if (!CS.paramHasAttr(ix, Attribute::ByVal))
757 return true;
758
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000759 const Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000760 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
761 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
762 if (!SrcTy->isSized() || !DstTy->isSized())
763 return false;
764 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
765 return false;
766 return true;
767}
768
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000769namespace {
770class InstCombineFortifiedLibCalls : public SimplifyFortifiedLibCalls {
771 InstCombiner *IC;
772protected:
773 void replaceCall(Value *With) {
774 NewInstruction = IC->ReplaceInstUsesWith(*CI, With);
775 }
776 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
Gabor Greifa3997812010-07-22 10:37:47 +0000777 if (ConstantInt *SizeCI =
778 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000779 if (SizeCI->isAllOnesValue())
780 return true;
781 if (isString)
782 return SizeCI->getZExtValue() >=
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000783 GetStringLength(CI->getArgOperand(SizeArgOp));
Gabor Greifa3997812010-07-22 10:37:47 +0000784 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
785 CI->getArgOperand(SizeArgOp)))
Evan Cheng9d8f0022010-03-23 06:06:09 +0000786 return SizeCI->getZExtValue() >= Arg->getZExtValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000787 }
788 return false;
789 }
790public:
791 InstCombineFortifiedLibCalls(InstCombiner *IC) : IC(IC), NewInstruction(0) { }
792 Instruction *NewInstruction;
793};
794} // end anonymous namespace
795
Eric Christopher27ceaa12010-03-06 10:50:38 +0000796// Try to fold some different type of calls here.
797// Currently we're only working with the checking functions, memcpy_chk,
798// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
799// strcat_chk and strncat_chk.
800Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData *TD) {
801 if (CI->getCalledFunction() == 0) return 0;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000802
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000803 InstCombineFortifiedLibCalls Simplifier(this);
804 Simplifier.fold(CI, TD);
805 return Simplifier.NewInstruction;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000806}
807
Chris Lattner753a2b42010-01-05 07:32:13 +0000808// visitCallSite - Improvements for call and invoke instructions.
809//
810Instruction *InstCombiner::visitCallSite(CallSite CS) {
811 bool Changed = false;
812
813 // If the callee is a constexpr cast of a function, attempt to move the cast
814 // to the arguments of the call/invoke.
815 if (transformConstExprCastCall(CS)) return 0;
816
817 Value *Callee = CS.getCalledValue();
818
819 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000820 // If the call and callee calling conventions don't match, this call must
821 // be unreachable, as the call is undefined.
822 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
823 // Only do this for calls to a function with a body. A prototype may
824 // not actually end up matching the implementation's calling conv for a
825 // variety of reasons (e.g. it may be written in assembly).
826 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000827 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000828 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000829 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000830 OldCall);
831 // If OldCall dues not return void then replaceAllUsesWith undef.
832 // This allows ValueHandlers and custom metadata to adjust itself.
833 if (!OldCall->getType()->isVoidTy())
834 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000835 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000836 return EraseInstFromFunction(*OldCall);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000837
Chris Lattner830f3f22010-02-01 18:04:58 +0000838 // We cannot remove an invoke, because it would change the CFG, just
839 // change the callee to a null pointer.
Gabor Greif654c06f2010-03-20 21:00:25 +0000840 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner830f3f22010-02-01 18:04:58 +0000841 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000842 return 0;
843 }
844
845 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
846 // This instruction is not reachable, just remove it. We insert a store to
847 // undef so that we know that this code is not reachable, despite the fact
848 // that we can't modify the CFG here.
849 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
850 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
851 CS.getInstruction());
852
Gabor Greifcea7ac72010-06-24 12:58:35 +0000853 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner753a2b42010-01-05 07:32:13 +0000854 // This allows ValueHandlers and custom metadata to adjust itself.
855 if (!CS.getInstruction()->getType()->isVoidTy())
856 CS.getInstruction()->
857 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
858
859 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
860 // Don't break the CFG, insert a dummy cond branch.
861 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
862 ConstantInt::getTrue(Callee->getContext()), II);
863 }
864 return EraseInstFromFunction(*CS.getInstruction());
865 }
866
867 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
868 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
869 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
870 return transformCallThroughTrampoline(CS);
871
872 const PointerType *PTy = cast<PointerType>(Callee->getType());
873 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
874 if (FTy->isVarArg()) {
875 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
876 // See if we can optimize any arguments passed through the varargs area of
877 // the call.
878 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
879 E = CS.arg_end(); I != E; ++I, ++ix) {
880 CastInst *CI = dyn_cast<CastInst>(*I);
881 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
882 *I = CI->getOperand(0);
883 Changed = true;
884 }
885 }
886 }
887
888 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
889 // Inline asm calls cannot throw - mark them 'nounwind'.
890 CS.setDoesNotThrow();
891 Changed = true;
892 }
893
Eric Christopher27ceaa12010-03-06 10:50:38 +0000894 // Try to optimize the call if possible, we require TargetData for most of
895 // this. None of these calls are seen as possibly dead so go ahead and
896 // delete the instruction now.
897 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
898 Instruction *I = tryOptimizeCall(CI, TD);
Eric Christopher7b323a32010-03-06 10:59:25 +0000899 // If we changed something return the result, etc. Otherwise let
900 // the fallthrough check.
901 if (I) return EraseInstFromFunction(*I);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000902 }
903
Chris Lattner753a2b42010-01-05 07:32:13 +0000904 return Changed ? CS.getInstruction() : 0;
905}
906
907// transformConstExprCastCall - If the callee is a constexpr cast of a function,
908// attempt to move the cast to the arguments of the call/invoke.
909//
910bool InstCombiner::transformConstExprCastCall(CallSite CS) {
911 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
912 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000913 if (CE->getOpcode() != Instruction::BitCast ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000914 !isa<Function>(CE->getOperand(0)))
915 return false;
916 Function *Callee = cast<Function>(CE->getOperand(0));
917 Instruction *Caller = CS.getInstruction();
918 const AttrListPtr &CallerPAL = CS.getAttributes();
919
920 // Okay, this is a cast from a function to a different type. Unless doing so
921 // would cause a type conversion of one of our arguments, change this call to
922 // be a direct call with arguments casted to the appropriate types.
923 //
924 const FunctionType *FT = Callee->getFunctionType();
925 const Type *OldRetTy = Caller->getType();
926 const Type *NewRetTy = FT->getReturnType();
927
Duncan Sands1df98592010-02-16 11:11:14 +0000928 if (NewRetTy->isStructTy())
Chris Lattner753a2b42010-01-05 07:32:13 +0000929 return false; // TODO: Handle multiple return values.
930
931 // Check to see if we are changing the return type...
932 if (OldRetTy != NewRetTy) {
933 if (Callee->isDeclaration() &&
934 // Conversion is ok if changing from one pointer type to another or from
935 // a pointer to an integer of the same size.
Duncan Sands1df98592010-02-16 11:11:14 +0000936 !((OldRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000937 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +0000938 (NewRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000939 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
940 return false; // Cannot transform this return value.
941
942 if (!Caller->use_empty() &&
943 // void -> non-void is handled specially
944 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
945 return false; // Cannot transform this return value.
946
947 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
948 Attributes RAttrs = CallerPAL.getRetAttributes();
949 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
950 return false; // Attribute not compatible with transformed value.
951 }
952
953 // If the callsite is an invoke instruction, and the return value is used by
954 // a PHI node in a successor, we cannot change the return type of the call
955 // because there is no place to put the cast instruction (without breaking
956 // the critical edge). Bail out in this case.
957 if (!Caller->use_empty())
958 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
959 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
960 UI != E; ++UI)
961 if (PHINode *PN = dyn_cast<PHINode>(*UI))
962 if (PN->getParent() == II->getNormalDest() ||
963 PN->getParent() == II->getUnwindDest())
964 return false;
965 }
966
967 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
968 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
969
970 CallSite::arg_iterator AI = CS.arg_begin();
971 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
972 const Type *ParamTy = FT->getParamType(i);
973 const Type *ActTy = (*AI)->getType();
974
975 if (!CastInst::isCastable(ActTy, ParamTy))
976 return false; // Cannot transform this parameter value.
977
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000978 if (CallerPAL.getParamAttributes(i + 1)
Chris Lattner753a2b42010-01-05 07:32:13 +0000979 & Attribute::typeIncompatible(ParamTy))
980 return false; // Attribute not compatible with transformed value.
981
982 // Converting from one pointer type to another or between a pointer and an
983 // integer of the same size is safe even if we do not have a body.
984 bool isConvertible = ActTy == ParamTy ||
Duncan Sands1df98592010-02-16 11:11:14 +0000985 (TD && ((ParamTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000986 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +0000987 (ActTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000988 ActTy == TD->getIntPtrType(Caller->getContext()))));
989 if (Callee->isDeclaration() && !isConvertible) return false;
990 }
991
992 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
993 Callee->isDeclaration())
994 return false; // Do not delete arguments unless we have a function body.
995
996 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
997 !CallerPAL.isEmpty())
998 // In this case we have more arguments than the new function type, but we
999 // won't be dropping them. Check that these extra arguments have attributes
1000 // that are compatible with being a vararg call argument.
1001 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1002 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1003 break;
1004 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1005 if (PAttrs & Attribute::VarArgsIncompatible)
1006 return false;
1007 }
1008
1009 // Okay, we decided that this is a safe thing to do: go ahead and start
1010 // inserting cast instructions as necessary...
1011 std::vector<Value*> Args;
1012 Args.reserve(NumActualArgs);
1013 SmallVector<AttributeWithIndex, 8> attrVec;
1014 attrVec.reserve(NumCommonArgs);
1015
1016 // Get any return attributes.
1017 Attributes RAttrs = CallerPAL.getRetAttributes();
1018
1019 // If the return value is not being used, the type may not be compatible
1020 // with the existing attributes. Wipe out any problematic attributes.
1021 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
1022
1023 // Add the new return attributes.
1024 if (RAttrs)
1025 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
1026
1027 AI = CS.arg_begin();
1028 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1029 const Type *ParamTy = FT->getParamType(i);
1030 if ((*AI)->getType() == ParamTy) {
1031 Args.push_back(*AI);
1032 } else {
1033 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1034 false, ParamTy, false);
1035 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
1036 }
1037
1038 // Add any parameter attributes.
1039 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1040 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1041 }
1042
1043 // If the function takes more arguments than the call was taking, add them
1044 // now.
1045 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1046 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1047
1048 // If we are removing arguments to the function, emit an obnoxious warning.
1049 if (FT->getNumParams() < NumActualArgs) {
1050 if (!FT->isVarArg()) {
1051 errs() << "WARNING: While resolving call to function '"
1052 << Callee->getName() << "' arguments were dropped!\n";
1053 } else {
1054 // Add all of the arguments in their promoted form to the arg list.
1055 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1056 const Type *PTy = getPromotedType((*AI)->getType());
1057 if (PTy != (*AI)->getType()) {
1058 // Must promote to pass through va_arg area!
1059 Instruction::CastOps opcode =
1060 CastInst::getCastOpcode(*AI, false, PTy, false);
1061 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
1062 } else {
1063 Args.push_back(*AI);
1064 }
1065
1066 // Add any parameter attributes.
1067 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1068 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1069 }
1070 }
1071 }
1072
1073 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
1074 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1075
1076 if (NewRetTy->isVoidTy())
1077 Caller->setName(""); // Void type should not have a name.
1078
1079 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
1080 attrVec.end());
1081
1082 Instruction *NC;
1083 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1084 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
1085 Args.begin(), Args.end(),
1086 Caller->getName(), Caller);
1087 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1088 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1089 } else {
1090 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
1091 Caller->getName(), Caller);
1092 CallInst *CI = cast<CallInst>(Caller);
1093 if (CI->isTailCall())
1094 cast<CallInst>(NC)->setTailCall();
1095 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1096 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1097 }
1098
1099 // Insert a cast of the return type as necessary.
1100 Value *NV = NC;
1101 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1102 if (!NV->getType()->isVoidTy()) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001103 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Chris Lattner753a2b42010-01-05 07:32:13 +00001104 OldRetTy, false);
1105 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1106
1107 // If this is an invoke instruction, we should insert it after the first
1108 // non-phi, instruction in the normal successor block.
1109 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1110 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1111 InsertNewInstBefore(NC, *I);
1112 } else {
1113 // Otherwise, it's a call, just insert cast right after the call instr
1114 InsertNewInstBefore(NC, *Caller);
1115 }
1116 Worklist.AddUsersToWorkList(*Caller);
1117 } else {
1118 NV = UndefValue::get(Caller->getType());
1119 }
1120 }
1121
1122
1123 if (!Caller->use_empty())
1124 Caller->replaceAllUsesWith(NV);
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001125
Chris Lattner753a2b42010-01-05 07:32:13 +00001126 EraseInstFromFunction(*Caller);
1127 return true;
1128}
1129
1130// transformCallThroughTrampoline - Turn a call to a function created by the
1131// init_trampoline intrinsic into a direct call to the underlying function.
1132//
1133Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1134 Value *Callee = CS.getCalledValue();
1135 const PointerType *PTy = cast<PointerType>(Callee->getType());
1136 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1137 const AttrListPtr &Attrs = CS.getAttributes();
1138
1139 // If the call already has the 'nest' attribute somewhere then give up -
1140 // otherwise 'nest' would occur twice after splicing in the chain.
1141 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1142 return 0;
1143
1144 IntrinsicInst *Tramp =
1145 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1146
Gabor Greifa3997812010-07-22 10:37:47 +00001147 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Chris Lattner753a2b42010-01-05 07:32:13 +00001148 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1149 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1150
1151 const AttrListPtr &NestAttrs = NestF->getAttributes();
1152 if (!NestAttrs.isEmpty()) {
1153 unsigned NestIdx = 1;
1154 const Type *NestTy = 0;
1155 Attributes NestAttr = Attribute::None;
1156
1157 // Look for a parameter marked with the 'nest' attribute.
1158 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1159 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1160 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1161 // Record the parameter type and any other attributes.
1162 NestTy = *I;
1163 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1164 break;
1165 }
1166
1167 if (NestTy) {
1168 Instruction *Caller = CS.getInstruction();
1169 std::vector<Value*> NewArgs;
1170 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1171
1172 SmallVector<AttributeWithIndex, 8> NewAttrs;
1173 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1174
1175 // Insert the nest argument into the call argument list, which may
1176 // mean appending it. Likewise for attributes.
1177
1178 // Add any result attributes.
1179 if (Attributes Attr = Attrs.getRetAttributes())
1180 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1181
1182 {
1183 unsigned Idx = 1;
1184 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1185 do {
1186 if (Idx == NestIdx) {
1187 // Add the chain argument and attributes.
Gabor Greifcea7ac72010-06-24 12:58:35 +00001188 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner753a2b42010-01-05 07:32:13 +00001189 if (NestVal->getType() != NestTy)
1190 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1191 NewArgs.push_back(NestVal);
1192 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1193 }
1194
1195 if (I == E)
1196 break;
1197
1198 // Add the original argument and attributes.
1199 NewArgs.push_back(*I);
1200 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1201 NewAttrs.push_back
1202 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1203
1204 ++Idx, ++I;
1205 } while (1);
1206 }
1207
1208 // Add any function attributes.
1209 if (Attributes Attr = Attrs.getFnAttributes())
1210 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1211
1212 // The trampoline may have been bitcast to a bogus type (FTy).
1213 // Handle this by synthesizing a new function type, equal to FTy
1214 // with the chain parameter inserted.
1215
1216 std::vector<const Type*> NewTypes;
1217 NewTypes.reserve(FTy->getNumParams()+1);
1218
1219 // Insert the chain's type into the list of parameter types, which may
1220 // mean appending it.
1221 {
1222 unsigned Idx = 1;
1223 FunctionType::param_iterator I = FTy->param_begin(),
1224 E = FTy->param_end();
1225
1226 do {
1227 if (Idx == NestIdx)
1228 // Add the chain's type.
1229 NewTypes.push_back(NestTy);
1230
1231 if (I == E)
1232 break;
1233
1234 // Add the original type.
1235 NewTypes.push_back(*I);
1236
1237 ++Idx, ++I;
1238 } while (1);
1239 }
1240
1241 // Replace the trampoline call with a direct call. Let the generic
1242 // code sort out any function type mismatches.
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001243 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001244 FTy->isVarArg());
1245 Constant *NewCallee =
1246 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001247 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001248 PointerType::getUnqual(NewFTy));
1249 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1250 NewAttrs.end());
1251
1252 Instruction *NewCaller;
1253 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1254 NewCaller = InvokeInst::Create(NewCallee,
1255 II->getNormalDest(), II->getUnwindDest(),
1256 NewArgs.begin(), NewArgs.end(),
1257 Caller->getName(), Caller);
1258 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1259 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1260 } else {
1261 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1262 Caller->getName(), Caller);
1263 if (cast<CallInst>(Caller)->isTailCall())
1264 cast<CallInst>(NewCaller)->setTailCall();
1265 cast<CallInst>(NewCaller)->
1266 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1267 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1268 }
1269 if (!Caller->getType()->isVoidTy())
1270 Caller->replaceAllUsesWith(NewCaller);
1271 Caller->eraseFromParent();
1272 Worklist.Remove(Caller);
1273 return 0;
1274 }
1275 }
1276
1277 // Replace the trampoline call with a direct call. Since there is no 'nest'
1278 // parameter, there is no need to adjust the argument list. Let the generic
1279 // code sort out any function type mismatches.
1280 Constant *NewCallee =
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001281 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001282 ConstantExpr::getBitCast(NestF, PTy);
1283 CS.setCalledFunction(NewCallee);
1284 return CS.getInstruction();
1285}
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001286