blob: c62155ed02d864b67621ee145706e7b917013a2a [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 }
62 break;
63 }
64 }
65
66 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
67 // If there is a large requested alignment and we can, bump up the alignment
68 // of the global.
69 if (!GV->isDeclaration()) {
70 if (GV->getAlignment() >= PrefAlign)
71 Align = GV->getAlignment();
72 else {
73 GV->setAlignment(PrefAlign);
74 Align = PrefAlign;
75 }
76 }
77 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
78 // If there is a requested alignment and if this is an alloca, round up.
79 if (AI->getAlignment() >= PrefAlign)
80 Align = AI->getAlignment();
81 else {
82 AI->setAlignment(PrefAlign);
83 Align = PrefAlign;
84 }
85 }
86
87 return Align;
88}
89
90/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
91/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
92/// and it is more than the alignment of the ultimate object, see if we can
93/// increase the alignment of the ultimate object, making this check succeed.
94unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
95 unsigned PrefAlign) {
96 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
97 sizeof(PrefAlign) * CHAR_BIT;
98 APInt Mask = APInt::getAllOnesValue(BitWidth);
99 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
100 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
101 unsigned TrailZ = KnownZero.countTrailingOnes();
102 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
103
104 if (PrefAlign > Align)
105 Align = EnforceKnownAlignment(V, Align, PrefAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000106
Chris Lattner753a2b42010-01-05 07:32:13 +0000107 // We don't need to make any adjustment.
108 return Align;
109}
110
111Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
112 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
113 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
114 unsigned MinAlign = std::min(DstAlign, SrcAlign);
115 unsigned CopyAlign = MI->getAlignment();
116
117 if (CopyAlign < MinAlign) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000118 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Chris Lattner753a2b42010-01-05 07:32:13 +0000119 MinAlign, false));
120 return MI;
121 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000122
Chris Lattner753a2b42010-01-05 07:32:13 +0000123 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
124 // load/store.
125 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
126 if (MemOpLength == 0) return 0;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000127
Chris Lattner753a2b42010-01-05 07:32:13 +0000128 // Source and destination pointer types are always "i8*" for intrinsic. See
129 // if the size is something we can handle with a single primitive load/store.
130 // A single load+store correctly handles overlapping memory in the memmove
131 // case.
132 unsigned Size = MemOpLength->getZExtValue();
133 if (Size == 0) return MI; // Delete this mem transfer.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000134
Chris Lattner753a2b42010-01-05 07:32:13 +0000135 if (Size > 8 || (Size&(Size-1)))
136 return 0; // If not 1/2/4/8 bytes, exit.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000137
Chris Lattner753a2b42010-01-05 07:32:13 +0000138 // Use an integer load+store unless we can find something better.
139 Type *NewPtrTy =
140 PointerType::getUnqual(IntegerType::get(MI->getContext(), Size<<3));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000141
Chris Lattner753a2b42010-01-05 07:32:13 +0000142 // Memcpy forces the use of i8* for the source and destination. That means
143 // that if you're using memcpy to move one double around, you'll get a cast
144 // from double* to i8*. We'd much rather use a double load+store rather than
145 // an i64 load+store, here because this improves the odds that the source or
146 // dest address will be promotable. See if we can find a better type than the
147 // integer datatype.
148 Value *StrippedDest = MI->getOperand(1)->stripPointerCasts();
149 if (StrippedDest != MI->getOperand(1)) {
150 const Type *SrcETy = cast<PointerType>(StrippedDest->getType())
151 ->getElementType();
152 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
153 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
154 // down through these levels if so.
155 while (!SrcETy->isSingleValueType()) {
156 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
157 if (STy->getNumElements() == 1)
158 SrcETy = STy->getElementType(0);
159 else
160 break;
161 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
162 if (ATy->getNumElements() == 1)
163 SrcETy = ATy->getElementType();
164 else
165 break;
166 } else
167 break;
168 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000169
Chris Lattner753a2b42010-01-05 07:32:13 +0000170 if (SrcETy->isSingleValueType())
171 NewPtrTy = PointerType::getUnqual(SrcETy);
172 }
173 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000174
175
Chris Lattner753a2b42010-01-05 07:32:13 +0000176 // If the memcpy/memmove provides better alignment info than we can
177 // infer, use it.
178 SrcAlign = std::max(SrcAlign, CopyAlign);
179 DstAlign = std::max(DstAlign, CopyAlign);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000180
Chris Lattner753a2b42010-01-05 07:32:13 +0000181 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
182 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
183 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
184 InsertNewInstBefore(L, *MI);
185 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
186
187 // Set the size of the copy to 0, it will be deleted on the next iteration.
188 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
189 return MI;
190}
191
192Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
193 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
194 if (MI->getAlignment() < Alignment) {
195 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
196 Alignment, false));
197 return MI;
198 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000199
Chris Lattner753a2b42010-01-05 07:32:13 +0000200 // Extract the length and alignment and fill if they are constant.
201 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
202 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000203 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Chris Lattner753a2b42010-01-05 07:32:13 +0000204 return 0;
205 uint64_t Len = LenC->getZExtValue();
206 Alignment = MI->getAlignment();
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000207
Chris Lattner753a2b42010-01-05 07:32:13 +0000208 // If the length is zero, this is a no-op
209 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000210
Chris Lattner753a2b42010-01-05 07:32:13 +0000211 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
212 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
213 const Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000214
Chris Lattner753a2b42010-01-05 07:32:13 +0000215 Value *Dest = MI->getDest();
216 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
217
218 // Alignment 0 is identity for alignment 1 for memset, but not store.
219 if (Alignment == 0) Alignment = 1;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000220
Chris Lattner753a2b42010-01-05 07:32:13 +0000221 // Extract the fill value and store.
222 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
223 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
224 Dest, false, Alignment), *MI);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000225
Chris Lattner753a2b42010-01-05 07:32:13 +0000226 // Set the size of the copy to 0, it will be deleted on the next iteration.
227 MI->setLength(Constant::getNullValue(LenC->getType()));
228 return MI;
229 }
230
231 return 0;
232}
233
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000234/// visitCallInst - CallInst simplification. This mostly only handles folding
Chris Lattner753a2b42010-01-05 07:32:13 +0000235/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
236/// the heavy lifting.
237///
238Instruction *InstCombiner::visitCallInst(CallInst &CI) {
239 if (isFreeCall(&CI))
240 return visitFree(CI);
241
242 // If the caller function is nounwind, mark the call as nounwind, even if the
243 // callee isn't.
244 if (CI.getParent()->getParent()->doesNotThrow() &&
245 !CI.doesNotThrow()) {
246 CI.setDoesNotThrow();
247 return &CI;
248 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000249
Chris Lattner753a2b42010-01-05 07:32:13 +0000250 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
251 if (!II) return visitCallSite(&CI);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000252
Chris Lattner753a2b42010-01-05 07:32:13 +0000253 // Intrinsics cannot occur in an invoke, so handle them here instead of in
254 // visitCallSite.
255 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
256 bool Changed = false;
257
258 // memmove/cpy/set of zero bytes is a noop.
259 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
260 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
261
262 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
263 if (CI->getZExtValue() == 1) {
264 // Replace the instruction with just byte operations. We would
265 // transform other cases to loads/stores, but we don't know if
266 // alignment is sufficient.
267 }
268 }
269
270 // If we have a memmove and the source operation is a constant global,
271 // then the source and dest pointers can't alias, so we can change this
272 // into a call to memcpy.
273 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
274 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
275 if (GVSrc->isConstant()) {
276 Module *M = CI.getParent()->getParent()->getParent();
277 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
278 const Type *Tys[1];
279 Tys[0] = CI.getOperand(3)->getType();
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000280 CI.setOperand(0,
Chris Lattner753a2b42010-01-05 07:32:13 +0000281 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
282 Changed = true;
283 }
284 }
285
286 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
287 // memmove(x,x,size) -> noop.
288 if (MTI->getSource() == MTI->getDest())
289 return EraseInstFromFunction(CI);
290 }
291
292 // If we can determine a pointer alignment that is bigger than currently
293 // set, update the alignment.
294 if (isa<MemTransferInst>(MI)) {
295 if (Instruction *I = SimplifyMemTransfer(MI))
296 return I;
297 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
298 if (Instruction *I = SimplifyMemSet(MSI))
299 return I;
300 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000301
Chris Lattner753a2b42010-01-05 07:32:13 +0000302 if (Changed) return II;
303 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000304
Chris Lattner753a2b42010-01-05 07:32:13 +0000305 switch (II->getIntrinsicID()) {
306 default: break;
Eric Christopher415326b2010-02-09 21:24:27 +0000307 case Intrinsic::objectsize: {
Eric Christopher26d0e892010-02-11 01:48:54 +0000308 // We need target data for just about everything so depend on it.
Eric Christopher415326b2010-02-09 21:24:27 +0000309 if (!TD) break;
Eric Christopher26d0e892010-02-11 01:48:54 +0000310
Evan Chenga8623262010-03-05 20:47:23 +0000311 const Type *ReturnTy = CI.getType();
312 bool Min = (cast<ConstantInt>(II->getOperand(2))->getZExtValue() == 1);
313
Eric Christopher26d0e892010-02-11 01:48:54 +0000314 // Get to the real allocated thing and offset as fast as possible.
Evan Chenga8623262010-03-05 20:47:23 +0000315 Value *Op1 = II->getOperand(1)->stripPointerCasts();
Eric Christopher415326b2010-02-09 21:24:27 +0000316
Eric Christopher26d0e892010-02-11 01:48:54 +0000317 // If we've stripped down to a single global variable that we
318 // can know the size of then just return that.
Eric Christopher415326b2010-02-09 21:24:27 +0000319 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op1)) {
320 if (GV->hasDefinitiveInitializer()) {
321 Constant *C = GV->getInitializer();
Evan Chenga8623262010-03-05 20:47:23 +0000322 uint64_t GlobalSize = TD->getTypeAllocSize(C->getType());
323 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, GlobalSize));
Eric Christopher415326b2010-02-09 21:24:27 +0000324 } else {
Evan Chenga8623262010-03-05 20:47:23 +0000325 // Can't determine size of the GV.
Eric Christopher415326b2010-02-09 21:24:27 +0000326 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
327 return ReplaceInstUsesWith(CI, RetVal);
328 }
Evan Chenga8623262010-03-05 20:47:23 +0000329 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Op1)) {
330 // Get alloca size.
331 if (AI->getAllocatedType()->isSized()) {
332 uint64_t AllocaSize = TD->getTypeAllocSize(AI->getAllocatedType());
333 if (AI->isArrayAllocation()) {
334 const ConstantInt *C = dyn_cast<ConstantInt>(AI->getArraySize());
335 if (!C) break;
336 AllocaSize *= C->getZExtValue();
337 }
338 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy, AllocaSize));
339 }
Evan Cheng687fed32010-03-08 22:54:36 +0000340 } else if (CallInst *MI = extractMallocCall(Op1)) {
341 const Type* MallocType = getMallocAllocatedType(MI);
342 // Get alloca size.
343 if (MallocType && MallocType->isSized()) {
344 if (Value *NElems = getMallocArraySize(MI, TD, true)) {
345 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
346 return ReplaceInstUsesWith(CI, ConstantInt::get(ReturnTy,
347 (NElements->getZExtValue() * TD->getTypeAllocSize(MallocType))));
348 }
349 }
Evan Chenga8623262010-03-05 20:47:23 +0000350 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op1)) {
Eric Christopher26d0e892010-02-11 01:48:54 +0000351 // Only handle constant GEPs here.
352 if (CE->getOpcode() != Instruction::GetElementPtr) break;
353 GEPOperator *GEP = cast<GEPOperator>(CE);
354
Eric Christopherdfdddd82010-02-11 17:44:04 +0000355 // Make sure we're not a constant offset from an external
356 // global.
357 Value *Operand = GEP->getPointerOperand();
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000358 Operand = Operand->stripPointerCasts();
Eric Christopherdfdddd82010-02-11 17:44:04 +0000359 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Operand))
360 if (!GV->hasDefinitiveInitializer()) break;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000361
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000362 // Get what we're pointing to and its size.
363 const PointerType *BaseType =
Eric Christopherdfdddd82010-02-11 17:44:04 +0000364 cast<PointerType>(Operand->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000365 uint64_t Size = TD->getTypeAllocSize(BaseType->getElementType());
Eric Christopher26d0e892010-02-11 01:48:54 +0000366
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000367 // Get the current byte offset into the thing. Use the original
368 // operand in case we're looking through a bitcast.
Eric Christopher26d0e892010-02-11 01:48:54 +0000369 SmallVector<Value*, 8> Ops(CE->op_begin()+1, CE->op_end());
Eric Christopher77ffe3b2010-02-13 23:38:01 +0000370 const PointerType *OffsetType =
371 cast<PointerType>(GEP->getPointerOperand()->getType());
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000372 uint64_t Offset = TD->getIndexedOffset(OffsetType, &Ops[0], Ops.size());
Eric Christopher26d0e892010-02-11 01:48:54 +0000373
Evan Cheng6e5dfd42010-02-22 23:34:00 +0000374 if (Size < Offset) {
375 // Out of bound reference? Negative index normalized to large
376 // index? Just return "I don't know".
377 Constant *RetVal = ConstantInt::get(ReturnTy, Min ? 0 : -1ULL);
378 return ReplaceInstUsesWith(CI, RetVal);
379 }
Eric Christopher26d0e892010-02-11 01:48:54 +0000380
381 Constant *RetVal = ConstantInt::get(ReturnTy, Size-Offset);
382 return ReplaceInstUsesWith(CI, RetVal);
383
Eric Christopher27ceaa12010-03-06 10:50:38 +0000384 }
Evan Chenga8623262010-03-05 20:47:23 +0000385
386 // Do not return "I don't know" here. Later optimization passes could
387 // make it possible to evaluate objectsize to a constant.
Evan Chengf79d6242010-03-05 01:22:47 +0000388 break;
Eric Christopher415326b2010-02-09 21:24:27 +0000389 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000390 case Intrinsic::bswap:
391 // bswap(bswap(x)) -> x
392 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
393 if (Operand->getIntrinsicID() == Intrinsic::bswap)
394 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000395
Chris Lattner753a2b42010-01-05 07:32:13 +0000396 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
397 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
398 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
399 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
400 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
401 TI->getType()->getPrimitiveSizeInBits();
402 Value *CV = ConstantInt::get(Operand->getType(), C);
403 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
404 return new TruncInst(V, TI->getType());
405 }
406 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000407
Chris Lattner753a2b42010-01-05 07:32:13 +0000408 break;
409 case Intrinsic::powi:
410 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
411 // powi(x, 0) -> 1.0
412 if (Power->isZero())
413 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
414 // powi(x, 1) -> x
415 if (Power->isOne())
416 return ReplaceInstUsesWith(CI, II->getOperand(1));
417 // powi(x, -1) -> 1/x
418 if (Power->isAllOnesValue())
419 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
420 II->getOperand(1));
421 }
422 break;
423 case Intrinsic::cttz: {
424 // If all bits below the first known one are known zero,
425 // this value is constant.
426 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
427 uint32_t BitWidth = IT->getBitWidth();
428 APInt KnownZero(BitWidth, 0);
429 APInt KnownOne(BitWidth, 0);
430 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
431 KnownZero, KnownOne);
432 unsigned TrailingZeros = KnownOne.countTrailingZeros();
433 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
434 if ((Mask & KnownZero) == Mask)
435 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
436 APInt(BitWidth, TrailingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000437
Chris Lattner753a2b42010-01-05 07:32:13 +0000438 }
439 break;
440 case Intrinsic::ctlz: {
441 // If all bits above the first known one are known zero,
442 // this value is constant.
443 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
444 uint32_t BitWidth = IT->getBitWidth();
445 APInt KnownZero(BitWidth, 0);
446 APInt KnownOne(BitWidth, 0);
447 ComputeMaskedBits(II->getOperand(1), APInt::getAllOnesValue(BitWidth),
448 KnownZero, KnownOne);
449 unsigned LeadingZeros = KnownOne.countLeadingZeros();
450 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
451 if ((Mask & KnownZero) == Mask)
452 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
453 APInt(BitWidth, LeadingZeros)));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000454
Chris Lattner753a2b42010-01-05 07:32:13 +0000455 }
456 break;
457 case Intrinsic::uadd_with_overflow: {
458 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
459 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
460 uint32_t BitWidth = IT->getBitWidth();
461 APInt Mask = APInt::getSignBit(BitWidth);
462 APInt LHSKnownZero(BitWidth, 0);
463 APInt LHSKnownOne(BitWidth, 0);
464 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
465 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
466 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
467
468 if (LHSKnownNegative || LHSKnownPositive) {
469 APInt RHSKnownZero(BitWidth, 0);
470 APInt RHSKnownOne(BitWidth, 0);
471 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
472 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
473 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
474 if (LHSKnownNegative && RHSKnownNegative) {
475 // The sign bit is set in both cases: this MUST overflow.
476 // Create a simple add instruction, and insert it into the struct.
477 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
478 Worklist.Add(Add);
479 Constant *V[] = {
480 UndefValue::get(LHS->getType()),ConstantInt::getTrue(II->getContext())
481 };
482 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
483 return InsertValueInst::Create(Struct, Add, 0);
484 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000485
Chris Lattner753a2b42010-01-05 07:32:13 +0000486 if (LHSKnownPositive && RHSKnownPositive) {
487 // The sign bit is clear in both cases: this CANNOT overflow.
488 // Create a simple add instruction, and insert it into the struct.
489 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
490 Worklist.Add(Add);
491 Constant *V[] = {
492 UndefValue::get(LHS->getType()),
493 ConstantInt::getFalse(II->getContext())
494 };
495 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
496 return InsertValueInst::Create(Struct, Add, 0);
497 }
498 }
499 }
500 // FALL THROUGH uadd into sadd
501 case Intrinsic::sadd_with_overflow:
502 // Canonicalize constants into the RHS.
503 if (isa<Constant>(II->getOperand(1)) &&
504 !isa<Constant>(II->getOperand(2))) {
505 Value *LHS = II->getOperand(1);
506 II->setOperand(1, II->getOperand(2));
507 II->setOperand(2, LHS);
508 return II;
509 }
510
511 // X + undef -> undef
512 if (isa<UndefValue>(II->getOperand(2)))
513 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000514
Chris Lattner753a2b42010-01-05 07:32:13 +0000515 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
516 // X + 0 -> {X, false}
517 if (RHS->isZero()) {
518 Constant *V[] = {
519 UndefValue::get(II->getOperand(0)->getType()),
520 ConstantInt::getFalse(II->getContext())
521 };
522 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
523 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
524 }
525 }
526 break;
527 case Intrinsic::usub_with_overflow:
528 case Intrinsic::ssub_with_overflow:
529 // undef - X -> undef
530 // X - undef -> undef
531 if (isa<UndefValue>(II->getOperand(1)) ||
532 isa<UndefValue>(II->getOperand(2)))
533 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000534
Chris Lattner753a2b42010-01-05 07:32:13 +0000535 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
536 // X - 0 -> {X, false}
537 if (RHS->isZero()) {
538 Constant *V[] = {
539 UndefValue::get(II->getOperand(1)->getType()),
540 ConstantInt::getFalse(II->getContext())
541 };
542 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
543 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
544 }
545 }
546 break;
547 case Intrinsic::umul_with_overflow:
548 case Intrinsic::smul_with_overflow:
549 // Canonicalize constants into the RHS.
550 if (isa<Constant>(II->getOperand(1)) &&
551 !isa<Constant>(II->getOperand(2))) {
552 Value *LHS = II->getOperand(1);
553 II->setOperand(1, II->getOperand(2));
554 II->setOperand(2, LHS);
555 return II;
556 }
557
558 // X * undef -> undef
559 if (isa<UndefValue>(II->getOperand(2)))
560 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000561
Chris Lattner753a2b42010-01-05 07:32:13 +0000562 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
563 // X*0 -> {0, false}
564 if (RHSI->isZero())
565 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000566
Chris Lattner753a2b42010-01-05 07:32:13 +0000567 // X * 1 -> {X, false}
568 if (RHSI->equalsInt(1)) {
569 Constant *V[] = {
570 UndefValue::get(II->getOperand(1)->getType()),
571 ConstantInt::getFalse(II->getContext())
572 };
573 Constant *Struct = ConstantStruct::get(II->getContext(), V, 2, false);
574 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
575 }
576 }
577 break;
578 case Intrinsic::ppc_altivec_lvx:
579 case Intrinsic::ppc_altivec_lvxl:
580 case Intrinsic::x86_sse_loadu_ps:
581 case Intrinsic::x86_sse2_loadu_pd:
582 case Intrinsic::x86_sse2_loadu_dq:
583 // Turn PPC lvx -> load if the pointer is known aligned.
584 // Turn X86 loadups -> load if the pointer is known aligned.
585 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
586 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
587 PointerType::getUnqual(II->getType()));
588 return new LoadInst(Ptr);
589 }
590 break;
591 case Intrinsic::ppc_altivec_stvx:
592 case Intrinsic::ppc_altivec_stvxl:
593 // Turn stvx -> store if the pointer is known aligned.
594 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000595 const Type *OpPtrTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000596 PointerType::getUnqual(II->getOperand(1)->getType());
597 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
598 return new StoreInst(II->getOperand(1), Ptr);
599 }
600 break;
601 case Intrinsic::x86_sse_storeu_ps:
602 case Intrinsic::x86_sse2_storeu_pd:
603 case Intrinsic::x86_sse2_storeu_dq:
604 // Turn X86 storeu -> store if the pointer is known aligned.
605 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000606 const Type *OpPtrTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000607 PointerType::getUnqual(II->getOperand(2)->getType());
608 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
609 return new StoreInst(II->getOperand(2), Ptr);
610 }
611 break;
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000612
Chris Lattner753a2b42010-01-05 07:32:13 +0000613 case Intrinsic::x86_sse_cvttss2si: {
614 // These intrinsics only demands the 0th element of its input vector. If
615 // we can simplify the input based on that, do so now.
616 unsigned VWidth =
617 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
618 APInt DemandedElts(VWidth, 1);
619 APInt UndefElts(VWidth, 0);
620 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
621 UndefElts)) {
622 II->setOperand(1, V);
623 return II;
624 }
625 break;
626 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000627
Chris Lattner753a2b42010-01-05 07:32:13 +0000628 case Intrinsic::ppc_altivec_vperm:
629 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
630 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
631 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000632
Chris Lattner753a2b42010-01-05 07:32:13 +0000633 // Check that all of the elements are integer constants or undefs.
634 bool AllEltsOk = true;
635 for (unsigned i = 0; i != 16; ++i) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000636 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
Chris Lattner753a2b42010-01-05 07:32:13 +0000637 !isa<UndefValue>(Mask->getOperand(i))) {
638 AllEltsOk = false;
639 break;
640 }
641 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000642
Chris Lattner753a2b42010-01-05 07:32:13 +0000643 if (AllEltsOk) {
644 // Cast the input vectors to byte vectors.
645 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
646 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
647 Value *Result = UndefValue::get(Op0->getType());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000648
Chris Lattner753a2b42010-01-05 07:32:13 +0000649 // Only extract each element once.
650 Value *ExtractedElts[32];
651 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000652
Chris Lattner753a2b42010-01-05 07:32:13 +0000653 for (unsigned i = 0; i != 16; ++i) {
654 if (isa<UndefValue>(Mask->getOperand(i)))
655 continue;
656 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
657 Idx &= 31; // Match the hardware behavior.
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000658
Chris Lattner753a2b42010-01-05 07:32:13 +0000659 if (ExtractedElts[Idx] == 0) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000660 ExtractedElts[Idx] =
661 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
Chris Lattner753a2b42010-01-05 07:32:13 +0000662 ConstantInt::get(Type::getInt32Ty(II->getContext()),
663 Idx&15, false), "tmp");
664 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000665
Chris Lattner753a2b42010-01-05 07:32:13 +0000666 // Insert this value into the result vector.
667 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
668 ConstantInt::get(Type::getInt32Ty(II->getContext()),
669 i, false), "tmp");
670 }
671 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
672 }
673 }
674 break;
675
676 case Intrinsic::stackrestore: {
677 // If the save is right next to the restore, remove the restore. This can
678 // happen when variable allocas are DCE'd.
679 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
680 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
681 BasicBlock::iterator BI = SS;
682 if (&*++BI == II)
683 return EraseInstFromFunction(CI);
684 }
685 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000686
Chris Lattner753a2b42010-01-05 07:32:13 +0000687 // Scan down this block to see if there is another stack restore in the
688 // same block without an intervening call/alloca.
689 BasicBlock::iterator BI = II;
690 TerminatorInst *TI = II->getParent()->getTerminator();
691 bool CannotRemove = false;
692 for (++BI; &*BI != TI; ++BI) {
693 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
694 CannotRemove = true;
695 break;
696 }
697 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
698 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
699 // If there is a stackrestore below this one, remove this one.
700 if (II->getIntrinsicID() == Intrinsic::stackrestore)
701 return EraseInstFromFunction(CI);
702 // Otherwise, ignore the intrinsic.
703 } else {
704 // If we found a non-intrinsic call, we can't remove the stack
705 // restore.
706 CannotRemove = true;
707 break;
708 }
709 }
710 }
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000711
Chris Lattner753a2b42010-01-05 07:32:13 +0000712 // If the stack restore is in a return/unwind block and if there are no
713 // allocas or calls between the restore and the return, nuke the restore.
714 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
715 return EraseInstFromFunction(CI);
716 break;
717 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000718 }
719
720 return visitCallSite(II);
721}
722
723// InvokeInst simplification
724//
725Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
726 return visitCallSite(&II);
727}
728
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000729/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000730/// passed through the varargs area, we can eliminate the use of the cast.
731static bool isSafeToEliminateVarargsCast(const CallSite CS,
732 const CastInst * const CI,
733 const TargetData * const TD,
734 const int ix) {
735 if (!CI->isLosslessCast())
736 return false;
737
738 // The size of ByVal arguments is derived from the type, so we
739 // can't change to a type with a different size. If the size were
740 // passed explicitly we could avoid this check.
741 if (!CS.paramHasAttr(ix, Attribute::ByVal))
742 return true;
743
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000744 const Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000745 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
746 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
747 if (!SrcTy->isSized() || !DstTy->isSized())
748 return false;
749 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
750 return false;
751 return true;
752}
753
Eric Christopher27ceaa12010-03-06 10:50:38 +0000754// Try to fold some different type of calls here.
755// Currently we're only working with the checking functions, memcpy_chk,
756// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
757// strcat_chk and strncat_chk.
758Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const TargetData *TD) {
759 if (CI->getCalledFunction() == 0) return 0;
760
761 StringRef Name = CI->getCalledFunction()->getName();
762 BasicBlock *BB = CI->getParent();
763 IRBuilder<> B(CI->getParent()->getContext());
764
765 // Set the builder to the instruction after the call.
766 B.SetInsertPoint(BB, CI);
767
768 if (Name == "__memcpy_chk") {
769 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
770 if (!SizeCI)
771 return 0;
772 ConstantInt *SizeArg = dyn_cast<ConstantInt>(CI->getOperand(3));
773 if (!SizeArg)
774 return 0;
775 if (SizeCI->isAllOnesValue() ||
776 SizeCI->getZExtValue() <= SizeArg->getZExtValue()) {
777 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
778 1, B, TD);
779 return ReplaceInstUsesWith(*CI, CI->getOperand(1));
780 }
781 return 0;
782 }
783
784 // Should be similar to memcpy.
785 if (Name == "__mempcpy_chk") {
786 return 0;
787 }
788
789 if (Name == "__memmove_chk") {
790 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
791 if (!SizeCI)
792 return 0;
793 ConstantInt *SizeArg = dyn_cast<ConstantInt>(CI->getOperand(3));
794 if (!SizeArg)
795 return 0;
796 if (SizeCI->isAllOnesValue() ||
797 SizeCI->getZExtValue() <= SizeArg->getZExtValue()) {
798 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
799 1, B, TD);
800 return ReplaceInstUsesWith(*CI, CI->getOperand(1));
801 }
802 return 0;
803 }
804
805 if (Name == "__memset_chk") {
806 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
807 if (!SizeCI)
808 return 0;
809 ConstantInt *SizeArg = dyn_cast<ConstantInt>(CI->getOperand(3));
810 if (!SizeArg)
811 return 0;
812 if (SizeCI->isAllOnesValue() ||
813 SizeCI->getZExtValue() <= SizeArg->getZExtValue()) {
814 Value *Val = B.CreateIntCast(CI->getOperand(2), B.getInt8Ty(),
815 false);
816 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B, TD);
817 return ReplaceInstUsesWith(*CI, CI->getOperand(1));
818 }
819 return 0;
820 }
821
822 if (Name == "__strcpy_chk") {
823 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(3));
824 if (!SizeCI)
825 return 0;
826 // If a) we don't have any length information, or b) we know this will
827 // fit then just lower to a plain strcpy. Otherwise we'll keep our
828 // strcpy_chk call which may fail at runtime if the size is too long.
829 // TODO: It might be nice to get a maximum length out of the possible
830 // string lengths for varying.
831 if (SizeCI->isAllOnesValue() ||
832 SizeCI->getZExtValue() >= GetStringLength(CI->getOperand(2))) {
833 Value *Ret = EmitStrCpy(CI->getOperand(1), CI->getOperand(2), B, TD);
834 return ReplaceInstUsesWith(*CI, Ret);
835 }
836 return 0;
837 }
838
839 // Should be similar to strcpy.
840 if (Name == "__stpcpy_chk") {
841 return 0;
842 }
843
844 if (Name == "__strncpy_chk") {
845 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
846 if (!SizeCI)
847 return 0;
848 ConstantInt *SizeArg = dyn_cast<ConstantInt>(CI->getOperand(3));
849 if (!SizeArg)
850 return 0;
851 if (SizeCI->isAllOnesValue() ||
852 SizeCI->getZExtValue() <= SizeArg->getZExtValue()) {
Eric Christopherbd973762010-03-11 01:25:07 +0000853 Value *Ret = EmitStrNCpy(CI->getOperand(1), CI->getOperand(2),
854 CI->getOperand(3), B, TD);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000855 return ReplaceInstUsesWith(*CI, Ret);
856 }
857 return 0;
858 }
859
860 if (Name == "__strcat_chk") {
861 return 0;
862 }
863
864 if (Name == "__strncat_chk") {
865 return 0;
866 }
867
868 return 0;
869}
870
Chris Lattner753a2b42010-01-05 07:32:13 +0000871// visitCallSite - Improvements for call and invoke instructions.
872//
873Instruction *InstCombiner::visitCallSite(CallSite CS) {
874 bool Changed = false;
875
876 // If the callee is a constexpr cast of a function, attempt to move the cast
877 // to the arguments of the call/invoke.
878 if (transformConstExprCastCall(CS)) return 0;
879
880 Value *Callee = CS.getCalledValue();
881
882 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000883 // If the call and callee calling conventions don't match, this call must
884 // be unreachable, as the call is undefined.
885 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
886 // Only do this for calls to a function with a body. A prototype may
887 // not actually end up matching the implementation's calling conv for a
888 // variety of reasons (e.g. it may be written in assembly).
889 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000890 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000891 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000892 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000893 OldCall);
894 // If OldCall dues not return void then replaceAllUsesWith undef.
895 // This allows ValueHandlers and custom metadata to adjust itself.
896 if (!OldCall->getType()->isVoidTy())
897 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000898 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000899 return EraseInstFromFunction(*OldCall);
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000900
Chris Lattner830f3f22010-02-01 18:04:58 +0000901 // We cannot remove an invoke, because it would change the CFG, just
902 // change the callee to a null pointer.
903 cast<InvokeInst>(OldCall)->setOperand(0,
904 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000905 return 0;
906 }
907
908 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
909 // This instruction is not reachable, just remove it. We insert a store to
910 // undef so that we know that this code is not reachable, despite the fact
911 // that we can't modify the CFG here.
912 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
913 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
914 CS.getInstruction());
915
916 // If CS dues not return void then replaceAllUsesWith undef.
917 // This allows ValueHandlers and custom metadata to adjust itself.
918 if (!CS.getInstruction()->getType()->isVoidTy())
919 CS.getInstruction()->
920 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
921
922 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
923 // Don't break the CFG, insert a dummy cond branch.
924 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
925 ConstantInt::getTrue(Callee->getContext()), II);
926 }
927 return EraseInstFromFunction(*CS.getInstruction());
928 }
929
930 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
931 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
932 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
933 return transformCallThroughTrampoline(CS);
934
935 const PointerType *PTy = cast<PointerType>(Callee->getType());
936 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
937 if (FTy->isVarArg()) {
938 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
939 // See if we can optimize any arguments passed through the varargs area of
940 // the call.
941 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
942 E = CS.arg_end(); I != E; ++I, ++ix) {
943 CastInst *CI = dyn_cast<CastInst>(*I);
944 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
945 *I = CI->getOperand(0);
946 Changed = true;
947 }
948 }
949 }
950
951 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
952 // Inline asm calls cannot throw - mark them 'nounwind'.
953 CS.setDoesNotThrow();
954 Changed = true;
955 }
956
Eric Christopher27ceaa12010-03-06 10:50:38 +0000957 // Try to optimize the call if possible, we require TargetData for most of
958 // this. None of these calls are seen as possibly dead so go ahead and
959 // delete the instruction now.
960 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
961 Instruction *I = tryOptimizeCall(CI, TD);
Eric Christopher7b323a32010-03-06 10:59:25 +0000962 // If we changed something return the result, etc. Otherwise let
963 // the fallthrough check.
964 if (I) return EraseInstFromFunction(*I);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000965 }
966
Chris Lattner753a2b42010-01-05 07:32:13 +0000967 return Changed ? CS.getInstruction() : 0;
968}
969
970// transformConstExprCastCall - If the callee is a constexpr cast of a function,
971// attempt to move the cast to the arguments of the call/invoke.
972//
973bool InstCombiner::transformConstExprCastCall(CallSite CS) {
974 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
975 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Eric Christopher0c6a8f92010-02-03 00:21:58 +0000976 if (CE->getOpcode() != Instruction::BitCast ||
Chris Lattner753a2b42010-01-05 07:32:13 +0000977 !isa<Function>(CE->getOperand(0)))
978 return false;
979 Function *Callee = cast<Function>(CE->getOperand(0));
980 Instruction *Caller = CS.getInstruction();
981 const AttrListPtr &CallerPAL = CS.getAttributes();
982
983 // Okay, this is a cast from a function to a different type. Unless doing so
984 // would cause a type conversion of one of our arguments, change this call to
985 // be a direct call with arguments casted to the appropriate types.
986 //
987 const FunctionType *FT = Callee->getFunctionType();
988 const Type *OldRetTy = Caller->getType();
989 const Type *NewRetTy = FT->getReturnType();
990
Duncan Sands1df98592010-02-16 11:11:14 +0000991 if (NewRetTy->isStructTy())
Chris Lattner753a2b42010-01-05 07:32:13 +0000992 return false; // TODO: Handle multiple return values.
993
994 // Check to see if we are changing the return type...
995 if (OldRetTy != NewRetTy) {
996 if (Callee->isDeclaration() &&
997 // Conversion is ok if changing from one pointer type to another or from
998 // a pointer to an integer of the same size.
Duncan Sands1df98592010-02-16 11:11:14 +0000999 !((OldRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001000 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001001 (NewRetTy->isPointerTy() || !TD ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001002 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
1003 return false; // Cannot transform this return value.
1004
1005 if (!Caller->use_empty() &&
1006 // void -> non-void is handled specially
1007 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
1008 return false; // Cannot transform this return value.
1009
1010 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
1011 Attributes RAttrs = CallerPAL.getRetAttributes();
1012 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
1013 return false; // Attribute not compatible with transformed value.
1014 }
1015
1016 // If the callsite is an invoke instruction, and the return value is used by
1017 // a PHI node in a successor, we cannot change the return type of the call
1018 // because there is no place to put the cast instruction (without breaking
1019 // the critical edge). Bail out in this case.
1020 if (!Caller->use_empty())
1021 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1022 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
1023 UI != E; ++UI)
1024 if (PHINode *PN = dyn_cast<PHINode>(*UI))
1025 if (PN->getParent() == II->getNormalDest() ||
1026 PN->getParent() == II->getUnwindDest())
1027 return false;
1028 }
1029
1030 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1031 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1032
1033 CallSite::arg_iterator AI = CS.arg_begin();
1034 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1035 const Type *ParamTy = FT->getParamType(i);
1036 const Type *ActTy = (*AI)->getType();
1037
1038 if (!CastInst::isCastable(ActTy, ParamTy))
1039 return false; // Cannot transform this parameter value.
1040
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001041 if (CallerPAL.getParamAttributes(i + 1)
Chris Lattner753a2b42010-01-05 07:32:13 +00001042 & Attribute::typeIncompatible(ParamTy))
1043 return false; // Attribute not compatible with transformed value.
1044
1045 // Converting from one pointer type to another or between a pointer and an
1046 // integer of the same size is safe even if we do not have a body.
1047 bool isConvertible = ActTy == ParamTy ||
Duncan Sands1df98592010-02-16 11:11:14 +00001048 (TD && ((ParamTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001049 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001050 (ActTy->isPointerTy() ||
Chris Lattner753a2b42010-01-05 07:32:13 +00001051 ActTy == TD->getIntPtrType(Caller->getContext()))));
1052 if (Callee->isDeclaration() && !isConvertible) return false;
1053 }
1054
1055 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1056 Callee->isDeclaration())
1057 return false; // Do not delete arguments unless we have a function body.
1058
1059 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1060 !CallerPAL.isEmpty())
1061 // In this case we have more arguments than the new function type, but we
1062 // won't be dropping them. Check that these extra arguments have attributes
1063 // that are compatible with being a vararg call argument.
1064 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1065 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1066 break;
1067 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
1068 if (PAttrs & Attribute::VarArgsIncompatible)
1069 return false;
1070 }
1071
1072 // Okay, we decided that this is a safe thing to do: go ahead and start
1073 // inserting cast instructions as necessary...
1074 std::vector<Value*> Args;
1075 Args.reserve(NumActualArgs);
1076 SmallVector<AttributeWithIndex, 8> attrVec;
1077 attrVec.reserve(NumCommonArgs);
1078
1079 // Get any return attributes.
1080 Attributes RAttrs = CallerPAL.getRetAttributes();
1081
1082 // If the return value is not being used, the type may not be compatible
1083 // with the existing attributes. Wipe out any problematic attributes.
1084 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
1085
1086 // Add the new return attributes.
1087 if (RAttrs)
1088 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
1089
1090 AI = CS.arg_begin();
1091 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1092 const Type *ParamTy = FT->getParamType(i);
1093 if ((*AI)->getType() == ParamTy) {
1094 Args.push_back(*AI);
1095 } else {
1096 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1097 false, ParamTy, false);
1098 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
1099 }
1100
1101 // Add any parameter attributes.
1102 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1103 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1104 }
1105
1106 // If the function takes more arguments than the call was taking, add them
1107 // now.
1108 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1109 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1110
1111 // If we are removing arguments to the function, emit an obnoxious warning.
1112 if (FT->getNumParams() < NumActualArgs) {
1113 if (!FT->isVarArg()) {
1114 errs() << "WARNING: While resolving call to function '"
1115 << Callee->getName() << "' arguments were dropped!\n";
1116 } else {
1117 // Add all of the arguments in their promoted form to the arg list.
1118 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1119 const Type *PTy = getPromotedType((*AI)->getType());
1120 if (PTy != (*AI)->getType()) {
1121 // Must promote to pass through va_arg area!
1122 Instruction::CastOps opcode =
1123 CastInst::getCastOpcode(*AI, false, PTy, false);
1124 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
1125 } else {
1126 Args.push_back(*AI);
1127 }
1128
1129 // Add any parameter attributes.
1130 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
1131 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1132 }
1133 }
1134 }
1135
1136 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
1137 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
1138
1139 if (NewRetTy->isVoidTy())
1140 Caller->setName(""); // Void type should not have a name.
1141
1142 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
1143 attrVec.end());
1144
1145 Instruction *NC;
1146 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1147 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
1148 Args.begin(), Args.end(),
1149 Caller->getName(), Caller);
1150 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1151 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1152 } else {
1153 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
1154 Caller->getName(), Caller);
1155 CallInst *CI = cast<CallInst>(Caller);
1156 if (CI->isTailCall())
1157 cast<CallInst>(NC)->setTailCall();
1158 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1159 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1160 }
1161
1162 // Insert a cast of the return type as necessary.
1163 Value *NV = NC;
1164 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1165 if (!NV->getType()->isVoidTy()) {
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001166 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Chris Lattner753a2b42010-01-05 07:32:13 +00001167 OldRetTy, false);
1168 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
1169
1170 // If this is an invoke instruction, we should insert it after the first
1171 // non-phi, instruction in the normal successor block.
1172 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1173 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
1174 InsertNewInstBefore(NC, *I);
1175 } else {
1176 // Otherwise, it's a call, just insert cast right after the call instr
1177 InsertNewInstBefore(NC, *Caller);
1178 }
1179 Worklist.AddUsersToWorkList(*Caller);
1180 } else {
1181 NV = UndefValue::get(Caller->getType());
1182 }
1183 }
1184
1185
1186 if (!Caller->use_empty())
1187 Caller->replaceAllUsesWith(NV);
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001188
Chris Lattner753a2b42010-01-05 07:32:13 +00001189 EraseInstFromFunction(*Caller);
1190 return true;
1191}
1192
1193// transformCallThroughTrampoline - Turn a call to a function created by the
1194// init_trampoline intrinsic into a direct call to the underlying function.
1195//
1196Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
1197 Value *Callee = CS.getCalledValue();
1198 const PointerType *PTy = cast<PointerType>(Callee->getType());
1199 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1200 const AttrListPtr &Attrs = CS.getAttributes();
1201
1202 // If the call already has the 'nest' attribute somewhere then give up -
1203 // otherwise 'nest' would occur twice after splicing in the chain.
1204 if (Attrs.hasAttrSomewhere(Attribute::Nest))
1205 return 0;
1206
1207 IntrinsicInst *Tramp =
1208 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
1209
1210 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
1211 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1212 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
1213
1214 const AttrListPtr &NestAttrs = NestF->getAttributes();
1215 if (!NestAttrs.isEmpty()) {
1216 unsigned NestIdx = 1;
1217 const Type *NestTy = 0;
1218 Attributes NestAttr = Attribute::None;
1219
1220 // Look for a parameter marked with the 'nest' attribute.
1221 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1222 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
1223 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
1224 // Record the parameter type and any other attributes.
1225 NestTy = *I;
1226 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1227 break;
1228 }
1229
1230 if (NestTy) {
1231 Instruction *Caller = CS.getInstruction();
1232 std::vector<Value*> NewArgs;
1233 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1234
1235 SmallVector<AttributeWithIndex, 8> NewAttrs;
1236 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1237
1238 // Insert the nest argument into the call argument list, which may
1239 // mean appending it. Likewise for attributes.
1240
1241 // Add any result attributes.
1242 if (Attributes Attr = Attrs.getRetAttributes())
1243 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
1244
1245 {
1246 unsigned Idx = 1;
1247 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1248 do {
1249 if (Idx == NestIdx) {
1250 // Add the chain argument and attributes.
1251 Value *NestVal = Tramp->getOperand(3);
1252 if (NestVal->getType() != NestTy)
1253 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
1254 NewArgs.push_back(NestVal);
1255 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1256 }
1257
1258 if (I == E)
1259 break;
1260
1261 // Add the original argument and attributes.
1262 NewArgs.push_back(*I);
1263 if (Attributes Attr = Attrs.getParamAttributes(Idx))
1264 NewAttrs.push_back
1265 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1266
1267 ++Idx, ++I;
1268 } while (1);
1269 }
1270
1271 // Add any function attributes.
1272 if (Attributes Attr = Attrs.getFnAttributes())
1273 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
1274
1275 // The trampoline may have been bitcast to a bogus type (FTy).
1276 // Handle this by synthesizing a new function type, equal to FTy
1277 // with the chain parameter inserted.
1278
1279 std::vector<const Type*> NewTypes;
1280 NewTypes.reserve(FTy->getNumParams()+1);
1281
1282 // Insert the chain's type into the list of parameter types, which may
1283 // mean appending it.
1284 {
1285 unsigned Idx = 1;
1286 FunctionType::param_iterator I = FTy->param_begin(),
1287 E = FTy->param_end();
1288
1289 do {
1290 if (Idx == NestIdx)
1291 // Add the chain's type.
1292 NewTypes.push_back(NestTy);
1293
1294 if (I == E)
1295 break;
1296
1297 // Add the original type.
1298 NewTypes.push_back(*I);
1299
1300 ++Idx, ++I;
1301 } while (1);
1302 }
1303
1304 // Replace the trampoline call with a direct call. Let the generic
1305 // code sort out any function type mismatches.
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001306 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001307 FTy->isVarArg());
1308 Constant *NewCallee =
1309 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001310 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001311 PointerType::getUnqual(NewFTy));
1312 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
1313 NewAttrs.end());
1314
1315 Instruction *NewCaller;
1316 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1317 NewCaller = InvokeInst::Create(NewCallee,
1318 II->getNormalDest(), II->getUnwindDest(),
1319 NewArgs.begin(), NewArgs.end(),
1320 Caller->getName(), Caller);
1321 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1322 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1323 } else {
1324 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
1325 Caller->getName(), Caller);
1326 if (cast<CallInst>(Caller)->isTailCall())
1327 cast<CallInst>(NewCaller)->setTailCall();
1328 cast<CallInst>(NewCaller)->
1329 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1330 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1331 }
1332 if (!Caller->getType()->isVoidTy())
1333 Caller->replaceAllUsesWith(NewCaller);
1334 Caller->eraseFromParent();
1335 Worklist.Remove(Caller);
1336 return 0;
1337 }
1338 }
1339
1340 // Replace the trampoline call with a direct call. Since there is no 'nest'
1341 // parameter, there is no need to adjust the argument list. Let the generic
1342 // code sort out any function type mismatches.
1343 Constant *NewCallee =
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001344 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001345 ConstantExpr::getBitCast(NestF, PTy);
1346 CS.setCalledFunction(NewCallee);
1347 return CS.getInstruction();
1348}
Eric Christopher0c6a8f92010-02-03 00:21:58 +00001349