blob: f3025dc5ebc3e276331768a14f71a365cabf0d62 [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) {
Eric Christopher551754c2010-04-16 23:37:20 +0000115 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
116 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
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.
Eric Christopher551754c2010-04-16 23:37:20 +0000128 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
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 =
Eric Christopher551754c2010-04-16 23:37:20 +0000143 cast<PointerType>(MI->getOperand(2)->getType())->getAddressSpace();
Gabor Greif4ec22582010-04-16 15:33:14 +0000144 unsigned DstAddrSp =
Eric Christopher551754c2010-04-16 23:37:20 +0000145 cast<PointerType>(MI->getOperand(1)->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
Eric Christopher551754c2010-04-16 23:37:20 +0000192 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewSrcPtrTy);
193 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), 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.
Eric Christopher551754c2010-04-16 23:37:20 +0000200 MI->setOperand(3, 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;
Eric Christopher551754c2010-04-16 23:37:20 +0000292 const Type *Tys[3] = { CI.getOperand(1)->getType(),
293 CI.getOperand(2)->getType(),
294 CI.getOperand(3)->getType() };
Gabor Greifa9b23132010-04-20 13:13:04 +0000295 CI.setCalledFunction(
Mon P Wang20adc9d2010-04-04 03:10:48 +0000296 Intrinsic::getDeclaration(M, MemCpyID, Tys, 3));
Chris Lattner753a2b42010-01-05 07:32:13 +0000297 Changed = true;
298 }
299 }
300
301 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
302 // memmove(x,x,size) -> noop.
303 if (MTI->getSource() == MTI->getDest())
304 return EraseInstFromFunction(CI);
Eric Christopher551754c2010-04-16 23:37:20 +0000305 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000306
Eric Christopher551754c2010-04-16 23:37:20 +0000307 // If we can determine a pointer alignment that is bigger than currently
308 // set, update the alignment.
309 if (isa<MemTransferInst>(MI)) {
310 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner753a2b42010-01-05 07:32:13 +0000311 return I;
312 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
313 if (Instruction *I = SimplifyMemSet(MSI))
314 return I;
315 }
Eric Christopher551754c2010-04-16 23:37:20 +0000316
Chris Lattner753a2b42010-01-05 07:32:13 +0000317 if (Changed) return II;
318 }
Eric Christopher551754c2010-04-16 23:37:20 +0000319
Chris Lattner753a2b42010-01-05 07:32:13 +0000320 switch (II->getIntrinsicID()) {
321 default: break;
Eric Christopher415326b2010-02-09 21:24:27 +0000322 case Intrinsic::objectsize: {
Eric Christopher26d0e892010-02-11 01:48:54 +0000323 // We need target data for just about everything so depend on it.
Eric Christopher415326b2010-02-09 21:24:27 +0000324 if (!TD) break;
Eric Christopher26d0e892010-02-11 01:48:54 +0000325
Evan Chenga8623262010-03-05 20:47:23 +0000326 const Type *ReturnTy = CI.getType();
Gabor Greifcea7ac72010-06-24 12:58:35 +0000327 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Evan Chenga8623262010-03-05 20:47:23 +0000328
Eric Christopher26d0e892010-02-11 01:48:54 +0000329 // Get to the real allocated thing and offset as fast as possible.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000330 Value *Op1 = II->getArgOperand(0)->stripPointerCasts();
Eric Christopher415326b2010-02-09 21:24:27 +0000331
Eric Christopher26d0e892010-02-11 01:48:54 +0000332 // If we've stripped down to a single global variable that we
333 // can know the size of then just return that.
Eric Christopher415326b2010-02-09 21:24:27 +0000334 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
335 if (GV->hasDefinitiveInitializer()) {
336 Constant *C = GV->getInitializer();
Evan Chenga8623262010-03-05 20:47:23 +0000337 uint64_t GlobalSize = TD->getTypeAllocSize(C->getType());
338 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, GlobalSize));
Eric Christopher415326b2010-02-09 21:24:27 +0000339 } else {
Evan Chenga8623262010-03-05 20:47:23 +0000340 // Can't determine size of the GV.
Eric Christopher415326b2010-02-09 21:24:27 +0000341 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
342 return ReplaceInstUsesWith(CI, RetVal);
343 }
Evan Chenga8623262010-03-05 20:47:23 +0000344 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
345 // Get alloca size.
346 if (AI->getAllocatedType()->isSized()) {
347 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
348 if (AI->isArrayAllocation()) {
349 const ConstantInt *C = dyn_cast<ConstantInt>(AI->getArraySize());
350 if (!C) break;
351 AllocaSize *= C->getZExtValue();
352 }
353 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, AllocaSize));
354 }
Evan Cheng687fed32010-03-08 22:54:36 +0000355 } else if (CallInst *MI = extractMallocCall(Op1)) {
356 const Type* MallocType = getMallocAllocatedType(MI);
357 // Get alloca size.
358 if (MallocType && MallocType->isSized()) {
359 if (Value *NElems = getMallocArraySize(MI, TD, true)) {
360 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
361 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy,
362 (NElements->getZExtValue() * TD->getTypeAllocSize(MallocType))));
363 }
364 }
Evan Chenga8623262010-03-05 20:47:23 +0000365 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
Eric Christopher26d0e892010-02-11 01:48:54 +0000366 // Only handle constant GEPs here.
367 if (CE->getOpcode() != Instruction::GetElementPtr) break;
368 GEPOperator *GEP = cast<GEPOperator>(CE);
369
Eric Christopherdfdddd82010-02-11 17:44:04 +0000370 // Make sure we're not a constant offset from an external
371 // global.
372 Value *Operand = GEP->getPointerOperand();
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000373 Operand = Operand->stripPointerCasts();
Eric Christopherdfdddd82010-02-11 17:44:04 +0000374 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
375 if (!GV->hasDefinitiveInitializer()) break;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000376
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000377 // Get what we're pointing to and its size.
378 const PointerType *BaseType =
Eric Christopherdfdddd82010-02-11 17:44:04 +0000379 cast<PointerType>(Operand->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000380 uint64_t Size = TD->getTypeAllocSize(BaseType->getElementType());
Eric Christopher26d0e892010-02-11 01:48:54 +0000381
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000382 // Get the current byte offset into the thing. Use the original
383 // operand in case we're looking through a bitcast.
Eric Christopher26d0e892010-02-11 01:48:54 +0000384 SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000385 const PointerType *OffsetType =
386 cast<PointerType>(GEP->getPointerOperand()->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000387 uint64_t Offset = TD->getIndexedOffset(OffsetType, &Ops[0], Ops.size());
Eric Christopher26d0e892010-02-11 01:48:54 +0000388
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000389 if (Size < Offset) {
390 // Out of bound reference? Negative index normalized to large
391 // index? Just return "I don't know".
392 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
393 return ReplaceInstUsesWith(CI, RetVal);
394 }
Eric Christopher26d0e892010-02-11 01:48:54 +0000395
396 Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
397 return ReplaceInstUsesWith(CI, RetVal);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000398 }
Evan Chenga8623262010-03-05 20:47:23 +0000399
400 // Do not return "I don't know" here. Later optimization passes could
401 // make it possible to evaluate objectsize to a constant.
Evan Chengf79d6242010-03-05 01:22:47 +0000402 break;
Eric Christopher415326b2010-02-09 21:24:27 +0000403 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000404 case Intrinsic::bswap:
405 // bswap(bswap(x)) -> x
Gabor Greifcea7ac72010-06-24 12:58:35 +0000406 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getArgOperand(0)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000407 if (Operand->getIntrinsicID() == Intrinsic::bswap)
Gabor Greifcea7ac72010-06-24 12:58:35 +0000408 return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000409
Chris Lattner753a2b42010-01-05 07:32:13 +0000410 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Gabor Greifcea7ac72010-06-24 12:58:35 +0000411 if (TruncInst *TI = dyn_cast<TruncInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000412 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
413 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
414 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
415 TI->getType()->getPrimitiveSizeInBits();
416 Value *CV = ConstantInt::get(Operand->getType(), C);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000417 Value *V = Builder->CreateLShr(Operand->getArgOperand(0), CV);
Chris Lattner753a2b42010-01-05 07:32:13 +0000418 return new TruncInst(V, TI->getType());
419 }
420 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000421
Chris Lattner753a2b42010-01-05 07:32:13 +0000422 break;
423 case Intrinsic::powi:
Gabor Greifcea7ac72010-06-24 12:58:35 +0000424 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000425 // powi(x, 0) -> 1.0
426 if (Power->isZero())
427 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
428 // powi(x, 1) -> x
429 if (Power->isOne())
Gabor Greifcea7ac72010-06-24 12:58:35 +0000430 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000431 // powi(x, -1) -> 1/x
432 if (Power->isAllOnesValue())
433 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greifcea7ac72010-06-24 12:58:35 +0000434 II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000435 }
436 break;
437 case Intrinsic::cttz: {
438 // If all bits below the first known one are known zero,
439 // this value is constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000440 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000441 uint32_t BitWidth = IT->getBitWidth();
442 APInt KnownZero(BitWidth, 0);
443 APInt KnownOne(BitWidth, 0);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000444 ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidth),
Chris Lattner753a2b42010-01-05 07:32:13 +0000445 KnownZero, KnownOne);
446 unsigned TrailingZeros = KnownOne.countTrailingZeros();
447 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
448 if ((Mask & KnownZero) == Mask)
449 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
450 APInt(BitWidth, TrailingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000451
Chris Lattner753a2b42010-01-05 07:32:13 +0000452 }
453 break;
454 case Intrinsic::ctlz: {
455 // If all bits above the first known one are known zero,
456 // this value is constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000457 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000458 uint32_t BitWidth = IT->getBitWidth();
459 APInt KnownZero(BitWidth, 0);
460 APInt KnownOne(BitWidth, 0);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000461 ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidth),
Chris Lattner753a2b42010-01-05 07:32:13 +0000462 KnownZero, KnownOne);
463 unsigned LeadingZeros = KnownOne.countLeadingZeros();
464 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
465 if ((Mask & KnownZero) == Mask)
466 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
467 APInt(BitWidth, LeadingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000468
Chris Lattner753a2b42010-01-05 07:32:13 +0000469 }
470 break;
471 case Intrinsic::uadd_with_overflow: {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000472 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
473 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000474 uint32_t BitWidth = IT->getBitWidth();
475 APInt Mask = APInt::getSignBit(BitWidth);
476 APInt LHSKnownZero(BitWidth, 0);
477 APInt LHSKnownOne(BitWidth, 0);
478 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
479 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
480 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
481
482 if (LHSKnownNegative || LHSKnownPositive) {
483 APInt RHSKnownZero(BitWidth, 0);
484 APInt RHSKnownOne(BitWidth, 0);
485 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
486 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
487 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
488 if (LHSKnownNegative && RHSKnownNegative) {
489 // The sign bit is set in both cases: this MUST overflow.
490 // Create a simple add instruction, and insert it into the struct.
491 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
492 Worklist.Add(Add);
493 Constant *V[] = {
494 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
495 };
496 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
497 return InsertValueInst::Create(Struct, Add, 0);
498 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000499
Chris Lattner753a2b42010-01-05 07:32:13 +0000500 if (LHSKnownPositive && RHSKnownPositive) {
501 // The sign bit is clear in both cases: this CANNOT overflow.
502 // Create a simple add instruction, and insert it into the struct.
503 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
504 Worklist.Add(Add);
505 Constant *V[] = {
506 UndefValue::get(LHS->getType()),
507 ConstantInt::getFalse(II->getContext())
508 };
509 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
510 return InsertValueInst::Create(Struct, Add, 0);
511 }
512 }
513 }
514 // FALL THROUGH uadd into sadd
515 case Intrinsic::sadd_with_overflow:
516 // Canonicalize constants into the RHS.
Eric Christopher551754c2010-04-16 23:37:20 +0000517 if (isa<Constant>(II->getOperand(1)) &&
518 !isa<Constant>(II->getOperand(2))) {
519 Value *LHS = II->getOperand(1);
520 II->setOperand(1, II->getOperand(2));
521 II->setOperand(2, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000522 return II;
523 }
524
525 // X + undef -> undef
Eric Christopher551754c2010-04-16 23:37:20 +0000526 if (isa<UndefValue>(II->getOperand(2)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000527 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000528
Eric Christopher551754c2010-04-16 23:37:20 +0000529 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000530 // X + 0 -> {X, false}
531 if (RHS->isZero()) {
532 Constant *V[] = {
Gabor Greifa9b23132010-04-20 13:13:04 +0000533 UndefValue::get(II->getCalledValue()->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000534 ConstantInt::getFalse(II->getContext())
535 };
536 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000537 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000538 }
539 }
540 break;
541 case Intrinsic::usub_with_overflow:
542 case Intrinsic::ssub_with_overflow:
543 // undef - X -> undef
544 // X - undef -> undef
Eric Christopher551754c2010-04-16 23:37:20 +0000545 if (isa<UndefValue>(II->getOperand(1)) ||
546 isa<UndefValue>(II->getOperand(2)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000547 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000548
Eric Christopher551754c2010-04-16 23:37:20 +0000549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000550 // X - 0 -> {X, false}
551 if (RHS->isZero()) {
552 Constant *V[] = {
Eric Christopher551754c2010-04-16 23:37:20 +0000553 UndefValue::get(II->getOperand(1)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000554 ConstantInt::getFalse(II->getContext())
555 };
556 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Eric Christopher551754c2010-04-16 23:37:20 +0000557 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000558 }
559 }
560 break;
561 case Intrinsic::umul_with_overflow:
562 case Intrinsic::smul_with_overflow:
563 // Canonicalize constants into the RHS.
Eric Christopher551754c2010-04-16 23:37:20 +0000564 if (isa<Constant>(II->getOperand(1)) &&
565 !isa<Constant>(II->getOperand(2))) {
566 Value *LHS = II->getOperand(1);
567 II->setOperand(1, II->getOperand(2));
568 II->setOperand(2, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000569 return II;
570 }
571
572 // X * undef -> undef
Eric Christopher551754c2010-04-16 23:37:20 +0000573 if (isa<UndefValue>(II->getOperand(2)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000574 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000575
Eric Christopher551754c2010-04-16 23:37:20 +0000576 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000577 // X*0 -> {0, false}
578 if (RHSI->isZero())
579 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000580
Chris Lattner753a2b42010-01-05 07:32:13 +0000581 // X * 1 -> {X, false}
582 if (RHSI->equalsInt(1)) {
583 Constant *V[] = {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000584 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000585 ConstantInt::getFalse(II->getContext())
586 };
587 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000588 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000589 }
590 }
591 break;
592 case Intrinsic::ppc_altivec_lvx:
593 case Intrinsic::ppc_altivec_lvxl:
594 case Intrinsic::x86_sse_loadu_ps:
595 case Intrinsic::x86_sse2_loadu_pd:
596 case Intrinsic::x86_sse2_loadu_dq:
597 // Turn PPC lvx -> load if the pointer is known aligned.
598 // Turn X86 loadups -> load if the pointer is known aligned.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000599 if (GetOrEnforceKnownAlignment(II->getArgOperand(0), 16) >= 16) {
600 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner753a2b42010-01-05 07:32:13 +0000601 PointerType::getUnqual(II->getType()));
602 return new LoadInst(Ptr);
603 }
604 break;
605 case Intrinsic::ppc_altivec_stvx:
606 case Intrinsic::ppc_altivec_stvxl:
607 // Turn stvx -> store if the pointer is known aligned.
Eric Christopher551754c2010-04-16 23:37:20 +0000608 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000609 const Type *OpPtrTy =
Eric Christopher551754c2010-04-16 23:37:20 +0000610 PointerType::getUnqual(II->getOperand(1)->getType());
611 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
612 return new StoreInst(II->getOperand(1), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000613 }
614 break;
615 case Intrinsic::x86_sse_storeu_ps:
616 case Intrinsic::x86_sse2_storeu_pd:
617 case Intrinsic::x86_sse2_storeu_dq:
618 // Turn X86 storeu -> store if the pointer is known aligned.
Eric Christopher551754c2010-04-16 23:37:20 +0000619 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000620 const Type *OpPtrTy =
Eric Christopher551754c2010-04-16 23:37:20 +0000621 PointerType::getUnqual(II->getOperand(2)->getType());
622 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
623 return new StoreInst(II->getOperand(2), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000624 }
625 break;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000626
Chris Lattner753a2b42010-01-05 07:32:13 +0000627 case Intrinsic::x86_sse_cvttss2si: {
628 // These intrinsics only demands the 0th element of its input vector. If
629 // we can simplify the input based on that, do so now.
630 unsigned VWidth =
Eric Christopher551754c2010-04-16 23:37:20 +0000631 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
Chris Lattner753a2b42010-01-05 07:32:13 +0000632 APInt DemandedElts(VWidth, 1);
633 APInt UndefElts(VWidth, 0);
Eric Christopher551754c2010-04-16 23:37:20 +0000634 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner753a2b42010-01-05 07:32:13 +0000635 UndefElts)) {
Eric Christopher551754c2010-04-16 23:37:20 +0000636 II->setOperand(1, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000637 return II;
638 }
639 break;
640 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000641
Chris Lattner753a2b42010-01-05 07:32:13 +0000642 case Intrinsic::ppc_altivec_vperm:
643 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000644 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getArgOperand(2))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000645 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000646
Chris Lattner753a2b42010-01-05 07:32:13 +0000647 // Check that all of the elements are integer constants or undefs.
648 bool AllEltsOk = true;
649 for (unsigned i = 0; i != 16; ++i) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000650 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
Chris Lattner753a2b42010-01-05 07:32:13 +0000651 !isa<UndefValue>(Mask->getOperand(i))) {
652 AllEltsOk = false;
653 break;
654 }
655 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000656
Chris Lattner753a2b42010-01-05 07:32:13 +0000657 if (AllEltsOk) {
658 // Cast the input vectors to byte vectors.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000659 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0), Mask->getType());
660 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1), Mask->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000661 Value *Result = UndefValue::get(Op0->getType());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000662
Chris Lattner753a2b42010-01-05 07:32:13 +0000663 // Only extract each element once.
664 Value *ExtractedElts[32];
665 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000666
Chris Lattner753a2b42010-01-05 07:32:13 +0000667 for (unsigned i = 0; i != 16; ++i) {
668 if (isa<UndefValue>(Mask->getOperand(i)))
669 continue;
670 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
671 Idx &= 31; // Match the hardware behavior.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000672
Chris Lattner753a2b42010-01-05 07:32:13 +0000673 if (ExtractedElts[Idx] == 0) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000674 ExtractedElts[Idx] =
675 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner753a2b42010-01-05 07:32:13 +0000676 ConstantInt::get(Type::getInt32Ty(II->getContext()),
677 Idx&15, false), "tmp");
678 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000679
Chris Lattner753a2b42010-01-05 07:32:13 +0000680 // Insert this value into the result vector.
681 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
682 ConstantInt::get(Type::getInt32Ty(II->getContext()),
683 i, false), "tmp");
684 }
685 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
686 }
687 }
688 break;
689
690 case Intrinsic::stackrestore: {
691 // If the save is right next to the restore, remove the restore. This can
692 // happen when variable allocas are DCE'd.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000693 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000694 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
695 BasicBlock::iterator BI = SS;
696 if (&*++BI == II)
697 return EraseInstFromFunction(CI);
698 }
699 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000700
Chris Lattner753a2b42010-01-05 07:32:13 +0000701 // Scan down this block to see if there is another stack restore in the
702 // same block without an intervening call/alloca.
703 BasicBlock::iterator BI = II;
704 TerminatorInst *TI = II->getParent()->getTerminator();
705 bool CannotRemove = false;
706 for (++BI; &*BI != TI; ++BI) {
707 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
708 CannotRemove = true;
709 break;
710 }
711 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
712 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
713 // If there is a stackrestore below this one, remove this one.
714 if (II->getIntrinsicID() == Intrinsic::stackrestore)
715 return EraseInstFromFunction(CI);
716 // Otherwise, ignore the intrinsic.
717 } else {
718 // If we found a non-intrinsic call, we can't remove the stack
719 // restore.
720 CannotRemove = true;
721 break;
722 }
723 }
724 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000725
Chris Lattner753a2b42010-01-05 07:32:13 +0000726 // If the stack restore is in a return/unwind block and if there are no
727 // allocas or calls between the restore and the return, nuke the restore.
728 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
729 return EraseInstFromFunction(CI);
730 break;
731 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000732 }
733
734 return visitCallSite(II);
735}
736
737// InvokeInst simplification
738//
739Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
740 return visitCallSite(&II);
741}
742
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000743/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000744/// passed through the varargs area, we can eliminate the use of the cast.
745static bool isSafeToEliminateVarargsCast(const CallSite CS,
746 const CastInst * const CI,
747 const TargetData * const TD,
748 const int ix) {
749 if (!CI->isLosslessCast())
750 return false;
751
752 // The size of ByVal arguments is derived from the type, so we
753 // can't change to a type with a different size. If the size were
754 // passed explicitly we could avoid this check.
755 if (!CS.paramHasAttr(ix, Attribute::ByVal))
756 return true;
757
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000758 const Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000759 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
760 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
761 if (!SrcTy->isSized() || !DstTy->isSized())
762 return false;
763 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
764 return false;
765 return true;
766}
767
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000768namespace {
769class InstCombineFortifiedLibCalls : public SimplifyFortifiedLibCalls {
770 InstCombiner *IC;
771protected:
772 void replaceCall(Value *With) {
773 NewInstruction = IC->ReplaceInstUsesWith(*CI, With);
774 }
775 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
776 if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(SizeCIOp))) {
777 if (SizeCI->isAllOnesValue())
778 return true;
779 if (isString)
780 return SizeCI->getZExtValue() >=
781 GetStringLength(CI->getOperand(SizeArgOp));
782 if (ConstantInt *Arg = dyn_cast<ConstantInt>(CI->getOperand(SizeArgOp)))
Evan Cheng9d8f0022010-03-23 06:06:09 +0000783 return SizeCI->getZExtValue() >= Arg->getZExtValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000784 }
785 return false;
786 }
787public:
788 InstCombineFortifiedLibCalls(InstCombiner *IC) : IC(IC), NewInstruction(0) { }
789 Instruction *NewInstruction;
790};
791} // end anonymous namespace
792
Eric Christopher27ceaa12010-03-06 10:50:38 +0000793// Try to fold some different type of calls here.
794// Currently we're only working with the checking functions, memcpy_chk,
795// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
796// strcat_chk and strncat_chk.
797Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData *TD) {
798 if (CI->getCalledFunction() == 0) return 0;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000799
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000800 InstCombineFortifiedLibCalls Simplifier(this);
801 Simplifier.fold(CI, TD);
802 return Simplifier.NewInstruction;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000803}
804
Chris Lattner753a2b42010-01-05 07:32:13 +0000805// visitCallSite - Improvements for call and invoke instructions.
806//
807Instruction *InstCombiner::visitCallSite(CallSite CS) {
808 bool Changed = false;
809
810 // If the callee is a constexpr cast of a function, attempt to move the cast
811 // to the arguments of the call/invoke.
812 if (transformConstExprCastCall(CS)) return 0;
813
814 Value *Callee = CS.getCalledValue();
815
816 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000817 // If the call and callee calling conventions don't match, this call must
818 // be unreachable, as the call is undefined.
819 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
820 // Only do this for calls to a function with a body. A prototype may
821 // not actually end up matching the implementation's calling conv for a
822 // variety of reasons (e.g. it may be written in assembly).
823 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000824 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000825 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000826 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000827 OldCall);
828 // If OldCall dues not return void then replaceAllUsesWith undef.
829 // This allows ValueHandlers and custom metadata to adjust itself.
830 if (!OldCall->getType()->isVoidTy())
831 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000832 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000833 return EraseInstFromFunction(*OldCall);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000834
Chris Lattner830f3f22010-02-01 18:04:58 +0000835 // We cannot remove an invoke, because it would change the CFG, just
836 // change the callee to a null pointer.
Gabor Greif654c06f2010-03-20 21:00:25 +0000837 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner830f3f22010-02-01 18:04:58 +0000838 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000839 return 0;
840 }
841
842 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
843 // This instruction is not reachable, just remove it. We insert a store to
844 // undef so that we know that this code is not reachable, despite the fact
845 // that we can't modify the CFG here.
846 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
847 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
848 CS.getInstruction());
849
Gabor Greifcea7ac72010-06-24 12:58:35 +0000850 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner753a2b42010-01-05 07:32:13 +0000851 // This allows ValueHandlers and custom metadata to adjust itself.
852 if (!CS.getInstruction()->getType()->isVoidTy())
853 CS.getInstruction()->
854 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
855
856 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
857 // Don't break the CFG, insert a dummy cond branch.
858 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
859 ConstantInt::getTrue(Callee->getContext()), II);
860 }
861 return EraseInstFromFunction(*CS.getInstruction());
862 }
863
864 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
865 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
866 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
867 return transformCallThroughTrampoline(CS);
868
869 const PointerType *PTy = cast<PointerType>(Callee->getType());
870 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
871 if (FTy->isVarArg()) {
872 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
873 // See if we can optimize any arguments passed through the varargs area of
874 // the call.
875 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
876 E = CS.arg_end(); I != E; ++I, ++ix) {
877 CastInst *CI = dyn_cast<CastInst>(*I);
878 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
879 *I = CI->getOperand(0);
880 Changed = true;
881 }
882 }
883 }
884
885 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
886 // Inline asm calls cannot throw - mark them 'nounwind'.
887 CS.setDoesNotThrow();
888 Changed = true;
889 }
890
Eric Christopher27ceaa12010-03-06 10:50:38 +0000891 // Try to optimize the call if possible, we require TargetData for most of
892 // this. None of these calls are seen as possibly dead so go ahead and
893 // delete the instruction now.
894 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
895 Instruction *I = tryOptimizeCall(CI, TD);
Eric Christopher7b323a32010-03-06 10:59:25 +0000896 // If we changed something return the result, etc. Otherwise let
897 // the fallthrough check.
898 if (I) return EraseInstFromFunction(*I);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000899 }
900
Chris Lattner753a2b42010-01-05 07:32:13 +0000901 return Changed ? CS.getInstruction() : 0;
902}
903
904// transformConstExprCastCall - If the callee is a constexpr cast of a function,
905// attempt to move the cast to the arguments of the call/invoke.
906//
907bool InstCombiner::transformConstExprCastCall(CallSite CS) {
908 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
909 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000910 if (CE->getOpcode() != Instruction::BitCast ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000911 !isa<Function>(CE->getOperand(0)))
912 return false;
913 Function *Callee = cast<Function>(CE->getOperand(0));
914 Instruction *Caller = CS.getInstruction();
915 const AttrListPtr &CallerPAL = CS.getAttributes();
916
917 // Okay, this is a cast from a function to a different type. Unless doing so
918 // would cause a type conversion of one of our arguments, change this call to
919 // be a direct call with arguments casted to the appropriate types.
920 //
921 const FunctionType *FT = Callee->getFunctionType();
922 const Type *OldRetTy = Caller->getType();
923 const Type *NewRetTy = FT->getReturnType();
924
Duncan Sands1df98592010-02-16 11:11:14 +0000925 if (NewRetTy->isStructTy())
Chris Lattner753a2b42010-01-05 07:32:13 +0000926 return false; // TODO: Handle multiple return values.
927
928 // Check to see if we are changing the return type...
929 if (OldRetTy != NewRetTy) {
930 if (Callee->isDeclaration() &&
931 // Conversion is ok if changing from one pointer type to another or from
932 // a pointer to an integer of the same size.
Duncan Sands1df98592010-02-16 11:11:14 +0000933 !((OldRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000934 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +0000935 (NewRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000936 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
937 return false; // Cannot transform this return value.
938
939 if (!Caller->use_empty() &&
940 // void -> non-void is handled specially
941 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
942 return false; // Cannot transform this return value.
943
944 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
945 Attributes RAttrs = CallerPAL.getRetAttributes();
946 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
947 return false; // Attribute not compatible with transformed value.
948 }
949
950 // If the callsite is an invoke instruction, and the return value is used by
951 // a PHI node in a successor, we cannot change the return type of the call
952 // because there is no place to put the cast instruction (without breaking
953 // the critical edge). Bail out in this case.
954 if (!Caller->use_empty())
955 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
956 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
957 UI != E; ++UI)
958 if (PHINode *PN = dyn_cast<PHINode>(*UI))
959 if (PN->getParent() == II->getNormalDest() ||
960 PN->getParent() == II->getUnwindDest())
961 return false;
962 }
963
964 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
965 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
966
967 CallSite::arg_iterator AI = CS.arg_begin();
968 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
969 const Type *ParamTy = FT->getParamType(i);
970 const Type *ActTy = (*AI)->getType();
971
972 if (!CastInst::isCastable(ActTy, ParamTy))
973 return false; // Cannot transform this parameter value.
974
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000975 if (CallerPAL.getParamAttributes(i + 1)
Chris Lattner753a2b42010-01-05 07:32:13 +0000976 & Attribute::typeIncompatible(ParamTy))
977 return false; // Attribute not compatible with transformed value.
978
979 // Converting from one pointer type to another or between a pointer and an
980 // integer of the same size is safe even if we do not have a body.
981 bool isConvertible = ActTy == ParamTy ||
Duncan Sands1df98592010-02-16 11:11:14 +0000982 (TD && ((ParamTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000983 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +0000984 (ActTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000985 ActTy == TD->getIntPtrType(Caller->getContext()))));
986 if (Callee->isDeclaration() && !isConvertible) return false;
987 }
988
989 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
990 Callee->isDeclaration())
991 return false; // Do not delete arguments unless we have a function body.
992
993 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
994 !CallerPAL.isEmpty())
995 // In this case we have more arguments than the new function type, but we
996 // won't be dropping them. Check that these extra arguments have attributes
997 // that are compatible with being a vararg call argument.
998 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
999 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1000 break;
1001 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1002 if (PAttrs & Attribute::VarArgsIncompatible)
1003 return false;
1004 }
1005
1006 // Okay, we decided that this is a safe thing to do: go ahead and start
1007 // inserting cast instructions as necessary...
1008 std::vector<Value*> Args;
1009 Args.reserve(NumActualArgs);
1010 SmallVector<AttributeWithIndex, 8> attrVec;
1011 attrVec.reserve(NumCommonArgs);
1012
1013 // Get any return attributes.
1014 Attributes RAttrs = CallerPAL.getRetAttributes();
1015
1016 // If the return value is not being used, the type may not be compatible
1017 // with the existing attributes. Wipe out any problematic attributes.
1018 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
1019
1020 // Add the new return attributes.
1021 if (RAttrs)
1022 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
1023
1024 AI = CS.arg_begin();
1025 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1026 const Type *ParamTy = FT->getParamType(i);
1027 if ((*AI)->getType() == ParamTy) {
1028 Args.push_back(*AI);
1029 } else {
1030 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1031 false, ParamTy, false);
1032 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
1033 }
1034
1035 // Add any parameter attributes.
1036 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1037 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1038 }
1039
1040 // If the function takes more arguments than the call was taking, add them
1041 // now.
1042 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1043 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1044
1045 // If we are removing arguments to the function, emit an obnoxious warning.
1046 if (FT->getNumParams() < NumActualArgs) {
1047 if (!FT->isVarArg()) {
1048 errs() << "WARNING: While resolving call to function '"
1049 << Callee->getName() << "' arguments were dropped!\n";
1050 } else {
1051 // Add all of the arguments in their promoted form to the arg list.
1052 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1053 const Type *PTy = getPromotedType((*AI)->getType());
1054 if (PTy != (*AI)->getType()) {
1055 // Must promote to pass through va_arg area!
1056 Instruction::CastOps opcode =
1057 CastInst::getCastOpcode(*AI, false, PTy, false);
1058 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
1059 } else {
1060 Args.push_back(*AI);
1061 }
1062
1063 // Add any parameter attributes.
1064 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1065 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1066 }
1067 }
1068 }
1069
1070 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
1071 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1072
1073 if (NewRetTy->isVoidTy())
1074 Caller->setName(""); // Void type should not have a name.
1075
1076 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
1077 attrVec.end());
1078
1079 Instruction *NC;
1080 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1081 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
1082 Args.begin(), Args.end(),
1083 Caller->getName(), Caller);
1084 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1085 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1086 } else {
1087 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
1088 Caller->getName(), Caller);
1089 CallInst *CI = cast<CallInst>(Caller);
1090 if (CI->isTailCall())
1091 cast<CallInst>(NC)->setTailCall();
1092 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1093 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1094 }
1095
1096 // Insert a cast of the return type as necessary.
1097 Value *NV = NC;
1098 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1099 if (!NV->getType()->isVoidTy()) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001100 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Chris Lattner753a2b42010-01-05 07:32:13 +00001101 OldRetTy, false);
1102 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1103
1104 // If this is an invoke instruction, we should insert it after the first
1105 // non-phi, instruction in the normal successor block.
1106 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1107 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1108 InsertNewInstBefore(NC, *I);
1109 } else {
1110 // Otherwise, it's a call, just insert cast right after the call instr
1111 InsertNewInstBefore(NC, *Caller);
1112 }
1113 Worklist.AddUsersToWorkList(*Caller);
1114 } else {
1115 NV = UndefValue::get(Caller->getType());
1116 }
1117 }
1118
1119
1120 if (!Caller->use_empty())
1121 Caller->replaceAllUsesWith(NV);
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001122
Chris Lattner753a2b42010-01-05 07:32:13 +00001123 EraseInstFromFunction(*Caller);
1124 return true;
1125}
1126
1127// transformCallThroughTrampoline - Turn a call to a function created by the
1128// init_trampoline intrinsic into a direct call to the underlying function.
1129//
1130Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1131 Value *Callee = CS.getCalledValue();
1132 const PointerType *PTy = cast<PointerType>(Callee->getType());
1133 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1134 const AttrListPtr &Attrs = CS.getAttributes();
1135
1136 // If the call already has the 'nest' attribute somewhere then give up -
1137 // otherwise 'nest' would occur twice after splicing in the chain.
1138 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1139 return 0;
1140
1141 IntrinsicInst *Tramp =
1142 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1143
Gabor Greifcea7ac72010-06-24 12:58:35 +00001144 Function *NestF = cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Chris Lattner753a2b42010-01-05 07:32:13 +00001145 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1146 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1147
1148 const AttrListPtr &NestAttrs = NestF->getAttributes();
1149 if (!NestAttrs.isEmpty()) {
1150 unsigned NestIdx = 1;
1151 const Type *NestTy = 0;
1152 Attributes NestAttr = Attribute::None;
1153
1154 // Look for a parameter marked with the 'nest' attribute.
1155 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1156 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1157 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1158 // Record the parameter type and any other attributes.
1159 NestTy = *I;
1160 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1161 break;
1162 }
1163
1164 if (NestTy) {
1165 Instruction *Caller = CS.getInstruction();
1166 std::vector<Value*> NewArgs;
1167 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1168
1169 SmallVector<AttributeWithIndex, 8> NewAttrs;
1170 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1171
1172 // Insert the nest argument into the call argument list, which may
1173 // mean appending it. Likewise for attributes.
1174
1175 // Add any result attributes.
1176 if (Attributes Attr = Attrs.getRetAttributes())
1177 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1178
1179 {
1180 unsigned Idx = 1;
1181 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1182 do {
1183 if (Idx == NestIdx) {
1184 // Add the chain argument and attributes.
Gabor Greifcea7ac72010-06-24 12:58:35 +00001185 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner753a2b42010-01-05 07:32:13 +00001186 if (NestVal->getType() != NestTy)
1187 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1188 NewArgs.push_back(NestVal);
1189 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1190 }
1191
1192 if (I == E)
1193 break;
1194
1195 // Add the original argument and attributes.
1196 NewArgs.push_back(*I);
1197 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1198 NewAttrs.push_back
1199 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1200
1201 ++Idx, ++I;
1202 } while (1);
1203 }
1204
1205 // Add any function attributes.
1206 if (Attributes Attr = Attrs.getFnAttributes())
1207 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1208
1209 // The trampoline may have been bitcast to a bogus type (FTy).
1210 // Handle this by synthesizing a new function type, equal to FTy
1211 // with the chain parameter inserted.
1212
1213 std::vector<const Type*> NewTypes;
1214 NewTypes.reserve(FTy->getNumParams()+1);
1215
1216 // Insert the chain's type into the list of parameter types, which may
1217 // mean appending it.
1218 {
1219 unsigned Idx = 1;
1220 FunctionType::param_iterator I = FTy->param_begin(),
1221 E = FTy->param_end();
1222
1223 do {
1224 if (Idx == NestIdx)
1225 // Add the chain's type.
1226 NewTypes.push_back(NestTy);
1227
1228 if (I == E)
1229 break;
1230
1231 // Add the original type.
1232 NewTypes.push_back(*I);
1233
1234 ++Idx, ++I;
1235 } while (1);
1236 }
1237
1238 // Replace the trampoline call with a direct call. Let the generic
1239 // code sort out any function type mismatches.
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001240 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001241 FTy->isVarArg());
1242 Constant *NewCallee =
1243 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001244 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001245 PointerType::getUnqual(NewFTy));
1246 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1247 NewAttrs.end());
1248
1249 Instruction *NewCaller;
1250 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1251 NewCaller = InvokeInst::Create(NewCallee,
1252 II->getNormalDest(), II->getUnwindDest(),
1253 NewArgs.begin(), NewArgs.end(),
1254 Caller->getName(), Caller);
1255 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1256 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1257 } else {
1258 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1259 Caller->getName(), Caller);
1260 if (cast<CallInst>(Caller)->isTailCall())
1261 cast<CallInst>(NewCaller)->setTailCall();
1262 cast<CallInst>(NewCaller)->
1263 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1264 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1265 }
1266 if (!Caller->getType()->isVoidTy())
1267 Caller->replaceAllUsesWith(NewCaller);
1268 Caller->eraseFromParent();
1269 Worklist.Remove(Caller);
1270 return 0;
1271 }
1272 }
1273
1274 // Replace the trampoline call with a direct call. Since there is no 'nest'
1275 // parameter, there is no need to adjust the argument list. Let the generic
1276 // code sort out any function type mismatches.
1277 Constant *NewCallee =
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001278 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001279 ConstantExpr::getBitCast(NestF, PTy);
1280 CS.setCalledFunction(NewCallee);
1281 return CS.getInstruction();
1282}
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001283