blob: 57510ddca13dbb10310dc59686dd63145c4bf44f [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) {
Dan Gohman33591af2010-07-28 17:14:23 +000099 assert(V->getType()->isPointerTy() &&
100 "GetOrEnforceKnownAlignment expects a pointer!");
101 unsigned BitWidth = TD ? TD->getPointerSizeInBits() : 64;
Chris Lattner753a2b42010-01-05 07:32:13 +0000102 APInt Mask = APInt::getAllOnesValue(BitWidth);
103 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
104 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
105 unsigned TrailZ = KnownZero.countTrailingOnes();
Dan Gohman33591af2010-07-28 17:14:23 +0000106
Dan Gohman138aa2a2010-07-28 20:12:04 +0000107 // Avoid trouble with rediculously large TrailZ values, such as
108 // those computed from a null pointer.
Dan Gohman33591af2010-07-28 17:14:23 +0000109 TrailZ = std::min(TrailZ, unsigned(sizeof(unsigned) * CHAR_BIT - 1));
110
Chris Lattner753a2b42010-01-05 07:32:13 +0000111 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
112
Dan Gohman138aa2a2010-07-28 20:12:04 +0000113 // LLVM doesn't support alignments larger than this currently.
Dan Gohman795e70e2010-08-03 16:15:50 +0000114 Align = std::min(Align, +Value::MaximumAlignment);
Dan Gohman138aa2a2010-07-28 20:12:04 +0000115
Chris Lattner753a2b42010-01-05 07:32:13 +0000116 if (PrefAlign > Align)
117 Align = EnforceKnownAlignment(V, Align, PrefAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000118
Chris Lattner753a2b42010-01-05 07:32:13 +0000119 // We don't need to make any adjustment.
120 return Align;
121}
122
123Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Gabor Greifbcda85c2010-06-24 13:54:33 +0000124 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getArgOperand(0));
125 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getArgOperand(1));
Chris Lattner753a2b42010-01-05 07:32:13 +0000126 unsigned MinAlign = std::min(DstAlign, SrcAlign);
127 unsigned CopyAlign = MI->getAlignment();
128
129 if (CopyAlign < MinAlign) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000130 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Chris Lattner753a2b42010-01-05 07:32:13 +0000131 MinAlign, false));
132 return MI;
133 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000134
Chris Lattner753a2b42010-01-05 07:32:13 +0000135 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
136 // load/store.
Gabor Greifbcda85c2010-06-24 13:54:33 +0000137 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Chris Lattner753a2b42010-01-05 07:32:13 +0000138 if (MemOpLength == 0) return 0;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000139
Chris Lattner753a2b42010-01-05 07:32:13 +0000140 // Source and destination pointer types are always "i8*" for intrinsic. See
141 // if the size is something we can handle with a single primitive load/store.
142 // A single load+store correctly handles overlapping memory in the memmove
143 // case.
144 unsigned Size = MemOpLength->getZExtValue();
145 if (Size == 0) return MI; // Delete this mem transfer.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000146
Chris Lattner753a2b42010-01-05 07:32:13 +0000147 if (Size > 8 || (Size&(Size-1)))
148 return 0; // If not 1/2/4/8 bytes, exit.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000149
Chris Lattner753a2b42010-01-05 07:32:13 +0000150 // Use an integer load+store unless we can find something better.
Mon P Wang20adc9d2010-04-04 03:10:48 +0000151 unsigned SrcAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +0000152 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greif4ec22582010-04-16 15:33:14 +0000153 unsigned DstAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +0000154 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wang20adc9d2010-04-04 03:10:48 +0000155
156 const IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
157 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
158 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000159
Chris Lattner753a2b42010-01-05 07:32:13 +0000160 // Memcpy forces the use of i8* for the source and destination. That means
161 // that if you're using memcpy to move one double around, you'll get a cast
162 // from double* to i8*. We'd much rather use a double load+store rather than
163 // an i64 load+store, here because this improves the odds that the source or
164 // dest address will be promotable. See if we can find a better type than the
165 // integer datatype.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000166 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
167 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000168 const Type *SrcETy = cast<PointerType>(StrippedDest->getType())
169 ->getElementType();
170 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
171 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
172 // down through these levels if so.
173 while (!SrcETy->isSingleValueType()) {
174 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
175 if (STy->getNumElements() == 1)
176 SrcETy = STy->getElementType(0);
177 else
178 break;
179 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
180 if (ATy->getNumElements() == 1)
181 SrcETy = ATy->getElementType();
182 else
183 break;
184 } else
185 break;
186 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000187
Mon P Wang20adc9d2010-04-04 03:10:48 +0000188 if (SrcETy->isSingleValueType()) {
189 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
190 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
191 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000192 }
193 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000194
195
Chris Lattner753a2b42010-01-05 07:32:13 +0000196 // If the memcpy/memmove provides better alignment info than we can
197 // infer, use it.
198 SrcAlign = std::max(SrcAlign, CopyAlign);
199 DstAlign = std::max(DstAlign, CopyAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000200
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000201 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
202 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000203 Instruction *L = new LoadInst(Src, "tmp", MI->isVolatile(), SrcAlign);
Chris Lattner753a2b42010-01-05 07:32:13 +0000204 InsertNewInstBefore(L, *MI);
Mon P Wang20adc9d2010-04-04 03:10:48 +0000205 InsertNewInstBefore(new StoreInst(L, Dest, MI->isVolatile(), DstAlign),
206 *MI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000207
208 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000209 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000210 return MI;
211}
212
213Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
214 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
215 if (MI->getAlignment() < Alignment) {
216 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
217 Alignment, false));
218 return MI;
219 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000220
Chris Lattner753a2b42010-01-05 07:32:13 +0000221 // Extract the length and alignment and fill if they are constant.
222 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
223 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000224 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Chris Lattner753a2b42010-01-05 07:32:13 +0000225 return 0;
226 uint64_t Len = LenC->getZExtValue();
227 Alignment = MI->getAlignment();
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000228
Chris Lattner753a2b42010-01-05 07:32:13 +0000229 // If the length is zero, this is a no-op
230 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000231
Chris Lattner753a2b42010-01-05 07:32:13 +0000232 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
233 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
234 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000235
Chris Lattner753a2b42010-01-05 07:32:13 +0000236 Value *Dest = MI->getDest();
Mon P Wang55fb9b02010-12-20 01:05:30 +0000237 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
238 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
239 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner753a2b42010-01-05 07:32:13 +0000240
241 // Alignment 0 is identity for alignment 1 for memset, but not store.
242 if (Alignment == 0) Alignment = 1;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000243
Chris Lattner753a2b42010-01-05 07:32:13 +0000244 // Extract the fill value and store.
245 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
246 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
247 Dest, false, Alignment), *MI);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000248
Chris Lattner753a2b42010-01-05 07:32:13 +0000249 // Set the size of the copy to 0, it will be deleted on the next iteration.
250 MI->setLength(Constant::getNullValue(LenC->getType()));
251 return MI;
252 }
253
254 return 0;
255}
256
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000257/// visitCallInst - CallInst simplification. This mostly only handles folding
Chris Lattner753a2b42010-01-05 07:32:13 +0000258/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
259/// the heavy lifting.
260///
261Instruction *InstCombiner::visitCallInst(CallInst &CI) {
262 if (isFreeCall(&CI))
263 return visitFree(CI);
Duncan Sands1d9b9732010-05-27 19:09:06 +0000264 if (isMalloc(&CI))
265 return visitMalloc(CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000266
267 // If the caller function is nounwind, mark the call as nounwind, even if the
268 // callee isn't.
269 if (CI.getParent()->getParent()->doesNotThrow() &&
270 !CI.doesNotThrow()) {
271 CI.setDoesNotThrow();
272 return &CI;
273 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000274
Chris Lattner753a2b42010-01-05 07:32:13 +0000275 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
276 if (!II) return visitCallSite(&CI);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000277
Chris Lattner753a2b42010-01-05 07:32:13 +0000278 // Intrinsics cannot occur in an invoke, so handle them here instead of in
279 // visitCallSite.
280 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
281 bool Changed = false;
282
283 // memmove/cpy/set of zero bytes is a noop.
284 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattner6eff7512010-10-01 05:51:02 +0000285 if (NumBytes->isNullValue())
286 return EraseInstFromFunction(CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000287
288 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
289 if (CI->getZExtValue() == 1) {
290 // Replace the instruction with just byte operations. We would
291 // transform other cases to loads/stores, but we don't know if
292 // alignment is sufficient.
293 }
294 }
Chris Lattner6eff7512010-10-01 05:51:02 +0000295
296 // No other transformations apply to volatile transfers.
297 if (MI->isVolatile())
298 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000299
300 // If we have a memmove and the source operation is a constant global,
301 // then the source and dest pointers can't alias, so we can change this
302 // into a call to memcpy.
303 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
304 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
305 if (GVSrc->isConstant()) {
Eric Christopher551754c2010-04-16 23:37:20 +0000306 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner753a2b42010-01-05 07:32:13 +0000307 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Gabor Greifc310fcc2010-06-24 13:42:49 +0000308 const Type *Tys[3] = { CI.getArgOperand(0)->getType(),
309 CI.getArgOperand(1)->getType(),
310 CI.getArgOperand(2)->getType() };
311 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys, 3));
Chris Lattner753a2b42010-01-05 07:32:13 +0000312 Changed = true;
313 }
314 }
315
316 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
317 // memmove(x,x,size) -> noop.
318 if (MTI->getSource() == MTI->getDest())
319 return EraseInstFromFunction(CI);
Eric Christopher551754c2010-04-16 23:37:20 +0000320 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000321
Eric Christopher551754c2010-04-16 23:37:20 +0000322 // If we can determine a pointer alignment that is bigger than currently
323 // set, update the alignment.
324 if (isa<MemTransferInst>(MI)) {
325 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner753a2b42010-01-05 07:32:13 +0000326 return I;
327 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
328 if (Instruction *I = SimplifyMemSet(MSI))
329 return I;
330 }
Gabor Greifc310fcc2010-06-24 13:42:49 +0000331
Chris Lattner753a2b42010-01-05 07:32:13 +0000332 if (Changed) return II;
333 }
Eric Christopher551754c2010-04-16 23:37:20 +0000334
Chris Lattner753a2b42010-01-05 07:32:13 +0000335 switch (II->getIntrinsicID()) {
336 default: break;
Eric Christopher415326b2010-02-09 21:24:27 +0000337 case Intrinsic::objectsize: {
Eric Christopher26d0e892010-02-11 01:48:54 +0000338 // We need target data for just about everything so depend on it.
Eric Christopher415326b2010-02-09 21:24:27 +0000339 if (!TD) break;
Eric Christopher26d0e892010-02-11 01:48:54 +0000340
Evan Chenga8623262010-03-05 20:47:23 +0000341 const Type *ReturnTy = CI.getType();
Gabor Greifcea7ac72010-06-24 12:58:35 +0000342 bool Min = (cast<ConstantInt>(II->getArgOperand(1))->getZExtValue() == 1);
Evan Chenga8623262010-03-05 20:47:23 +0000343
Eric Christopher26d0e892010-02-11 01:48:54 +0000344 // Get to the real allocated thing and offset as fast as possible.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000345 Value *Op1 = II->getArgOperand(0)->stripPointerCasts();
Eric Christopher415326b2010-02-09 21:24:27 +0000346
Eric Christopher26d0e892010-02-11 01:48:54 +0000347 // If we've stripped down to a single global variable that we
348 // can know the size of then just return that.
Eric Christopher415326b2010-02-09 21:24:27 +0000349 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
350 if (GV->hasDefinitiveInitializer()) {
351 Constant *C = GV->getInitializer();
Evan Chenga8623262010-03-05 20:47:23 +0000352 uint64_t GlobalSize = TD->getTypeAllocSize(C->getType());
353 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, GlobalSize));
Eric Christopher415326b2010-02-09 21:24:27 +0000354 } else {
Evan Chenga8623262010-03-05 20:47:23 +0000355 // Can't determine size of the GV.
Eric Christopher415326b2010-02-09 21:24:27 +0000356 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
357 return ReplaceInstUsesWith(CI, RetVal);
358 }
Evan Chenga8623262010-03-05 20:47:23 +0000359 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
360 // Get alloca size.
361 if (AI->getAllocatedType()->isSized()) {
362 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
363 if (AI->isArrayAllocation()) {
364 const ConstantInt *C = dyn_cast<ConstantInt>(AI->getArraySize());
365 if (!C) break;
366 AllocaSize *= C->getZExtValue();
367 }
368 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, AllocaSize));
369 }
Evan Cheng687fed32010-03-08 22:54:36 +0000370 } else if (CallInst *MI = extractMallocCall(Op1)) {
371 const Type* MallocType = getMallocAllocatedType(MI);
372 // Get alloca size.
373 if (MallocType && MallocType->isSized()) {
374 if (Value *NElems = getMallocArraySize(MI, TD, true)) {
375 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
376 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy,
377 (NElements->getZExtValue() * TD->getTypeAllocSize(MallocType))));
378 }
379 }
Evan Chenga8623262010-03-05 20:47:23 +0000380 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
Eric Christopher26d0e892010-02-11 01:48:54 +0000381 // Only handle constant GEPs here.
382 if (CE->getOpcode() != Instruction::GetElementPtr) break;
383 GEPOperator *GEP = cast<GEPOperator>(CE);
384
Eric Christopherdfdddd82010-02-11 17:44:04 +0000385 // Make sure we're not a constant offset from an external
386 // global.
387 Value *Operand = GEP->getPointerOperand();
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000388 Operand = Operand->stripPointerCasts();
Eric Christopherdfdddd82010-02-11 17:44:04 +0000389 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
390 if (!GV->hasDefinitiveInitializer()) break;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000391
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000392 // Get what we're pointing to and its size.
393 const PointerType *BaseType =
Eric Christopherdfdddd82010-02-11 17:44:04 +0000394 cast<PointerType>(Operand->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000395 uint64_t Size = TD->getTypeAllocSize(BaseType->getElementType());
Eric Christopher26d0e892010-02-11 01:48:54 +0000396
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000397 // Get the current byte offset into the thing. Use the original
398 // operand in case we're looking through a bitcast.
Eric Christopher26d0e892010-02-11 01:48:54 +0000399 SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000400 const PointerType *OffsetType =
401 cast<PointerType>(GEP->getPointerOperand()->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000402 uint64_t Offset = TD->getIndexedOffset(OffsetType, &Ops[0], Ops.size());
Eric Christopher26d0e892010-02-11 01:48:54 +0000403
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000404 if (Size < Offset) {
405 // Out of bound reference? Negative index normalized to large
406 // index? Just return "I don't know".
407 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
408 return ReplaceInstUsesWith(CI, RetVal);
409 }
Eric Christopher26d0e892010-02-11 01:48:54 +0000410
411 Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
412 return ReplaceInstUsesWith(CI, RetVal);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000413 }
Evan Chenga8623262010-03-05 20:47:23 +0000414
415 // Do not return "I don't know" here. Later optimization passes could
416 // make it possible to evaluate objectsize to a constant.
Evan Chengf79d6242010-03-05 01:22:47 +0000417 break;
Eric Christopher415326b2010-02-09 21:24:27 +0000418 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000419 case Intrinsic::bswap:
420 // bswap(bswap(x)) -> x
Gabor Greifcea7ac72010-06-24 12:58:35 +0000421 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getArgOperand(0)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000422 if (Operand->getIntrinsicID() == Intrinsic::bswap)
Gabor Greifcea7ac72010-06-24 12:58:35 +0000423 return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000424
Chris Lattner753a2b42010-01-05 07:32:13 +0000425 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Gabor Greifcea7ac72010-06-24 12:58:35 +0000426 if (TruncInst *TI = dyn_cast<TruncInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000427 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
428 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
429 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
430 TI->getType()->getPrimitiveSizeInBits();
431 Value *CV = ConstantInt::get(Operand->getType(), C);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000432 Value *V = Builder->CreateLShr(Operand->getArgOperand(0), CV);
Chris Lattner753a2b42010-01-05 07:32:13 +0000433 return new TruncInst(V, TI->getType());
434 }
435 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000436
Chris Lattner753a2b42010-01-05 07:32:13 +0000437 break;
438 case Intrinsic::powi:
Gabor Greifcea7ac72010-06-24 12:58:35 +0000439 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000440 // powi(x, 0) -> 1.0
441 if (Power->isZero())
442 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
443 // powi(x, 1) -> x
444 if (Power->isOne())
Gabor Greifcea7ac72010-06-24 12:58:35 +0000445 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000446 // powi(x, -1) -> 1/x
447 if (Power->isAllOnesValue())
448 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greifcea7ac72010-06-24 12:58:35 +0000449 II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000450 }
451 break;
452 case Intrinsic::cttz: {
453 // If all bits below the first known one are known zero,
454 // this value is constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000455 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000456 uint32_t BitWidth = IT->getBitWidth();
457 APInt KnownZero(BitWidth, 0);
458 APInt KnownOne(BitWidth, 0);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000459 ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidth),
Chris Lattner753a2b42010-01-05 07:32:13 +0000460 KnownZero, KnownOne);
461 unsigned TrailingZeros = KnownOne.countTrailingZeros();
462 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
463 if ((Mask & KnownZero) == Mask)
464 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
465 APInt(BitWidth, TrailingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000466
Chris Lattner753a2b42010-01-05 07:32:13 +0000467 }
468 break;
469 case Intrinsic::ctlz: {
470 // If all bits above the first known one are known zero,
471 // this value is constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000472 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000473 uint32_t BitWidth = IT->getBitWidth();
474 APInt KnownZero(BitWidth, 0);
475 APInt KnownOne(BitWidth, 0);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000476 ComputeMaskedBits(II->getArgOperand(0), APInt::getAllOnesValue(BitWidth),
Chris Lattner753a2b42010-01-05 07:32:13 +0000477 KnownZero, KnownOne);
478 unsigned LeadingZeros = KnownOne.countLeadingZeros();
479 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
480 if ((Mask & KnownZero) == Mask)
481 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
482 APInt(BitWidth, LeadingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000483
Chris Lattner753a2b42010-01-05 07:32:13 +0000484 }
485 break;
486 case Intrinsic::uadd_with_overflow: {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000487 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
488 const IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000489 uint32_t BitWidth = IT->getBitWidth();
490 APInt Mask = APInt::getSignBit(BitWidth);
491 APInt LHSKnownZero(BitWidth, 0);
492 APInt LHSKnownOne(BitWidth, 0);
493 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
494 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
495 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
496
497 if (LHSKnownNegative || LHSKnownPositive) {
498 APInt RHSKnownZero(BitWidth, 0);
499 APInt RHSKnownOne(BitWidth, 0);
500 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
501 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
502 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
503 if (LHSKnownNegative && RHSKnownNegative) {
504 // The sign bit is set in both cases: this MUST overflow.
505 // Create a simple add instruction, and insert it into the struct.
506 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
507 Worklist.Add(Add);
508 Constant *V[] = {
509 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
510 };
511 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
512 return InsertValueInst::Create(Struct, Add, 0);
513 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000514
Chris Lattner753a2b42010-01-05 07:32:13 +0000515 if (LHSKnownPositive && RHSKnownPositive) {
516 // The sign bit is clear in both cases: this CANNOT overflow.
517 // Create a simple add instruction, and insert it into the struct.
518 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
519 Worklist.Add(Add);
520 Constant *V[] = {
521 UndefValue::get(LHS->getType()),
522 ConstantInt::getFalse(II->getContext())
523 };
524 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
525 return InsertValueInst::Create(Struct, Add, 0);
526 }
527 }
528 }
529 // FALL THROUGH uadd into sadd
530 case Intrinsic::sadd_with_overflow:
531 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000532 if (isa<Constant>(II->getArgOperand(0)) &&
533 !isa<Constant>(II->getArgOperand(1))) {
534 Value *LHS = II->getArgOperand(0);
535 II->setArgOperand(0, II->getArgOperand(1));
536 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000537 return II;
538 }
539
540 // X + undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000541 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000542 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000543
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000544 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000545 // X + 0 -> {X, false}
546 if (RHS->isZero()) {
547 Constant *V[] = {
Eli Friedman4fffb342010-08-09 20:49:43 +0000548 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000549 ConstantInt::getFalse(II->getContext())
550 };
551 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000552 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000553 }
554 }
555 break;
556 case Intrinsic::usub_with_overflow:
557 case Intrinsic::ssub_with_overflow:
558 // undef - X -> undef
559 // X - undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000560 if (isa<UndefValue>(II->getArgOperand(0)) ||
561 isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000562 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000563
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000564 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000565 // X - 0 -> {X, false}
566 if (RHS->isZero()) {
567 Constant *V[] = {
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000568 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000569 ConstantInt::getFalse(II->getContext())
570 };
571 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000572 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000573 }
574 }
575 break;
576 case Intrinsic::umul_with_overflow:
577 case Intrinsic::smul_with_overflow:
578 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000579 if (isa<Constant>(II->getArgOperand(0)) &&
580 !isa<Constant>(II->getArgOperand(1))) {
581 Value *LHS = II->getArgOperand(0);
582 II->setArgOperand(0, II->getArgOperand(1));
583 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000584 return II;
585 }
586
587 // X * undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000588 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000589 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000590
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000591 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000592 // X*0 -> {0, false}
593 if (RHSI->isZero())
594 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000595
Chris Lattner753a2b42010-01-05 07:32:13 +0000596 // X * 1 -> {X, false}
597 if (RHSI->equalsInt(1)) {
598 Constant *V[] = {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000599 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000600 ConstantInt::getFalse(II->getContext())
601 };
602 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000603 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000604 }
605 }
606 break;
607 case Intrinsic::ppc_altivec_lvx:
608 case Intrinsic::ppc_altivec_lvxl:
609 case Intrinsic::x86_sse_loadu_ps:
610 case Intrinsic::x86_sse2_loadu_pd:
611 case Intrinsic::x86_sse2_loadu_dq:
612 // Turn PPC lvx -> load if the pointer is known aligned.
613 // Turn X86 loadups -> load if the pointer is known aligned.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000614 if (GetOrEnforceKnownAlignment(II->getArgOperand(0), 16) >= 16) {
615 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner753a2b42010-01-05 07:32:13 +0000616 PointerType::getUnqual(II->getType()));
617 return new LoadInst(Ptr);
618 }
619 break;
620 case Intrinsic::ppc_altivec_stvx:
621 case Intrinsic::ppc_altivec_stvxl:
622 // Turn stvx -> store if the pointer is known aligned.
Gabor Greif2f1ab742010-06-24 15:51:11 +0000623 if (GetOrEnforceKnownAlignment(II->getArgOperand(1), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000624 const Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000625 PointerType::getUnqual(II->getArgOperand(0)->getType());
626 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
627 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000628 }
629 break;
630 case Intrinsic::x86_sse_storeu_ps:
631 case Intrinsic::x86_sse2_storeu_pd:
632 case Intrinsic::x86_sse2_storeu_dq:
633 // Turn X86 storeu -> store if the pointer is known aligned.
Gabor Greif2f1ab742010-06-24 15:51:11 +0000634 if (GetOrEnforceKnownAlignment(II->getArgOperand(0), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000635 const Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000636 PointerType::getUnqual(II->getArgOperand(1)->getType());
637 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
638 return new StoreInst(II->getArgOperand(1), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000639 }
640 break;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000641
Chris Lattner753a2b42010-01-05 07:32:13 +0000642 case Intrinsic::x86_sse_cvttss2si: {
643 // These intrinsics only demands the 0th element of its input vector. If
644 // we can simplify the input based on that, do so now.
645 unsigned VWidth =
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000646 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
Chris Lattner753a2b42010-01-05 07:32:13 +0000647 APInt DemandedElts(VWidth, 1);
648 APInt UndefElts(VWidth, 0);
Gabor Greifa3997812010-07-22 10:37:47 +0000649 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
650 DemandedElts, UndefElts)) {
Gabor Greifa90c5c72010-06-28 16:50:57 +0000651 II->setArgOperand(0, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000652 return II;
653 }
654 break;
655 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000656
Chris Lattner753a2b42010-01-05 07:32:13 +0000657 case Intrinsic::ppc_altivec_vperm:
658 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000659 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getArgOperand(2))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000660 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000661
Chris Lattner753a2b42010-01-05 07:32:13 +0000662 // Check that all of the elements are integer constants or undefs.
663 bool AllEltsOk = true;
664 for (unsigned i = 0; i != 16; ++i) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000665 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
Chris Lattner753a2b42010-01-05 07:32:13 +0000666 !isa<UndefValue>(Mask->getOperand(i))) {
667 AllEltsOk = false;
668 break;
669 }
670 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000671
Chris Lattner753a2b42010-01-05 07:32:13 +0000672 if (AllEltsOk) {
673 // Cast the input vectors to byte vectors.
Gabor Greifa3997812010-07-22 10:37:47 +0000674 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
675 Mask->getType());
676 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
677 Mask->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000678 Value *Result = UndefValue::get(Op0->getType());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000679
Chris Lattner753a2b42010-01-05 07:32:13 +0000680 // Only extract each element once.
681 Value *ExtractedElts[32];
682 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000683
Chris Lattner753a2b42010-01-05 07:32:13 +0000684 for (unsigned i = 0; i != 16; ++i) {
685 if (isa<UndefValue>(Mask->getOperand(i)))
686 continue;
687 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
688 Idx &= 31; // Match the hardware behavior.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000689
Chris Lattner753a2b42010-01-05 07:32:13 +0000690 if (ExtractedElts[Idx] == 0) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000691 ExtractedElts[Idx] =
692 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner753a2b42010-01-05 07:32:13 +0000693 ConstantInt::get(Type::getInt32Ty(II->getContext()),
694 Idx&15, false), "tmp");
695 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000696
Chris Lattner753a2b42010-01-05 07:32:13 +0000697 // Insert this value into the result vector.
698 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
699 ConstantInt::get(Type::getInt32Ty(II->getContext()),
700 i, false), "tmp");
701 }
702 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
703 }
704 }
705 break;
706
Bob Wilson364f17c2010-10-22 21:41:48 +0000707 case Intrinsic::arm_neon_vld1:
708 case Intrinsic::arm_neon_vld2:
709 case Intrinsic::arm_neon_vld3:
710 case Intrinsic::arm_neon_vld4:
711 case Intrinsic::arm_neon_vld2lane:
712 case Intrinsic::arm_neon_vld3lane:
713 case Intrinsic::arm_neon_vld4lane:
714 case Intrinsic::arm_neon_vst1:
715 case Intrinsic::arm_neon_vst2:
716 case Intrinsic::arm_neon_vst3:
717 case Intrinsic::arm_neon_vst4:
718 case Intrinsic::arm_neon_vst2lane:
719 case Intrinsic::arm_neon_vst3lane:
720 case Intrinsic::arm_neon_vst4lane: {
721 unsigned MemAlign = GetOrEnforceKnownAlignment(II->getArgOperand(0));
722 unsigned AlignArg = II->getNumArgOperands() - 1;
723 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
724 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
725 II->setArgOperand(AlignArg,
726 ConstantInt::get(Type::getInt32Ty(II->getContext()),
727 MemAlign, false));
728 return II;
729 }
730 break;
731 }
732
Chris Lattner753a2b42010-01-05 07:32:13 +0000733 case Intrinsic::stackrestore: {
734 // If the save is right next to the restore, remove the restore. This can
735 // happen when variable allocas are DCE'd.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000736 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000737 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
738 BasicBlock::iterator BI = SS;
739 if (&*++BI == II)
740 return EraseInstFromFunction(CI);
741 }
742 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000743
Chris Lattner753a2b42010-01-05 07:32:13 +0000744 // Scan down this block to see if there is another stack restore in the
745 // same block without an intervening call/alloca.
746 BasicBlock::iterator BI = II;
747 TerminatorInst *TI = II->getParent()->getTerminator();
748 bool CannotRemove = false;
749 for (++BI; &*BI != TI; ++BI) {
750 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
751 CannotRemove = true;
752 break;
753 }
754 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
755 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
756 // If there is a stackrestore below this one, remove this one.
757 if (II->getIntrinsicID() == Intrinsic::stackrestore)
758 return EraseInstFromFunction(CI);
759 // Otherwise, ignore the intrinsic.
760 } else {
761 // If we found a non-intrinsic call, we can't remove the stack
762 // restore.
763 CannotRemove = true;
764 break;
765 }
766 }
767 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000768
Chris Lattner753a2b42010-01-05 07:32:13 +0000769 // If the stack restore is in a return/unwind block and if there are no
770 // allocas or calls between the restore and the return, nuke the restore.
771 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
772 return EraseInstFromFunction(CI);
773 break;
774 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000775 }
776
777 return visitCallSite(II);
778}
779
780// InvokeInst simplification
781//
782Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
783 return visitCallSite(&II);
784}
785
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000786/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000787/// passed through the varargs area, we can eliminate the use of the cast.
788static bool isSafeToEliminateVarargsCast(const CallSite CS,
789 const CastInst * const CI,
790 const TargetData * const TD,
791 const int ix) {
792 if (!CI->isLosslessCast())
793 return false;
794
795 // The size of ByVal arguments is derived from the type, so we
796 // can't change to a type with a different size. If the size were
797 // passed explicitly we could avoid this check.
798 if (!CS.paramHasAttr(ix, Attribute::ByVal))
799 return true;
800
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000801 const Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000802 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
803 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
804 if (!SrcTy->isSized() || !DstTy->isSized())
805 return false;
806 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
807 return false;
808 return true;
809}
810
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000811namespace {
812class InstCombineFortifiedLibCalls : public SimplifyFortifiedLibCalls {
813 InstCombiner *IC;
814protected:
815 void replaceCall(Value *With) {
816 NewInstruction = IC->ReplaceInstUsesWith(*CI, With);
817 }
818 bool isFoldable(unsigned SizeCIOp, unsigned SizeArgOp, bool isString) const {
Gabor Greifa3997812010-07-22 10:37:47 +0000819 if (ConstantInt *SizeCI =
820 dyn_cast<ConstantInt>(CI->getArgOperand(SizeCIOp))) {
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000821 if (SizeCI->isAllOnesValue())
822 return true;
823 if (isString)
824 return SizeCI->getZExtValue() >=
Gabor Greifa6aac4c2010-07-16 09:38:02 +0000825 GetStringLength(CI->getArgOperand(SizeArgOp));
Gabor Greifa3997812010-07-22 10:37:47 +0000826 if (ConstantInt *Arg = dyn_cast<ConstantInt>(
827 CI->getArgOperand(SizeArgOp)))
Evan Cheng9d8f0022010-03-23 06:06:09 +0000828 return SizeCI->getZExtValue() >= Arg->getZExtValue();
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000829 }
830 return false;
831 }
832public:
833 InstCombineFortifiedLibCalls(InstCombiner *IC) : IC(IC), NewInstruction(0) { }
834 Instruction *NewInstruction;
835};
836} // end anonymous namespace
837
Eric Christopher27ceaa12010-03-06 10:50:38 +0000838// Try to fold some different type of calls here.
839// Currently we're only working with the checking functions, memcpy_chk,
840// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
841// strcat_chk and strncat_chk.
842Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData *TD) {
843 if (CI->getCalledFunction() == 0) return 0;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000844
Benjamin Kramer0b6cb502010-03-12 09:27:41 +0000845 InstCombineFortifiedLibCalls Simplifier(this);
846 Simplifier.fold(CI, TD);
847 return Simplifier.NewInstruction;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000848}
849
Chris Lattner753a2b42010-01-05 07:32:13 +0000850// visitCallSite - Improvements for call and invoke instructions.
851//
852Instruction *InstCombiner::visitCallSite(CallSite CS) {
853 bool Changed = false;
854
Chris Lattnerab215bc2010-12-20 08:25:06 +0000855 // If the callee is a pointer to a function, attempt to move any casts to the
856 // arguments of the call/invoke.
Chris Lattner753a2b42010-01-05 07:32:13 +0000857 Value *Callee = CS.getCalledValue();
Chris Lattnerab215bc2010-12-20 08:25:06 +0000858 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
859 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000860
861 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000862 // If the call and callee calling conventions don't match, this call must
863 // be unreachable, as the call is undefined.
864 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
865 // Only do this for calls to a function with a body. A prototype may
866 // not actually end up matching the implementation's calling conv for a
867 // variety of reasons (e.g. it may be written in assembly).
868 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000869 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000870 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000871 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000872 OldCall);
873 // If OldCall dues not return void then replaceAllUsesWith undef.
874 // This allows ValueHandlers and custom metadata to adjust itself.
875 if (!OldCall->getType()->isVoidTy())
876 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000877 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000878 return EraseInstFromFunction(*OldCall);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000879
Chris Lattner830f3f22010-02-01 18:04:58 +0000880 // We cannot remove an invoke, because it would change the CFG, just
881 // change the callee to a null pointer.
Gabor Greif654c06f2010-03-20 21:00:25 +0000882 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner830f3f22010-02-01 18:04:58 +0000883 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000884 return 0;
885 }
886
887 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
888 // This instruction is not reachable, just remove it. We insert a store to
889 // undef so that we know that this code is not reachable, despite the fact
890 // that we can't modify the CFG here.
891 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
892 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
893 CS.getInstruction());
894
Gabor Greifcea7ac72010-06-24 12:58:35 +0000895 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner753a2b42010-01-05 07:32:13 +0000896 // This allows ValueHandlers and custom metadata to adjust itself.
897 if (!CS.getInstruction()->getType()->isVoidTy())
898 CS.getInstruction()->
899 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
900
901 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
902 // Don't break the CFG, insert a dummy cond branch.
903 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
904 ConstantInt::getTrue(Callee->getContext()), II);
905 }
906 return EraseInstFromFunction(*CS.getInstruction());
907 }
908
909 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
910 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
911 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
912 return transformCallThroughTrampoline(CS);
913
914 const PointerType *PTy = cast<PointerType>(Callee->getType());
915 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
916 if (FTy->isVarArg()) {
917 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
918 // See if we can optimize any arguments passed through the varargs area of
919 // the call.
920 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
921 E = CS.arg_end(); I != E; ++I, ++ix) {
922 CastInst *CI = dyn_cast<CastInst>(*I);
923 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
924 *I = CI->getOperand(0);
925 Changed = true;
926 }
927 }
928 }
929
930 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
931 // Inline asm calls cannot throw - mark them 'nounwind'.
932 CS.setDoesNotThrow();
933 Changed = true;
934 }
935
Eric Christopher27ceaa12010-03-06 10:50:38 +0000936 // Try to optimize the call if possible, we require TargetData for most of
937 // this. None of these calls are seen as possibly dead so go ahead and
938 // delete the instruction now.
939 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
940 Instruction *I = tryOptimizeCall(CI, TD);
Eric Christopher7b323a32010-03-06 10:59:25 +0000941 // If we changed something return the result, etc. Otherwise let
942 // the fallthrough check.
943 if (I) return EraseInstFromFunction(*I);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000944 }
945
Chris Lattner753a2b42010-01-05 07:32:13 +0000946 return Changed ? CS.getInstruction() : 0;
947}
948
949// transformConstExprCastCall - If the callee is a constexpr cast of a function,
950// attempt to move the cast to the arguments of the call/invoke.
951//
952bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Chris Lattnerab215bc2010-12-20 08:25:06 +0000953 Function *Callee =
954 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
955 if (Callee == 0)
Chris Lattner753a2b42010-01-05 07:32:13 +0000956 return false;
Chris Lattner753a2b42010-01-05 07:32:13 +0000957 Instruction *Caller = CS.getInstruction();
958 const AttrListPtr &CallerPAL = CS.getAttributes();
959
960 // Okay, this is a cast from a function to a different type. Unless doing so
961 // would cause a type conversion of one of our arguments, change this call to
962 // be a direct call with arguments casted to the appropriate types.
963 //
964 const FunctionType *FT = Callee->getFunctionType();
965 const Type *OldRetTy = Caller->getType();
966 const Type *NewRetTy = FT->getReturnType();
967
Duncan Sands1df98592010-02-16 11:11:14 +0000968 if (NewRetTy->isStructTy())
Chris Lattner753a2b42010-01-05 07:32:13 +0000969 return false; // TODO: Handle multiple return values.
970
971 // Check to see if we are changing the return type...
972 if (OldRetTy != NewRetTy) {
973 if (Callee->isDeclaration() &&
974 // Conversion is ok if changing from one pointer type to another or from
975 // a pointer to an integer of the same size.
Duncan Sands1df98592010-02-16 11:11:14 +0000976 !((OldRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000977 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +0000978 (NewRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000979 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
980 return false; // Cannot transform this return value.
981
982 if (!Caller->use_empty() &&
983 // void -> non-void is handled specially
984 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
985 return false; // Cannot transform this return value.
986
987 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
988 Attributes RAttrs = CallerPAL.getRetAttributes();
989 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
990 return false; // Attribute not compatible with transformed value.
991 }
992
993 // If the callsite is an invoke instruction, and the return value is used by
994 // a PHI node in a successor, we cannot change the return type of the call
995 // because there is no place to put the cast instruction (without breaking
996 // the critical edge). Bail out in this case.
997 if (!Caller->use_empty())
998 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
999 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
1000 UI != E; ++UI)
1001 if (PHINode *PN = dyn_cast<PHINode>(*UI))
1002 if (PN->getParent() == II->getNormalDest() ||
1003 PN->getParent() == II->getUnwindDest())
1004 return false;
1005 }
1006
1007 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1008 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1009
1010 CallSite::arg_iterator AI = CS.arg_begin();
1011 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1012 const Type *ParamTy = FT->getParamType(i);
1013 const Type *ActTy = (*AI)->getType();
1014
1015 if (!CastInst::isCastable(ActTy, ParamTy))
1016 return false; // Cannot transform this parameter value.
1017
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001018 if (CallerPAL.getParamAttributes(i + 1)
Chris Lattner753a2b42010-01-05 07:32:13 +00001019 & Attribute::typeIncompatible(ParamTy))
1020 return false; // Attribute not compatible with transformed value.
1021
1022 // Converting from one pointer type to another or between a pointer and an
1023 // integer of the same size is safe even if we do not have a body.
1024 bool isConvertible = ActTy == ParamTy ||
Duncan Sands1df98592010-02-16 11:11:14 +00001025 (TD && ((ParamTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001026 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001027 (ActTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001028 ActTy == TD->getIntPtrType(Caller->getContext()))));
1029 if (Callee->isDeclaration() && !isConvertible) return false;
1030 }
1031
1032 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1033 Callee->isDeclaration())
1034 return false; // Do not delete arguments unless we have a function body.
1035
1036 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1037 !CallerPAL.isEmpty())
1038 // In this case we have more arguments than the new function type, but we
1039 // won't be dropping them. Check that these extra arguments have attributes
1040 // that are compatible with being a vararg call argument.
1041 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1042 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1043 break;
1044 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1045 if (PAttrs & Attribute::VarArgsIncompatible)
1046 return false;
1047 }
1048
1049 // Okay, we decided that this is a safe thing to do: go ahead and start
1050 // inserting cast instructions as necessary...
1051 std::vector<Value*> Args;
1052 Args.reserve(NumActualArgs);
1053 SmallVector<AttributeWithIndex, 8> attrVec;
1054 attrVec.reserve(NumCommonArgs);
1055
1056 // Get any return attributes.
1057 Attributes RAttrs = CallerPAL.getRetAttributes();
1058
1059 // If the return value is not being used, the type may not be compatible
1060 // with the existing attributes. Wipe out any problematic attributes.
1061 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
1062
1063 // Add the new return attributes.
1064 if (RAttrs)
1065 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
1066
1067 AI = CS.arg_begin();
1068 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1069 const Type *ParamTy = FT->getParamType(i);
1070 if ((*AI)->getType() == ParamTy) {
1071 Args.push_back(*AI);
1072 } else {
1073 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1074 false, ParamTy, false);
1075 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
1076 }
1077
1078 // Add any parameter attributes.
1079 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1080 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1081 }
1082
1083 // If the function takes more arguments than the call was taking, add them
1084 // now.
1085 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1086 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1087
1088 // If we are removing arguments to the function, emit an obnoxious warning.
1089 if (FT->getNumParams() < NumActualArgs) {
1090 if (!FT->isVarArg()) {
1091 errs() << "WARNING: While resolving call to function '"
1092 << Callee->getName() << "' arguments were dropped!\n";
1093 } else {
1094 // Add all of the arguments in their promoted form to the arg list.
1095 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1096 const Type *PTy = getPromotedType((*AI)->getType());
1097 if (PTy != (*AI)->getType()) {
1098 // Must promote to pass through va_arg area!
1099 Instruction::CastOps opcode =
1100 CastInst::getCastOpcode(*AI, false, PTy, false);
1101 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
1102 } else {
1103 Args.push_back(*AI);
1104 }
1105
1106 // Add any parameter attributes.
1107 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1108 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1109 }
1110 }
1111 }
1112
1113 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
1114 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1115
1116 if (NewRetTy->isVoidTy())
1117 Caller->setName(""); // Void type should not have a name.
1118
1119 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
1120 attrVec.end());
1121
1122 Instruction *NC;
1123 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1124 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
1125 Args.begin(), Args.end(),
1126 Caller->getName(), Caller);
1127 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1128 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1129 } else {
1130 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
1131 Caller->getName(), Caller);
1132 CallInst *CI = cast<CallInst>(Caller);
1133 if (CI->isTailCall())
1134 cast<CallInst>(NC)->setTailCall();
1135 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1136 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1137 }
1138
1139 // Insert a cast of the return type as necessary.
1140 Value *NV = NC;
1141 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1142 if (!NV->getType()->isVoidTy()) {
Chris Lattnerab215bc2010-12-20 08:25:06 +00001143 Instruction::CastOps opcode =
1144 CastInst::getCastOpcode(NC, false, OldRetTy, false);
Chris Lattner753a2b42010-01-05 07:32:13 +00001145 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1146
1147 // If this is an invoke instruction, we should insert it after the first
1148 // non-phi, instruction in the normal successor block.
1149 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1150 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1151 InsertNewInstBefore(NC, *I);
1152 } else {
Chris Lattnerab215bc2010-12-20 08:25:06 +00001153 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner753a2b42010-01-05 07:32:13 +00001154 InsertNewInstBefore(NC, *Caller);
1155 }
1156 Worklist.AddUsersToWorkList(*Caller);
1157 } else {
1158 NV = UndefValue::get(Caller->getType());
1159 }
1160 }
1161
Chris Lattner753a2b42010-01-05 07:32:13 +00001162 if (!Caller->use_empty())
1163 Caller->replaceAllUsesWith(NV);
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001164
Chris Lattner753a2b42010-01-05 07:32:13 +00001165 EraseInstFromFunction(*Caller);
1166 return true;
1167}
1168
1169// transformCallThroughTrampoline - Turn a call to a function created by the
1170// init_trampoline intrinsic into a direct call to the underlying function.
1171//
1172Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1173 Value *Callee = CS.getCalledValue();
1174 const PointerType *PTy = cast<PointerType>(Callee->getType());
1175 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1176 const AttrListPtr &Attrs = CS.getAttributes();
1177
1178 // If the call already has the 'nest' attribute somewhere then give up -
1179 // otherwise 'nest' would occur twice after splicing in the chain.
1180 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1181 return 0;
1182
1183 IntrinsicInst *Tramp =
1184 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1185
Gabor Greifa3997812010-07-22 10:37:47 +00001186 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Chris Lattner753a2b42010-01-05 07:32:13 +00001187 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1188 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1189
1190 const AttrListPtr &NestAttrs = NestF->getAttributes();
1191 if (!NestAttrs.isEmpty()) {
1192 unsigned NestIdx = 1;
1193 const Type *NestTy = 0;
1194 Attributes NestAttr = Attribute::None;
1195
1196 // Look for a parameter marked with the 'nest' attribute.
1197 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1198 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1199 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1200 // Record the parameter type and any other attributes.
1201 NestTy = *I;
1202 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1203 break;
1204 }
1205
1206 if (NestTy) {
1207 Instruction *Caller = CS.getInstruction();
1208 std::vector<Value*> NewArgs;
1209 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1210
1211 SmallVector<AttributeWithIndex, 8> NewAttrs;
1212 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1213
1214 // Insert the nest argument into the call argument list, which may
1215 // mean appending it. Likewise for attributes.
1216
1217 // Add any result attributes.
1218 if (Attributes Attr = Attrs.getRetAttributes())
1219 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1220
1221 {
1222 unsigned Idx = 1;
1223 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1224 do {
1225 if (Idx == NestIdx) {
1226 // Add the chain argument and attributes.
Gabor Greifcea7ac72010-06-24 12:58:35 +00001227 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner753a2b42010-01-05 07:32:13 +00001228 if (NestVal->getType() != NestTy)
1229 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1230 NewArgs.push_back(NestVal);
1231 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1232 }
1233
1234 if (I == E)
1235 break;
1236
1237 // Add the original argument and attributes.
1238 NewArgs.push_back(*I);
1239 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1240 NewAttrs.push_back
1241 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1242
1243 ++Idx, ++I;
1244 } while (1);
1245 }
1246
1247 // Add any function attributes.
1248 if (Attributes Attr = Attrs.getFnAttributes())
1249 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1250
1251 // The trampoline may have been bitcast to a bogus type (FTy).
1252 // Handle this by synthesizing a new function type, equal to FTy
1253 // with the chain parameter inserted.
1254
1255 std::vector<const Type*> NewTypes;
1256 NewTypes.reserve(FTy->getNumParams()+1);
1257
1258 // Insert the chain's type into the list of parameter types, which may
1259 // mean appending it.
1260 {
1261 unsigned Idx = 1;
1262 FunctionType::param_iterator I = FTy->param_begin(),
1263 E = FTy->param_end();
1264
1265 do {
1266 if (Idx == NestIdx)
1267 // Add the chain's type.
1268 NewTypes.push_back(NestTy);
1269
1270 if (I == E)
1271 break;
1272
1273 // Add the original type.
1274 NewTypes.push_back(*I);
1275
1276 ++Idx, ++I;
1277 } while (1);
1278 }
1279
1280 // Replace the trampoline call with a direct call. Let the generic
1281 // code sort out any function type mismatches.
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001282 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001283 FTy->isVarArg());
1284 Constant *NewCallee =
1285 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001286 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001287 PointerType::getUnqual(NewFTy));
1288 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1289 NewAttrs.end());
1290
1291 Instruction *NewCaller;
1292 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1293 NewCaller = InvokeInst::Create(NewCallee,
1294 II->getNormalDest(), II->getUnwindDest(),
1295 NewArgs.begin(), NewArgs.end(),
1296 Caller->getName(), Caller);
1297 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1298 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1299 } else {
1300 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1301 Caller->getName(), Caller);
1302 if (cast<CallInst>(Caller)->isTailCall())
1303 cast<CallInst>(NewCaller)->setTailCall();
1304 cast<CallInst>(NewCaller)->
1305 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1306 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1307 }
1308 if (!Caller->getType()->isVoidTy())
1309 Caller->replaceAllUsesWith(NewCaller);
1310 Caller->eraseFromParent();
1311 Worklist.Remove(Caller);
1312 return 0;
1313 }
1314 }
1315
1316 // Replace the trampoline call with a direct call. Since there is no 'nest'
1317 // parameter, there is no need to adjust the argument list. Let the generic
1318 // code sort out any function type mismatches.
1319 Constant *NewCallee =
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001320 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001321 ConstantExpr::getBitCast(NestF, PTy);
1322 CS.setCalledFunction(NewCallee);
1323 return CS.getInstruction();
1324}
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001325