blob: 2d8904d77e55a3dd8eb6b6cfcfdc58a7958b7cf9 [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"
Meador Inge63f932c2012-11-30 04:05:06 +000015#include "llvm/ADT/Statistic.h"
Chris Lattner753a2b42010-01-05 07:32:13 +000016#include "llvm/Analysis/MemoryBuiltins.h"
Chandler Carruthd04a8d42012-12-03 16:50:05 +000017#include "llvm/DataLayout.h"
18#include "llvm/Support/CallSite.h"
Eric Christopher27ceaa12010-03-06 10:50:38 +000019#include "llvm/Transforms/Utils/BuildLibCalls.h"
Chris Lattner687140c2010-12-25 20:37:57 +000020#include "llvm/Transforms/Utils/Local.h"
Chris Lattner753a2b42010-01-05 07:32:13 +000021using namespace llvm;
22
Meador Inge63f932c2012-11-30 04:05:06 +000023STATISTIC(NumSimplified, "Number of library calls simplified");
24
Chris Lattner753a2b42010-01-05 07:32:13 +000025/// getPromotedType - Return the specified type promoted as it would be to pass
26/// though a va_arg area.
Chris Lattnerdb125cf2011-07-18 04:54:35 +000027static Type *getPromotedType(Type *Ty) {
28 if (IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
Chris Lattner753a2b42010-01-05 07:32:13 +000029 if (ITy->getBitWidth() < 32)
30 return Type::getInt32Ty(Ty->getContext());
31 }
32 return Ty;
33}
34
Dan Gohmance52bc52012-09-13 18:19:06 +000035/// reduceToSingleValueType - Given an aggregate type which ultimately holds a
36/// single scalar element, like {{{type}}} or [1 x type], return type.
37static Type *reduceToSingleValueType(Type *T) {
38 while (!T->isSingleValueType()) {
39 if (StructType *STy = dyn_cast<StructType>(T)) {
40 if (STy->getNumElements() == 1)
41 T = STy->getElementType(0);
42 else
43 break;
44 } else if (ArrayType *ATy = dyn_cast<ArrayType>(T)) {
45 if (ATy->getNumElements() == 1)
46 T = ATy->getElementType();
47 else
48 break;
49 } else
50 break;
51 }
52
53 return T;
54}
Chris Lattner753a2b42010-01-05 07:32:13 +000055
56Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Chris Lattner687140c2010-12-25 20:37:57 +000057 unsigned DstAlign = getKnownAlignment(MI->getArgOperand(0), TD);
58 unsigned SrcAlign = getKnownAlignment(MI->getArgOperand(1), TD);
Chris Lattner753a2b42010-01-05 07:32:13 +000059 unsigned MinAlign = std::min(DstAlign, SrcAlign);
60 unsigned CopyAlign = MI->getAlignment();
61
62 if (CopyAlign < MinAlign) {
Jim Grosbach00e403a2012-02-03 00:07:04 +000063 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Chris Lattner753a2b42010-01-05 07:32:13 +000064 MinAlign, false));
65 return MI;
66 }
Jim Grosbach00e403a2012-02-03 00:07:04 +000067
Chris Lattner753a2b42010-01-05 07:32:13 +000068 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
69 // load/store.
Gabor Greifbcda85c2010-06-24 13:54:33 +000070 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getArgOperand(2));
Chris Lattner753a2b42010-01-05 07:32:13 +000071 if (MemOpLength == 0) return 0;
Jim Grosbach00e403a2012-02-03 00:07:04 +000072
Chris Lattner753a2b42010-01-05 07:32:13 +000073 // Source and destination pointer types are always "i8*" for intrinsic. See
74 // if the size is something we can handle with a single primitive load/store.
75 // A single load+store correctly handles overlapping memory in the memmove
76 // case.
Michael Liao9441ad02012-08-15 03:49:59 +000077 uint64_t Size = MemOpLength->getLimitedValue();
78 assert(Size && "0-sized memory transfering should be removed already.");
Jim Grosbach00e403a2012-02-03 00:07:04 +000079
Chris Lattner753a2b42010-01-05 07:32:13 +000080 if (Size > 8 || (Size&(Size-1)))
81 return 0; // If not 1/2/4/8 bytes, exit.
Jim Grosbach00e403a2012-02-03 00:07:04 +000082
Chris Lattner753a2b42010-01-05 07:32:13 +000083 // Use an integer load+store unless we can find something better.
Mon P Wang20adc9d2010-04-04 03:10:48 +000084 unsigned SrcAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +000085 cast<PointerType>(MI->getArgOperand(1)->getType())->getAddressSpace();
Gabor Greif4ec22582010-04-16 15:33:14 +000086 unsigned DstAddrSp =
Gabor Greifbcda85c2010-06-24 13:54:33 +000087 cast<PointerType>(MI->getArgOperand(0)->getType())->getAddressSpace();
Mon P Wang20adc9d2010-04-04 03:10:48 +000088
Chris Lattnerdb125cf2011-07-18 04:54:35 +000089 IntegerType* IntType = IntegerType::get(MI->getContext(), Size<<3);
Mon P Wang20adc9d2010-04-04 03:10:48 +000090 Type *NewSrcPtrTy = PointerType::get(IntType, SrcAddrSp);
91 Type *NewDstPtrTy = PointerType::get(IntType, DstAddrSp);
Jim Grosbach00e403a2012-02-03 00:07:04 +000092
Chris Lattner753a2b42010-01-05 07:32:13 +000093 // Memcpy forces the use of i8* for the source and destination. That means
94 // that if you're using memcpy to move one double around, you'll get a cast
95 // from double* to i8*. We'd much rather use a double load+store rather than
96 // an i64 load+store, here because this improves the odds that the source or
97 // dest address will be promotable. See if we can find a better type than the
98 // integer datatype.
Gabor Greifcea7ac72010-06-24 12:58:35 +000099 Value *StrippedDest = MI->getArgOperand(0)->stripPointerCasts();
Dan Gohmanb9989132012-09-13 21:51:01 +0000100 MDNode *CopyMD = 0;
Gabor Greifcea7ac72010-06-24 12:58:35 +0000101 if (StrippedDest != MI->getArgOperand(0)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000102 Type *SrcETy = cast<PointerType>(StrippedDest->getType())
Chris Lattner753a2b42010-01-05 07:32:13 +0000103 ->getElementType();
104 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
105 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
106 // down through these levels if so.
Dan Gohmance52bc52012-09-13 18:19:06 +0000107 SrcETy = reduceToSingleValueType(SrcETy);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000108
Mon P Wang20adc9d2010-04-04 03:10:48 +0000109 if (SrcETy->isSingleValueType()) {
110 NewSrcPtrTy = PointerType::get(SrcETy, SrcAddrSp);
111 NewDstPtrTy = PointerType::get(SrcETy, DstAddrSp);
Dan Gohmanb9989132012-09-13 21:51:01 +0000112
113 // If the memcpy has metadata describing the members, see if we can
114 // get the TBAA tag describing our copy.
115 if (MDNode *M = MI->getMetadata(LLVMContext::MD_tbaa_struct)) {
116 if (M->getNumOperands() == 3 &&
Nick Lewycky5e01f802012-10-11 02:05:23 +0000117 M->getOperand(0) &&
Dan Gohmanb9989132012-09-13 21:51:01 +0000118 isa<ConstantInt>(M->getOperand(0)) &&
119 cast<ConstantInt>(M->getOperand(0))->isNullValue() &&
Nick Lewycky5e01f802012-10-11 02:05:23 +0000120 M->getOperand(1) &&
Dan Gohmanb9989132012-09-13 21:51:01 +0000121 isa<ConstantInt>(M->getOperand(1)) &&
122 cast<ConstantInt>(M->getOperand(1))->getValue() == Size &&
Nick Lewycky5e01f802012-10-11 02:05:23 +0000123 M->getOperand(2) &&
Dan Gohmanb9989132012-09-13 21:51:01 +0000124 isa<MDNode>(M->getOperand(2)))
125 CopyMD = cast<MDNode>(M->getOperand(2));
126 }
Mon P Wang20adc9d2010-04-04 03:10:48 +0000127 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000128 }
129 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000130
Chris Lattner753a2b42010-01-05 07:32:13 +0000131 // If the memcpy/memmove provides better alignment info than we can
132 // infer, use it.
133 SrcAlign = std::max(SrcAlign, CopyAlign);
134 DstAlign = std::max(DstAlign, CopyAlign);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000135
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000136 Value *Src = Builder->CreateBitCast(MI->getArgOperand(1), NewSrcPtrTy);
137 Value *Dest = Builder->CreateBitCast(MI->getArgOperand(0), NewDstPtrTy);
Eli Friedman59f15912011-05-18 19:57:14 +0000138 LoadInst *L = Builder->CreateLoad(Src, MI->isVolatile());
139 L->setAlignment(SrcAlign);
Dan Gohmanb9989132012-09-13 21:51:01 +0000140 if (CopyMD)
141 L->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Eli Friedman59f15912011-05-18 19:57:14 +0000142 StoreInst *S = Builder->CreateStore(L, Dest, MI->isVolatile());
143 S->setAlignment(DstAlign);
Dan Gohmanb9989132012-09-13 21:51:01 +0000144 if (CopyMD)
145 S->setMetadata(LLVMContext::MD_tbaa, CopyMD);
Chris Lattner753a2b42010-01-05 07:32:13 +0000146
147 // Set the size of the copy to 0, it will be deleted on the next iteration.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000148 MI->setArgOperand(2, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000149 return MI;
150}
151
152Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
Chris Lattnerae47be12010-12-25 20:52:04 +0000153 unsigned Alignment = getKnownAlignment(MI->getDest(), TD);
Chris Lattner753a2b42010-01-05 07:32:13 +0000154 if (MI->getAlignment() < Alignment) {
155 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
156 Alignment, false));
157 return MI;
158 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000159
Chris Lattner753a2b42010-01-05 07:32:13 +0000160 // Extract the length and alignment and fill if they are constant.
161 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
162 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Duncan Sandsb0bc6c32010-02-15 16:12:20 +0000163 if (!LenC || !FillC || !FillC->getType()->isIntegerTy(8))
Chris Lattner753a2b42010-01-05 07:32:13 +0000164 return 0;
Michael Liao9441ad02012-08-15 03:49:59 +0000165 uint64_t Len = LenC->getLimitedValue();
Chris Lattner753a2b42010-01-05 07:32:13 +0000166 Alignment = MI->getAlignment();
Michael Liao9441ad02012-08-15 03:49:59 +0000167 assert(Len && "0-sized memory setting should be removed already.");
Jim Grosbach00e403a2012-02-03 00:07:04 +0000168
Chris Lattner753a2b42010-01-05 07:32:13 +0000169 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
170 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000171 Type *ITy = IntegerType::get(MI->getContext(), Len*8); // n=1 -> i8.
Jim Grosbach00e403a2012-02-03 00:07:04 +0000172
Chris Lattner753a2b42010-01-05 07:32:13 +0000173 Value *Dest = MI->getDest();
Mon P Wang55fb9b02010-12-20 01:05:30 +0000174 unsigned DstAddrSp = cast<PointerType>(Dest->getType())->getAddressSpace();
175 Type *NewDstPtrTy = PointerType::get(ITy, DstAddrSp);
176 Dest = Builder->CreateBitCast(Dest, NewDstPtrTy);
Chris Lattner753a2b42010-01-05 07:32:13 +0000177
178 // Alignment 0 is identity for alignment 1 for memset, but not store.
179 if (Alignment == 0) Alignment = 1;
Jim Grosbach00e403a2012-02-03 00:07:04 +0000180
Chris Lattner753a2b42010-01-05 07:32:13 +0000181 // Extract the fill value and store.
182 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Eli Friedman59f15912011-05-18 19:57:14 +0000183 StoreInst *S = Builder->CreateStore(ConstantInt::get(ITy, Fill), Dest,
184 MI->isVolatile());
185 S->setAlignment(Alignment);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000186
Chris Lattner753a2b42010-01-05 07:32:13 +0000187 // Set the size of the copy to 0, it will be deleted on the next iteration.
188 MI->setLength(Constant::getNullValue(LenC->getType()));
189 return MI;
190 }
191
192 return 0;
193}
194
Jim Grosbach00e403a2012-02-03 00:07:04 +0000195/// visitCallInst - CallInst simplification. This mostly only handles folding
Chris Lattner753a2b42010-01-05 07:32:13 +0000196/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
197/// the heavy lifting.
198///
199Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000200 if (isFreeCall(&CI, TLI))
Chris Lattner753a2b42010-01-05 07:32:13 +0000201 return visitFree(CI);
202
203 // If the caller function is nounwind, mark the call as nounwind, even if the
204 // callee isn't.
205 if (CI.getParent()->getParent()->doesNotThrow() &&
206 !CI.doesNotThrow()) {
207 CI.setDoesNotThrow();
208 return &CI;
209 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000210
Chris Lattner753a2b42010-01-05 07:32:13 +0000211 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
212 if (!II) return visitCallSite(&CI);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000213
Chris Lattner753a2b42010-01-05 07:32:13 +0000214 // Intrinsics cannot occur in an invoke, so handle them here instead of in
215 // visitCallSite.
216 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
217 bool Changed = false;
218
219 // memmove/cpy/set of zero bytes is a noop.
220 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
Chris Lattner6eff7512010-10-01 05:51:02 +0000221 if (NumBytes->isNullValue())
222 return EraseInstFromFunction(CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000223
224 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
225 if (CI->getZExtValue() == 1) {
226 // Replace the instruction with just byte operations. We would
227 // transform other cases to loads/stores, but we don't know if
228 // alignment is sufficient.
229 }
230 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000231
Chris Lattner6eff7512010-10-01 05:51:02 +0000232 // No other transformations apply to volatile transfers.
233 if (MI->isVolatile())
234 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000235
236 // If we have a memmove and the source operation is a constant global,
237 // then the source and dest pointers can't alias, so we can change this
238 // into a call to memcpy.
239 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
240 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
241 if (GVSrc->isConstant()) {
Eric Christopher551754c2010-04-16 23:37:20 +0000242 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner753a2b42010-01-05 07:32:13 +0000243 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
Jay Foad5fdd6c82011-07-12 14:06:48 +0000244 Type *Tys[3] = { CI.getArgOperand(0)->getType(),
245 CI.getArgOperand(1)->getType(),
246 CI.getArgOperand(2)->getType() };
Benjamin Kramereb9a85f2011-07-14 17:45:39 +0000247 CI.setCalledFunction(Intrinsic::getDeclaration(M, MemCpyID, Tys));
Chris Lattner753a2b42010-01-05 07:32:13 +0000248 Changed = true;
249 }
250 }
251
252 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
253 // memmove(x,x,size) -> noop.
254 if (MTI->getSource() == MTI->getDest())
255 return EraseInstFromFunction(CI);
Eric Christopher551754c2010-04-16 23:37:20 +0000256 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000257
Eric Christopher551754c2010-04-16 23:37:20 +0000258 // If we can determine a pointer alignment that is bigger than currently
259 // set, update the alignment.
260 if (isa<MemTransferInst>(MI)) {
261 if (Instruction *I = SimplifyMemTransfer(MI))
Chris Lattner753a2b42010-01-05 07:32:13 +0000262 return I;
263 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
264 if (Instruction *I = SimplifyMemSet(MSI))
265 return I;
266 }
Gabor Greifc310fcc2010-06-24 13:42:49 +0000267
Chris Lattner753a2b42010-01-05 07:32:13 +0000268 if (Changed) return II;
269 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000270
Chris Lattner753a2b42010-01-05 07:32:13 +0000271 switch (II->getIntrinsicID()) {
272 default: break;
Eric Christopher415326b2010-02-09 21:24:27 +0000273 case Intrinsic::objectsize: {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000274 uint64_t Size;
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000275 if (getObjectSize(II->getArgOperand(0), Size, TD, TLI))
Nuno Lopes9e72a792012-06-21 15:45:28 +0000276 return ReplaceInstUsesWith(CI, ConstantInt::get(CI.getType(), Size));
277 return 0;
Eric Christopher415326b2010-02-09 21:24:27 +0000278 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000279 case Intrinsic::bswap:
280 // bswap(bswap(x)) -> x
Gabor Greifcea7ac72010-06-24 12:58:35 +0000281 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getArgOperand(0)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000282 if (Operand->getIntrinsicID() == Intrinsic::bswap)
Gabor Greifcea7ac72010-06-24 12:58:35 +0000283 return ReplaceInstUsesWith(CI, Operand->getArgOperand(0));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000284
Chris Lattner753a2b42010-01-05 07:32:13 +0000285 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
Gabor Greifcea7ac72010-06-24 12:58:35 +0000286 if (TruncInst *TI = dyn_cast<TruncInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000287 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
288 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
289 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
290 TI->getType()->getPrimitiveSizeInBits();
291 Value *CV = ConstantInt::get(Operand->getType(), C);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000292 Value *V = Builder->CreateLShr(Operand->getArgOperand(0), CV);
Chris Lattner753a2b42010-01-05 07:32:13 +0000293 return new TruncInst(V, TI->getType());
294 }
295 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000296
Chris Lattner753a2b42010-01-05 07:32:13 +0000297 break;
298 case Intrinsic::powi:
Gabor Greifcea7ac72010-06-24 12:58:35 +0000299 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000300 // powi(x, 0) -> 1.0
301 if (Power->isZero())
302 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
303 // powi(x, 1) -> x
304 if (Power->isOne())
Gabor Greifcea7ac72010-06-24 12:58:35 +0000305 return ReplaceInstUsesWith(CI, II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000306 // powi(x, -1) -> 1/x
307 if (Power->isAllOnesValue())
308 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
Gabor Greifcea7ac72010-06-24 12:58:35 +0000309 II->getArgOperand(0));
Chris Lattner753a2b42010-01-05 07:32:13 +0000310 }
311 break;
312 case Intrinsic::cttz: {
313 // If all bits below the first known one are known zero,
314 // this value is constant.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000315 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Andersonf1ac4652011-07-01 21:52:38 +0000316 // FIXME: Try to simplify vectors of integers.
317 if (!IT) break;
Chris Lattner753a2b42010-01-05 07:32:13 +0000318 uint32_t BitWidth = IT->getBitWidth();
319 APInt KnownZero(BitWidth, 0);
320 APInt KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000321 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000322 unsigned TrailingZeros = KnownOne.countTrailingZeros();
323 APInt Mask(APInt::getLowBitsSet(BitWidth, TrailingZeros));
324 if ((Mask & KnownZero) == Mask)
325 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
326 APInt(BitWidth, TrailingZeros)));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000327
Chris Lattner753a2b42010-01-05 07:32:13 +0000328 }
329 break;
330 case Intrinsic::ctlz: {
331 // If all bits above the first known one are known zero,
332 // this value is constant.
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000333 IntegerType *IT = dyn_cast<IntegerType>(II->getArgOperand(0)->getType());
Owen Andersonf1ac4652011-07-01 21:52:38 +0000334 // FIXME: Try to simplify vectors of integers.
335 if (!IT) break;
Chris Lattner753a2b42010-01-05 07:32:13 +0000336 uint32_t BitWidth = IT->getBitWidth();
337 APInt KnownZero(BitWidth, 0);
338 APInt KnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000339 ComputeMaskedBits(II->getArgOperand(0), KnownZero, KnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000340 unsigned LeadingZeros = KnownOne.countLeadingZeros();
341 APInt Mask(APInt::getHighBitsSet(BitWidth, LeadingZeros));
342 if ((Mask & KnownZero) == Mask)
343 return ReplaceInstUsesWith(CI, ConstantInt::get(IT,
344 APInt(BitWidth, LeadingZeros)));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000345
Chris Lattner753a2b42010-01-05 07:32:13 +0000346 }
347 break;
348 case Intrinsic::uadd_with_overflow: {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000349 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000350 IntegerType *IT = cast<IntegerType>(II->getArgOperand(0)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000351 uint32_t BitWidth = IT->getBitWidth();
Chris Lattner753a2b42010-01-05 07:32:13 +0000352 APInt LHSKnownZero(BitWidth, 0);
353 APInt LHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000354 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000355 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
356 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
357
358 if (LHSKnownNegative || LHSKnownPositive) {
359 APInt RHSKnownZero(BitWidth, 0);
360 APInt RHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000361 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Chris Lattner753a2b42010-01-05 07:32:13 +0000362 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
363 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
364 if (LHSKnownNegative && RHSKnownNegative) {
365 // The sign bit is set in both cases: this MUST overflow.
366 // Create a simple add instruction, and insert it into the struct.
Eli Friedman59f15912011-05-18 19:57:14 +0000367 Value *Add = Builder->CreateAdd(LHS, RHS);
368 Add->takeName(&CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000369 Constant *V[] = {
Eli Friedman59f15912011-05-18 19:57:14 +0000370 UndefValue::get(LHS->getType()),
371 ConstantInt::getTrue(II->getContext())
Chris Lattner753a2b42010-01-05 07:32:13 +0000372 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000373 StructType *ST = cast<StructType>(II->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +0000374 Constant *Struct = ConstantStruct::get(ST, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000375 return InsertValueInst::Create(Struct, Add, 0);
376 }
Eli Friedman59f15912011-05-18 19:57:14 +0000377
Chris Lattner753a2b42010-01-05 07:32:13 +0000378 if (LHSKnownPositive && RHSKnownPositive) {
379 // The sign bit is clear in both cases: this CANNOT overflow.
380 // Create a simple add instruction, and insert it into the struct.
Eli Friedman59f15912011-05-18 19:57:14 +0000381 Value *Add = Builder->CreateNUWAdd(LHS, RHS);
382 Add->takeName(&CI);
Chris Lattner753a2b42010-01-05 07:32:13 +0000383 Constant *V[] = {
384 UndefValue::get(LHS->getType()),
385 ConstantInt::getFalse(II->getContext())
386 };
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000387 StructType *ST = cast<StructType>(II->getType());
Chris Lattnerb065b062011-06-20 04:01:31 +0000388 Constant *Struct = ConstantStruct::get(ST, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000389 return InsertValueInst::Create(Struct, Add, 0);
390 }
391 }
392 }
393 // FALL THROUGH uadd into sadd
394 case Intrinsic::sadd_with_overflow:
395 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000396 if (isa<Constant>(II->getArgOperand(0)) &&
397 !isa<Constant>(II->getArgOperand(1))) {
398 Value *LHS = II->getArgOperand(0);
399 II->setArgOperand(0, II->getArgOperand(1));
400 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000401 return II;
402 }
403
404 // X + undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000405 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000406 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000407
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000408 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000409 // X + 0 -> {X, false}
410 if (RHS->isZero()) {
411 Constant *V[] = {
Eli Friedman4fffb342010-08-09 20:49:43 +0000412 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000413 ConstantInt::getFalse(II->getContext())
414 };
Chris Lattnerb065b062011-06-20 04:01:31 +0000415 Constant *Struct =
416 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000417 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000418 }
419 }
420 break;
421 case Intrinsic::usub_with_overflow:
422 case Intrinsic::ssub_with_overflow:
423 // undef - X -> undef
424 // X - undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000425 if (isa<UndefValue>(II->getArgOperand(0)) ||
426 isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000427 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000428
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000429 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000430 // X - 0 -> {X, false}
431 if (RHS->isZero()) {
432 Constant *V[] = {
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000433 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000434 ConstantInt::getFalse(II->getContext())
435 };
Jim Grosbach00e403a2012-02-03 00:07:04 +0000436 Constant *Struct =
Chris Lattnerb065b062011-06-20 04:01:31 +0000437 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000438 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000439 }
440 }
441 break;
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000442 case Intrinsic::umul_with_overflow: {
443 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
444 unsigned BitWidth = cast<IntegerType>(LHS->getType())->getBitWidth();
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000445
446 APInt LHSKnownZero(BitWidth, 0);
447 APInt LHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000448 ComputeMaskedBits(LHS, LHSKnownZero, LHSKnownOne);
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000449 APInt RHSKnownZero(BitWidth, 0);
450 APInt RHSKnownOne(BitWidth, 0);
Rafael Espindola26c8dcc2012-04-04 12:51:34 +0000451 ComputeMaskedBits(RHS, RHSKnownZero, RHSKnownOne);
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000452
Benjamin Kramerd655e6e2011-03-27 15:04:38 +0000453 // Get the largest possible values for each operand.
454 APInt LHSMax = ~LHSKnownZero;
455 APInt RHSMax = ~RHSKnownZero;
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000456
457 // If multiplying the maximum values does not overflow then we can turn
458 // this into a plain NUW mul.
Benjamin Kramerd655e6e2011-03-27 15:04:38 +0000459 bool Overflow;
460 LHSMax.umul_ov(RHSMax, Overflow);
461 if (!Overflow) {
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000462 Value *Mul = Builder->CreateNUWMul(LHS, RHS, "umul_with_overflow");
463 Constant *V[] = {
464 UndefValue::get(LHS->getType()),
465 Builder->getFalse()
466 };
Chris Lattnerb065b062011-06-20 04:01:31 +0000467 Constant *Struct = ConstantStruct::get(cast<StructType>(II->getType()),V);
Benjamin Kramer6b96fe72011-03-10 18:40:14 +0000468 return InsertValueInst::Create(Struct, Mul, 0);
469 }
470 } // FALL THROUGH
Chris Lattner753a2b42010-01-05 07:32:13 +0000471 case Intrinsic::smul_with_overflow:
472 // Canonicalize constants into the RHS.
Gabor Greifa90c5c72010-06-28 16:50:57 +0000473 if (isa<Constant>(II->getArgOperand(0)) &&
474 !isa<Constant>(II->getArgOperand(1))) {
475 Value *LHS = II->getArgOperand(0);
476 II->setArgOperand(0, II->getArgOperand(1));
477 II->setArgOperand(1, LHS);
Chris Lattner753a2b42010-01-05 07:32:13 +0000478 return II;
479 }
480
481 // X * undef -> undef
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000482 if (isa<UndefValue>(II->getArgOperand(1)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000483 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000484
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000485 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getArgOperand(1))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000486 // X*0 -> {0, false}
487 if (RHSI->isZero())
488 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000489
Chris Lattner753a2b42010-01-05 07:32:13 +0000490 // X * 1 -> {X, false}
491 if (RHSI->equalsInt(1)) {
492 Constant *V[] = {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000493 UndefValue::get(II->getArgOperand(0)->getType()),
Chris Lattner753a2b42010-01-05 07:32:13 +0000494 ConstantInt::getFalse(II->getContext())
495 };
Jim Grosbach00e403a2012-02-03 00:07:04 +0000496 Constant *Struct =
Chris Lattnerb065b062011-06-20 04:01:31 +0000497 ConstantStruct::get(cast<StructType>(II->getType()), V);
Gabor Greifcea7ac72010-06-24 12:58:35 +0000498 return InsertValueInst::Create(Struct, II->getArgOperand(0), 0);
Chris Lattner753a2b42010-01-05 07:32:13 +0000499 }
500 }
501 break;
502 case Intrinsic::ppc_altivec_lvx:
503 case Intrinsic::ppc_altivec_lvxl:
Bill Wendlingf93f7b22011-04-13 00:36:11 +0000504 // Turn PPC lvx -> load if the pointer is known aligned.
Chris Lattner687140c2010-12-25 20:37:57 +0000505 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000506 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0),
Chris Lattner753a2b42010-01-05 07:32:13 +0000507 PointerType::getUnqual(II->getType()));
508 return new LoadInst(Ptr);
509 }
510 break;
511 case Intrinsic::ppc_altivec_stvx:
512 case Intrinsic::ppc_altivec_stvxl:
513 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner687140c2010-12-25 20:37:57 +0000514 if (getOrEnforceKnownAlignment(II->getArgOperand(1), 16, TD) >= 16) {
Jim Grosbach00e403a2012-02-03 00:07:04 +0000515 Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000516 PointerType::getUnqual(II->getArgOperand(0)->getType());
517 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(1), OpPtrTy);
518 return new StoreInst(II->getArgOperand(0), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000519 }
520 break;
521 case Intrinsic::x86_sse_storeu_ps:
522 case Intrinsic::x86_sse2_storeu_pd:
523 case Intrinsic::x86_sse2_storeu_dq:
524 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner687140c2010-12-25 20:37:57 +0000525 if (getOrEnforceKnownAlignment(II->getArgOperand(0), 16, TD) >= 16) {
Jim Grosbach00e403a2012-02-03 00:07:04 +0000526 Type *OpPtrTy =
Gabor Greif2f1ab742010-06-24 15:51:11 +0000527 PointerType::getUnqual(II->getArgOperand(1)->getType());
528 Value *Ptr = Builder->CreateBitCast(II->getArgOperand(0), OpPtrTy);
529 return new StoreInst(II->getArgOperand(1), Ptr);
Chris Lattner753a2b42010-01-05 07:32:13 +0000530 }
531 break;
Chandler Carruth9cc9f502011-01-10 07:19:37 +0000532
533 case Intrinsic::x86_sse_cvtss2si:
534 case Intrinsic::x86_sse_cvtss2si64:
535 case Intrinsic::x86_sse_cvttss2si:
536 case Intrinsic::x86_sse_cvttss2si64:
537 case Intrinsic::x86_sse2_cvtsd2si:
538 case Intrinsic::x86_sse2_cvtsd2si64:
539 case Intrinsic::x86_sse2_cvttsd2si:
540 case Intrinsic::x86_sse2_cvttsd2si64: {
541 // These intrinsics only demand the 0th element of their input vectors. If
Chris Lattner753a2b42010-01-05 07:32:13 +0000542 // we can simplify the input based on that, do so now.
543 unsigned VWidth =
Gabor Greif9c68a7b2010-06-25 07:57:14 +0000544 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
Chris Lattner753a2b42010-01-05 07:32:13 +0000545 APInt DemandedElts(VWidth, 1);
546 APInt UndefElts(VWidth, 0);
Gabor Greifa3997812010-07-22 10:37:47 +0000547 if (Value *V = SimplifyDemandedVectorElts(II->getArgOperand(0),
548 DemandedElts, UndefElts)) {
Gabor Greifa90c5c72010-06-28 16:50:57 +0000549 II->setArgOperand(0, V);
Chris Lattner753a2b42010-01-05 07:32:13 +0000550 return II;
551 }
552 break;
553 }
Chandler Carruth9cc9f502011-01-10 07:19:37 +0000554
Stuart Hastingsca1ef482011-05-17 22:13:31 +0000555
556 case Intrinsic::x86_sse41_pmovsxbw:
557 case Intrinsic::x86_sse41_pmovsxwd:
558 case Intrinsic::x86_sse41_pmovsxdq:
559 case Intrinsic::x86_sse41_pmovzxbw:
560 case Intrinsic::x86_sse41_pmovzxwd:
561 case Intrinsic::x86_sse41_pmovzxdq: {
Evan Chengaaa7f492011-05-19 18:18:39 +0000562 // pmov{s|z}x ignores the upper half of their input vectors.
Stuart Hastingsca1ef482011-05-17 22:13:31 +0000563 unsigned VWidth =
564 cast<VectorType>(II->getArgOperand(0)->getType())->getNumElements();
565 unsigned LowHalfElts = VWidth / 2;
Stuart Hastingsd1166112011-05-18 15:54:26 +0000566 APInt InputDemandedElts(APInt::getBitsSet(VWidth, 0, LowHalfElts));
Stuart Hastingsca1ef482011-05-17 22:13:31 +0000567 APInt UndefElts(VWidth, 0);
568 if (Value *TmpV = SimplifyDemandedVectorElts(II->getArgOperand(0),
569 InputDemandedElts,
570 UndefElts)) {
571 II->setArgOperand(0, TmpV);
572 return II;
573 }
574 break;
575 }
576
Chris Lattner753a2b42010-01-05 07:32:13 +0000577 case Intrinsic::ppc_altivec_vperm:
578 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000579 if (Constant *Mask = dyn_cast<Constant>(II->getArgOperand(2))) {
580 assert(Mask->getType()->getVectorNumElements() == 16 &&
581 "Bad type for intrinsic!");
Jim Grosbach00e403a2012-02-03 00:07:04 +0000582
Chris Lattner753a2b42010-01-05 07:32:13 +0000583 // Check that all of the elements are integer constants or undefs.
584 bool AllEltsOk = true;
585 for (unsigned i = 0; i != 16; ++i) {
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000586 Constant *Elt = Mask->getAggregateElement(i);
587 if (Elt == 0 ||
588 !(isa<ConstantInt>(Elt) || isa<UndefValue>(Elt))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000589 AllEltsOk = false;
590 break;
591 }
592 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000593
Chris Lattner753a2b42010-01-05 07:32:13 +0000594 if (AllEltsOk) {
595 // Cast the input vectors to byte vectors.
Gabor Greifa3997812010-07-22 10:37:47 +0000596 Value *Op0 = Builder->CreateBitCast(II->getArgOperand(0),
597 Mask->getType());
598 Value *Op1 = Builder->CreateBitCast(II->getArgOperand(1),
599 Mask->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000600 Value *Result = UndefValue::get(Op0->getType());
Jim Grosbach00e403a2012-02-03 00:07:04 +0000601
Chris Lattner753a2b42010-01-05 07:32:13 +0000602 // Only extract each element once.
603 Value *ExtractedElts[32];
604 memset(ExtractedElts, 0, sizeof(ExtractedElts));
Jim Grosbach00e403a2012-02-03 00:07:04 +0000605
Chris Lattner753a2b42010-01-05 07:32:13 +0000606 for (unsigned i = 0; i != 16; ++i) {
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000607 if (isa<UndefValue>(Mask->getAggregateElement(i)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000608 continue;
Jim Grosbach00e403a2012-02-03 00:07:04 +0000609 unsigned Idx =
Chris Lattnera78fa8c2012-01-27 03:08:05 +0000610 cast<ConstantInt>(Mask->getAggregateElement(i))->getZExtValue();
Chris Lattner753a2b42010-01-05 07:32:13 +0000611 Idx &= 31; // Match the hardware behavior.
Jim Grosbach00e403a2012-02-03 00:07:04 +0000612
Chris Lattner753a2b42010-01-05 07:32:13 +0000613 if (ExtractedElts[Idx] == 0) {
Jim Grosbach00e403a2012-02-03 00:07:04 +0000614 ExtractedElts[Idx] =
Benjamin Kramera9390a42011-09-27 20:39:19 +0000615 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
616 Builder->getInt32(Idx&15));
Chris Lattner753a2b42010-01-05 07:32:13 +0000617 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000618
Chris Lattner753a2b42010-01-05 07:32:13 +0000619 // Insert this value into the result vector.
620 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
Benjamin Kramera9390a42011-09-27 20:39:19 +0000621 Builder->getInt32(i));
Chris Lattner753a2b42010-01-05 07:32:13 +0000622 }
623 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
624 }
625 }
626 break;
627
Bob Wilson364f17c2010-10-22 21:41:48 +0000628 case Intrinsic::arm_neon_vld1:
629 case Intrinsic::arm_neon_vld2:
630 case Intrinsic::arm_neon_vld3:
631 case Intrinsic::arm_neon_vld4:
632 case Intrinsic::arm_neon_vld2lane:
633 case Intrinsic::arm_neon_vld3lane:
634 case Intrinsic::arm_neon_vld4lane:
635 case Intrinsic::arm_neon_vst1:
636 case Intrinsic::arm_neon_vst2:
637 case Intrinsic::arm_neon_vst3:
638 case Intrinsic::arm_neon_vst4:
639 case Intrinsic::arm_neon_vst2lane:
640 case Intrinsic::arm_neon_vst3lane:
641 case Intrinsic::arm_neon_vst4lane: {
Chris Lattnerae47be12010-12-25 20:52:04 +0000642 unsigned MemAlign = getKnownAlignment(II->getArgOperand(0), TD);
Bob Wilson364f17c2010-10-22 21:41:48 +0000643 unsigned AlignArg = II->getNumArgOperands() - 1;
644 ConstantInt *IntrAlign = dyn_cast<ConstantInt>(II->getArgOperand(AlignArg));
645 if (IntrAlign && IntrAlign->getZExtValue() < MemAlign) {
646 II->setArgOperand(AlignArg,
647 ConstantInt::get(Type::getInt32Ty(II->getContext()),
648 MemAlign, false));
649 return II;
650 }
651 break;
652 }
653
Lang Hames973f72a2012-05-01 00:20:38 +0000654 case Intrinsic::arm_neon_vmulls:
655 case Intrinsic::arm_neon_vmullu: {
656 Value *Arg0 = II->getArgOperand(0);
657 Value *Arg1 = II->getArgOperand(1);
658
659 // Handle mul by zero first:
660 if (isa<ConstantAggregateZero>(Arg0) || isa<ConstantAggregateZero>(Arg1)) {
661 return ReplaceInstUsesWith(CI, ConstantAggregateZero::get(II->getType()));
662 }
663
664 // Check for constant LHS & RHS - in this case we just simplify.
665 bool Zext = (II->getIntrinsicID() == Intrinsic::arm_neon_vmullu);
666 VectorType *NewVT = cast<VectorType>(II->getType());
667 unsigned NewWidth = NewVT->getElementType()->getIntegerBitWidth();
668 if (ConstantDataVector *CV0 = dyn_cast<ConstantDataVector>(Arg0)) {
669 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
670 VectorType* VT = cast<VectorType>(CV0->getType());
671 SmallVector<Constant*, 4> NewElems;
672 for (unsigned i = 0; i < VT->getNumElements(); ++i) {
673 APInt CV0E =
674 (cast<ConstantInt>(CV0->getAggregateElement(i)))->getValue();
675 CV0E = Zext ? CV0E.zext(NewWidth) : CV0E.sext(NewWidth);
676 APInt CV1E =
677 (cast<ConstantInt>(CV1->getAggregateElement(i)))->getValue();
678 CV1E = Zext ? CV1E.zext(NewWidth) : CV1E.sext(NewWidth);
679 NewElems.push_back(
680 ConstantInt::get(NewVT->getElementType(), CV0E * CV1E));
681 }
682 return ReplaceInstUsesWith(CI, ConstantVector::get(NewElems));
683 }
684
685 // Couldn't simplify - cannonicalize constant to the RHS.
686 std::swap(Arg0, Arg1);
687 }
688
689 // Handle mul by one:
690 if (ConstantDataVector *CV1 = dyn_cast<ConstantDataVector>(Arg1)) {
691 if (ConstantInt *Splat =
692 dyn_cast_or_null<ConstantInt>(CV1->getSplatValue())) {
693 if (Splat->isOne()) {
694 if (Zext)
695 return CastInst::CreateZExtOrBitCast(Arg0, II->getType());
696 // else
697 return CastInst::CreateSExtOrBitCast(Arg0, II->getType());
698 }
699 }
700 }
701
702 break;
703 }
704
Chris Lattner753a2b42010-01-05 07:32:13 +0000705 case Intrinsic::stackrestore: {
706 // If the save is right next to the restore, remove the restore. This can
707 // happen when variable allocas are DCE'd.
Gabor Greifcea7ac72010-06-24 12:58:35 +0000708 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getArgOperand(0))) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000709 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
710 BasicBlock::iterator BI = SS;
711 if (&*++BI == II)
712 return EraseInstFromFunction(CI);
713 }
714 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000715
Chris Lattner753a2b42010-01-05 07:32:13 +0000716 // Scan down this block to see if there is another stack restore in the
717 // same block without an intervening call/alloca.
718 BasicBlock::iterator BI = II;
719 TerminatorInst *TI = II->getParent()->getTerminator();
720 bool CannotRemove = false;
721 for (++BI; &*BI != TI; ++BI) {
Nuno Lopes9e72a792012-06-21 15:45:28 +0000722 if (isa<AllocaInst>(BI)) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000723 CannotRemove = true;
724 break;
725 }
726 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
727 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
728 // If there is a stackrestore below this one, remove this one.
729 if (II->getIntrinsicID() == Intrinsic::stackrestore)
730 return EraseInstFromFunction(CI);
731 // Otherwise, ignore the intrinsic.
732 } else {
733 // If we found a non-intrinsic call, we can't remove the stack
734 // restore.
735 CannotRemove = true;
736 break;
737 }
738 }
739 }
Jim Grosbach00e403a2012-02-03 00:07:04 +0000740
Bill Wendlingdccc03b2011-07-31 06:30:59 +0000741 // If the stack restore is in a return, resume, or unwind block and if there
742 // are no allocas or calls between the restore and the return, nuke the
743 // restore.
Bill Wendlingaa5abe82012-02-06 21:16:41 +0000744 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<ResumeInst>(TI)))
Chris Lattner753a2b42010-01-05 07:32:13 +0000745 return EraseInstFromFunction(CI);
746 break;
747 }
Chris Lattner753a2b42010-01-05 07:32:13 +0000748 }
749
750 return visitCallSite(II);
751}
752
753// InvokeInst simplification
754//
755Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
756 return visitCallSite(&II);
757}
758
Jim Grosbach00e403a2012-02-03 00:07:04 +0000759/// isSafeToEliminateVarargsCast - If this cast does not affect the value
Chris Lattner753a2b42010-01-05 07:32:13 +0000760/// passed through the varargs area, we can eliminate the use of the cast.
761static bool isSafeToEliminateVarargsCast(const CallSite CS,
762 const CastInst * const CI,
Micah Villmow3574eca2012-10-08 16:38:25 +0000763 const DataLayout * const TD,
Chris Lattner753a2b42010-01-05 07:32:13 +0000764 const int ix) {
765 if (!CI->isLosslessCast())
766 return false;
767
768 // The size of ByVal arguments is derived from the type, so we
769 // can't change to a type with a different size. If the size were
770 // passed explicitly we could avoid this check.
Nick Lewycky173862e2011-11-20 19:09:04 +0000771 if (!CS.isByValArgument(ix))
Chris Lattner753a2b42010-01-05 07:32:13 +0000772 return true;
773
Jim Grosbach00e403a2012-02-03 00:07:04 +0000774 Type* SrcTy =
Chris Lattner753a2b42010-01-05 07:32:13 +0000775 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000776 Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner753a2b42010-01-05 07:32:13 +0000777 if (!SrcTy->isSized() || !DstTy->isSized())
778 return false;
779 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
780 return false;
781 return true;
782}
783
Eric Christopher27ceaa12010-03-06 10:50:38 +0000784// Try to fold some different type of calls here.
Jim Grosbach00e403a2012-02-03 00:07:04 +0000785// Currently we're only working with the checking functions, memcpy_chk,
Eric Christopher27ceaa12010-03-06 10:50:38 +0000786// mempcpy_chk, memmove_chk, memset_chk, strcpy_chk, stpcpy_chk, strncpy_chk,
787// strcat_chk and strncat_chk.
Micah Villmow3574eca2012-10-08 16:38:25 +0000788Instruction *InstCombiner::tryOptimizeCall(CallInst *CI, const DataLayout *TD) {
Eric Christopher27ceaa12010-03-06 10:50:38 +0000789 if (CI->getCalledFunction() == 0) return 0;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000790
Meador Inge63f932c2012-11-30 04:05:06 +0000791 if (Value *With = Simplifier->optimizeCall(CI)) {
792 ++NumSimplified;
Meador Ingea241b582012-11-27 18:52:49 +0000793 return CI->use_empty() ? CI : ReplaceInstUsesWith(*CI, With);
Meador Inge63f932c2012-11-30 04:05:06 +0000794 }
Meador Inge5e890452012-10-13 16:45:24 +0000795
796 return 0;
Eric Christopher27ceaa12010-03-06 10:50:38 +0000797}
798
Duncan Sands4a544a72011-09-06 13:37:06 +0000799static IntrinsicInst *FindInitTrampolineFromAlloca(Value *TrampMem) {
800 // Strip off at most one level of pointer casts, looking for an alloca. This
801 // is good enough in practice and simpler than handling any number of casts.
802 Value *Underlying = TrampMem->stripPointerCasts();
803 if (Underlying != TrampMem &&
804 (!Underlying->hasOneUse() || *Underlying->use_begin() != TrampMem))
805 return 0;
806 if (!isa<AllocaInst>(Underlying))
807 return 0;
808
809 IntrinsicInst *InitTrampoline = 0;
810 for (Value::use_iterator I = TrampMem->use_begin(), E = TrampMem->use_end();
811 I != E; I++) {
812 IntrinsicInst *II = dyn_cast<IntrinsicInst>(*I);
813 if (!II)
814 return 0;
815 if (II->getIntrinsicID() == Intrinsic::init_trampoline) {
816 if (InitTrampoline)
817 // More than one init_trampoline writes to this value. Give up.
818 return 0;
819 InitTrampoline = II;
820 continue;
821 }
822 if (II->getIntrinsicID() == Intrinsic::adjust_trampoline)
823 // Allow any number of calls to adjust.trampoline.
824 continue;
825 return 0;
826 }
827
828 // No call to init.trampoline found.
829 if (!InitTrampoline)
830 return 0;
831
832 // Check that the alloca is being used in the expected way.
833 if (InitTrampoline->getOperand(0) != TrampMem)
834 return 0;
835
836 return InitTrampoline;
837}
838
839static IntrinsicInst *FindInitTrampolineFromBB(IntrinsicInst *AdjustTramp,
840 Value *TrampMem) {
841 // Visit all the previous instructions in the basic block, and try to find a
842 // init.trampoline which has a direct path to the adjust.trampoline.
843 for (BasicBlock::iterator I = AdjustTramp,
844 E = AdjustTramp->getParent()->begin(); I != E; ) {
845 Instruction *Inst = --I;
846 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
847 if (II->getIntrinsicID() == Intrinsic::init_trampoline &&
848 II->getOperand(0) == TrampMem)
849 return II;
850 if (Inst->mayWriteToMemory())
851 return 0;
852 }
853 return 0;
854}
855
856// Given a call to llvm.adjust.trampoline, find and return the corresponding
857// call to llvm.init.trampoline if the call to the trampoline can be optimized
858// to a direct call to a function. Otherwise return NULL.
859//
860static IntrinsicInst *FindInitTrampoline(Value *Callee) {
861 Callee = Callee->stripPointerCasts();
862 IntrinsicInst *AdjustTramp = dyn_cast<IntrinsicInst>(Callee);
863 if (!AdjustTramp ||
864 AdjustTramp->getIntrinsicID() != Intrinsic::adjust_trampoline)
865 return 0;
866
867 Value *TrampMem = AdjustTramp->getOperand(0);
868
869 if (IntrinsicInst *IT = FindInitTrampolineFromAlloca(TrampMem))
870 return IT;
871 if (IntrinsicInst *IT = FindInitTrampolineFromBB(AdjustTramp, TrampMem))
872 return IT;
873 return 0;
874}
875
Chris Lattner753a2b42010-01-05 07:32:13 +0000876// visitCallSite - Improvements for call and invoke instructions.
877//
878Instruction *InstCombiner::visitCallSite(CallSite CS) {
Benjamin Kramer8e0d1c02012-08-29 15:32:21 +0000879 if (isAllocLikeFn(CS.getInstruction(), TLI))
Nuno Lopes78f8ef42012-07-09 18:38:20 +0000880 return visitAllocSite(*CS.getInstruction());
Nuno Lopes2b3e9582012-06-21 21:25:05 +0000881
Chris Lattner753a2b42010-01-05 07:32:13 +0000882 bool Changed = false;
883
Chris Lattnerab215bc2010-12-20 08:25:06 +0000884 // If the callee is a pointer to a function, attempt to move any casts to the
885 // arguments of the call/invoke.
Chris Lattner753a2b42010-01-05 07:32:13 +0000886 Value *Callee = CS.getCalledValue();
Chris Lattnerab215bc2010-12-20 08:25:06 +0000887 if (!isa<Function>(Callee) && transformConstExprCastCall(CS))
888 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000889
890 if (Function *CalleeF = dyn_cast<Function>(Callee))
Chris Lattnerd5695612010-02-01 18:11:34 +0000891 // If the call and callee calling conventions don't match, this call must
892 // be unreachable, as the call is undefined.
893 if (CalleeF->getCallingConv() != CS.getCallingConv() &&
894 // Only do this for calls to a function with a body. A prototype may
895 // not actually end up matching the implementation's calling conv for a
896 // variety of reasons (e.g. it may be written in assembly).
897 !CalleeF->isDeclaration()) {
Chris Lattner753a2b42010-01-05 07:32:13 +0000898 Instruction *OldCall = CS.getInstruction();
Chris Lattner753a2b42010-01-05 07:32:13 +0000899 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
Jim Grosbach00e403a2012-02-03 00:07:04 +0000900 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
Chris Lattner753a2b42010-01-05 07:32:13 +0000901 OldCall);
902 // If OldCall dues not return void then replaceAllUsesWith undef.
903 // This allows ValueHandlers and custom metadata to adjust itself.
904 if (!OldCall->getType()->isVoidTy())
Eli Friedman3e22cb92011-05-18 00:32:01 +0000905 ReplaceInstUsesWith(*OldCall, UndefValue::get(OldCall->getType()));
Chris Lattner830f3f22010-02-01 18:04:58 +0000906 if (isa<CallInst>(OldCall))
Chris Lattner753a2b42010-01-05 07:32:13 +0000907 return EraseInstFromFunction(*OldCall);
Jim Grosbach00e403a2012-02-03 00:07:04 +0000908
Chris Lattner830f3f22010-02-01 18:04:58 +0000909 // We cannot remove an invoke, because it would change the CFG, just
910 // change the callee to a null pointer.
Gabor Greif654c06f2010-03-20 21:00:25 +0000911 cast<InvokeInst>(OldCall)->setCalledFunction(
Chris Lattner830f3f22010-02-01 18:04:58 +0000912 Constant::getNullValue(CalleeF->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000913 return 0;
914 }
915
916 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
Gabor Greifcea7ac72010-06-24 12:58:35 +0000917 // If CS does not return void then replaceAllUsesWith undef.
Chris Lattner753a2b42010-01-05 07:32:13 +0000918 // This allows ValueHandlers and custom metadata to adjust itself.
919 if (!CS.getInstruction()->getType()->isVoidTy())
Eli Friedman3e22cb92011-05-18 00:32:01 +0000920 ReplaceInstUsesWith(*CS.getInstruction(),
921 UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner753a2b42010-01-05 07:32:13 +0000922
Nuno Lopesf1fb6c82012-06-21 23:52:14 +0000923 if (isa<InvokeInst>(CS.getInstruction())) {
924 // Can't remove an invoke because we cannot change the CFG.
925 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +0000926 }
Nuno Lopesf1fb6c82012-06-21 23:52:14 +0000927
928 // This instruction is not reachable, just remove it. We insert a store to
929 // undef so that we know that this code is not reachable, despite the fact
930 // that we can't modify the CFG here.
931 new StoreInst(ConstantInt::getTrue(Callee->getContext()),
932 UndefValue::get(Type::getInt1PtrTy(Callee->getContext())),
933 CS.getInstruction());
934
Chris Lattner753a2b42010-01-05 07:32:13 +0000935 return EraseInstFromFunction(*CS.getInstruction());
936 }
937
Duncan Sands4a544a72011-09-06 13:37:06 +0000938 if (IntrinsicInst *II = FindInitTrampoline(Callee))
939 return transformCallThroughTrampoline(CS, II);
Chris Lattner753a2b42010-01-05 07:32:13 +0000940
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000941 PointerType *PTy = cast<PointerType>(Callee->getType());
942 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner753a2b42010-01-05 07:32:13 +0000943 if (FTy->isVarArg()) {
Eli Friedmanba78c882011-11-29 01:18:23 +0000944 int ix = FTy->getNumParams();
Chris Lattner753a2b42010-01-05 07:32:13 +0000945 // See if we can optimize any arguments passed through the varargs area of
946 // the call.
947 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
948 E = CS.arg_end(); I != E; ++I, ++ix) {
949 CastInst *CI = dyn_cast<CastInst>(*I);
950 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
951 *I = CI->getOperand(0);
952 Changed = true;
953 }
954 }
955 }
956
957 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
958 // Inline asm calls cannot throw - mark them 'nounwind'.
959 CS.setDoesNotThrow();
960 Changed = true;
961 }
962
Micah Villmow3574eca2012-10-08 16:38:25 +0000963 // Try to optimize the call if possible, we require DataLayout for most of
Eric Christopher27ceaa12010-03-06 10:50:38 +0000964 // this. None of these calls are seen as possibly dead so go ahead and
965 // delete the instruction now.
966 if (CallInst *CI = dyn_cast<CallInst>(CS.getInstruction())) {
967 Instruction *I = tryOptimizeCall(CI, TD);
Eric Christopher7b323a32010-03-06 10:59:25 +0000968 // If we changed something return the result, etc. Otherwise let
969 // the fallthrough check.
970 if (I) return EraseInstFromFunction(*I);
Eric Christopher27ceaa12010-03-06 10:50:38 +0000971 }
972
Chris Lattner753a2b42010-01-05 07:32:13 +0000973 return Changed ? CS.getInstruction() : 0;
974}
975
976// transformConstExprCastCall - If the callee is a constexpr cast of a function,
977// attempt to move the cast to the arguments of the call/invoke.
978//
979bool InstCombiner::transformConstExprCastCall(CallSite CS) {
Chris Lattnerab215bc2010-12-20 08:25:06 +0000980 Function *Callee =
981 dyn_cast<Function>(CS.getCalledValue()->stripPointerCasts());
982 if (Callee == 0)
Chris Lattner753a2b42010-01-05 07:32:13 +0000983 return false;
Chris Lattner753a2b42010-01-05 07:32:13 +0000984 Instruction *Caller = CS.getInstruction();
985 const AttrListPtr &CallerPAL = CS.getAttributes();
986
987 // Okay, this is a cast from a function to a different type. Unless doing so
988 // would cause a type conversion of one of our arguments, change this call to
989 // be a direct call with arguments casted to the appropriate types.
990 //
Chris Lattnerdb125cf2011-07-18 04:54:35 +0000991 FunctionType *FT = Callee->getFunctionType();
992 Type *OldRetTy = Caller->getType();
993 Type *NewRetTy = FT->getReturnType();
Chris Lattner753a2b42010-01-05 07:32:13 +0000994
Duncan Sands1df98592010-02-16 11:11:14 +0000995 if (NewRetTy->isStructTy())
Chris Lattner753a2b42010-01-05 07:32:13 +0000996 return false; // TODO: Handle multiple return values.
997
998 // Check to see if we are changing the return type...
999 if (OldRetTy != NewRetTy) {
1000 if (Callee->isDeclaration() &&
1001 // Conversion is ok if changing from one pointer type to another or from
1002 // a pointer to an integer of the same size.
Duncan Sands1df98592010-02-16 11:11:14 +00001003 !((OldRetTy->isPointerTy() || !TD ||
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001004 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001005 (NewRetTy->isPointerTy() || !TD ||
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001006 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattner753a2b42010-01-05 07:32:13 +00001007 return false; // Cannot transform this return value.
1008
1009 if (!Caller->use_empty() &&
1010 // void -> non-void is handled specially
1011 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
1012 return false; // Cannot transform this return value.
1013
1014 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Bill Wendling702cc912012-10-15 20:35:56 +00001015 AttrBuilder RAttrs = CallerPAL.getRetAttributes();
Bill Wendling8831c062012-10-09 00:01:21 +00001016 if (RAttrs.hasAttributes(Attributes::typeIncompatible(NewRetTy)))
Chris Lattner753a2b42010-01-05 07:32:13 +00001017 return false; // Attribute not compatible with transformed value.
1018 }
1019
1020 // If the callsite is an invoke instruction, and the return value is used by
1021 // a PHI node in a successor, we cannot change the return type of the call
1022 // because there is no place to put the cast instruction (without breaking
1023 // the critical edge). Bail out in this case.
1024 if (!Caller->use_empty())
1025 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
1026 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
1027 UI != E; ++UI)
1028 if (PHINode *PN = dyn_cast<PHINode>(*UI))
1029 if (PN->getParent() == II->getNormalDest() ||
1030 PN->getParent() == II->getUnwindDest())
1031 return false;
1032 }
1033
1034 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1035 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1036
1037 CallSite::arg_iterator AI = CS.arg_begin();
1038 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001039 Type *ParamTy = FT->getParamType(i);
1040 Type *ActTy = (*AI)->getType();
Chris Lattner753a2b42010-01-05 07:32:13 +00001041
1042 if (!CastInst::isCastable(ActTy, ParamTy))
1043 return false; // Cannot transform this parameter value.
1044
Kostya Serebryany164b86b2012-01-20 17:56:17 +00001045 Attributes Attrs = CallerPAL.getParamAttributes(i + 1);
Bill Wendling702cc912012-10-15 20:35:56 +00001046 if (AttrBuilder(Attrs).
Bill Wendling1feacad2012-10-14 07:52:48 +00001047 hasAttributes(Attributes::typeIncompatible(ParamTy)))
Chris Lattner753a2b42010-01-05 07:32:13 +00001048 return false; // Attribute not compatible with transformed value.
Jim Grosbach00e403a2012-02-03 00:07:04 +00001049
Chris Lattner2b9375e2010-12-20 08:36:38 +00001050 // If the parameter is passed as a byval argument, then we have to have a
1051 // sized type and the sized type has to have the same size as the old type.
Bill Wendling67658342012-10-09 07:45:08 +00001052 if (ParamTy != ActTy && Attrs.hasAttribute(Attributes::ByVal)) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001053 PointerType *ParamPTy = dyn_cast<PointerType>(ParamTy);
Chris Lattner2b9375e2010-12-20 08:36:38 +00001054 if (ParamPTy == 0 || !ParamPTy->getElementType()->isSized() || TD == 0)
1055 return false;
Jim Grosbach00e403a2012-02-03 00:07:04 +00001056
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001057 Type *CurElTy = cast<PointerType>(ActTy)->getElementType();
Chris Lattner2b9375e2010-12-20 08:36:38 +00001058 if (TD->getTypeAllocSize(CurElTy) !=
1059 TD->getTypeAllocSize(ParamPTy->getElementType()))
1060 return false;
1061 }
Chris Lattner753a2b42010-01-05 07:32:13 +00001062
1063 // Converting from one pointer type to another or between a pointer and an
1064 // integer of the same size is safe even if we do not have a body.
1065 bool isConvertible = ActTy == ParamTy ||
Duncan Sands1df98592010-02-16 11:11:14 +00001066 (TD && ((ParamTy->isPointerTy() ||
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001067 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
Duncan Sands1df98592010-02-16 11:11:14 +00001068 (ActTy->isPointerTy() ||
Chandler Carruthece6c6b2012-11-01 08:07:29 +00001069 ActTy == TD->getIntPtrType(Caller->getContext()))));
Chris Lattner753a2b42010-01-05 07:32:13 +00001070 if (Callee->isDeclaration() && !isConvertible) return false;
1071 }
1072
Chris Lattner091b1e32011-02-24 05:10:56 +00001073 if (Callee->isDeclaration()) {
1074 // Do not delete arguments unless we have a function body.
1075 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg())
1076 return false;
Chris Lattner753a2b42010-01-05 07:32:13 +00001077
Chris Lattner091b1e32011-02-24 05:10:56 +00001078 // If the callee is just a declaration, don't change the varargsness of the
1079 // call. We don't want to introduce a varargs call where one doesn't
1080 // already exist.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001081 PointerType *APTy = cast<PointerType>(CS.getCalledValue()->getType());
Chris Lattner091b1e32011-02-24 05:10:56 +00001082 if (FT->isVarArg()!=cast<FunctionType>(APTy->getElementType())->isVarArg())
1083 return false;
Jim Grosbachf3744862012-02-03 00:00:55 +00001084
1085 // If both the callee and the cast type are varargs, we still have to make
1086 // sure the number of fixed parameters are the same or we have the same
1087 // ABI issues as if we introduce a varargs call.
Jim Grosbach871a2052012-02-03 00:26:07 +00001088 if (FT->isVarArg() &&
1089 cast<FunctionType>(APTy->getElementType())->isVarArg() &&
1090 FT->getNumParams() !=
Jim Grosbachf3744862012-02-03 00:00:55 +00001091 cast<FunctionType>(APTy->getElementType())->getNumParams())
1092 return false;
Chris Lattner091b1e32011-02-24 05:10:56 +00001093 }
Jim Grosbach00e403a2012-02-03 00:07:04 +00001094
Jim Grosbachd5917f02012-02-03 00:00:50 +00001095 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
1096 !CallerPAL.isEmpty())
1097 // In this case we have more arguments than the new function type, but we
1098 // won't be dropping them. Check that these extra arguments have attributes
1099 // that are compatible with being a vararg call argument.
1100 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
1101 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
1102 break;
1103 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Bill Wendling8831c062012-10-09 00:01:21 +00001104 if (PAttrs.hasIncompatibleWithVarArgsAttrs())
Jim Grosbachd5917f02012-02-03 00:00:50 +00001105 return false;
1106 }
Chris Lattner753a2b42010-01-05 07:32:13 +00001107
Jim Grosbach00e403a2012-02-03 00:07:04 +00001108
Chris Lattner753a2b42010-01-05 07:32:13 +00001109 // Okay, we decided that this is a safe thing to do: go ahead and start
Chris Lattner091b1e32011-02-24 05:10:56 +00001110 // inserting cast instructions as necessary.
Chris Lattner753a2b42010-01-05 07:32:13 +00001111 std::vector<Value*> Args;
1112 Args.reserve(NumActualArgs);
1113 SmallVector<AttributeWithIndex, 8> attrVec;
1114 attrVec.reserve(NumCommonArgs);
1115
1116 // Get any return attributes.
Bill Wendling702cc912012-10-15 20:35:56 +00001117 AttrBuilder RAttrs = CallerPAL.getRetAttributes();
Chris Lattner753a2b42010-01-05 07:32:13 +00001118
1119 // If the return value is not being used, the type may not be compatible
1120 // with the existing attributes. Wipe out any problematic attributes.
Bill Wendling8831c062012-10-09 00:01:21 +00001121 RAttrs.removeAttributes(Attributes::typeIncompatible(NewRetTy));
Chris Lattner753a2b42010-01-05 07:32:13 +00001122
1123 // Add the new return attributes.
Bill Wendling8831c062012-10-09 00:01:21 +00001124 if (RAttrs.hasAttributes())
Bill Wendlingcb3de0b2012-10-15 04:46:55 +00001125 attrVec.push_back(
Bill Wendling07aae2e2012-10-15 07:29:08 +00001126 AttributeWithIndex::get(AttrListPtr::ReturnIndex,
1127 Attributes::get(FT->getContext(), RAttrs)));
Chris Lattner753a2b42010-01-05 07:32:13 +00001128
1129 AI = CS.arg_begin();
1130 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001131 Type *ParamTy = FT->getParamType(i);
Chris Lattner753a2b42010-01-05 07:32:13 +00001132 if ((*AI)->getType() == ParamTy) {
1133 Args.push_back(*AI);
1134 } else {
1135 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
1136 false, ParamTy, false);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001137 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy));
Chris Lattner753a2b42010-01-05 07:32:13 +00001138 }
1139
1140 // Add any parameter attributes.
Bill Wendling7be78482012-10-14 08:54:26 +00001141 Attributes PAttrs = CallerPAL.getParamAttributes(i + 1);
1142 if (PAttrs.hasAttributes())
Chris Lattner753a2b42010-01-05 07:32:13 +00001143 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1144 }
1145
1146 // If the function takes more arguments than the call was taking, add them
1147 // now.
1148 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1149 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1150
1151 // If we are removing arguments to the function, emit an obnoxious warning.
1152 if (FT->getNumParams() < NumActualArgs) {
1153 if (!FT->isVarArg()) {
1154 errs() << "WARNING: While resolving call to function '"
1155 << Callee->getName() << "' arguments were dropped!\n";
1156 } else {
1157 // Add all of the arguments in their promoted form to the arg list.
1158 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001159 Type *PTy = getPromotedType((*AI)->getType());
Chris Lattner753a2b42010-01-05 07:32:13 +00001160 if (PTy != (*AI)->getType()) {
1161 // Must promote to pass through va_arg area!
1162 Instruction::CastOps opcode =
1163 CastInst::getCastOpcode(*AI, false, PTy, false);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001164 Args.push_back(Builder->CreateCast(opcode, *AI, PTy));
Chris Lattner753a2b42010-01-05 07:32:13 +00001165 } else {
1166 Args.push_back(*AI);
1167 }
1168
1169 // Add any parameter attributes.
Bill Wendling7be78482012-10-14 08:54:26 +00001170 Attributes PAttrs = CallerPAL.getParamAttributes(i + 1);
1171 if (PAttrs.hasAttributes())
Chris Lattner753a2b42010-01-05 07:32:13 +00001172 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
1173 }
1174 }
1175 }
1176
Bill Wendling7be78482012-10-14 08:54:26 +00001177 Attributes FnAttrs = CallerPAL.getFnAttributes();
1178 if (FnAttrs.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00001179 attrVec.push_back(AttributeWithIndex::get(AttrListPtr::FunctionIndex,
1180 FnAttrs));
Chris Lattner753a2b42010-01-05 07:32:13 +00001181
1182 if (NewRetTy->isVoidTy())
1183 Caller->setName(""); // Void type should not have a name.
1184
Bill Wendling0976e002012-11-20 05:09:20 +00001185 const AttrListPtr &NewCallerPAL = AttrListPtr::get(Callee->getContext(),
1186 attrVec);
Chris Lattner753a2b42010-01-05 07:32:13 +00001187
1188 Instruction *NC;
1189 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Eli Friedmanef819d02011-05-18 01:28:27 +00001190 NC = Builder->CreateInvoke(Callee, II->getNormalDest(),
Jay Foada3efbb12011-07-15 08:37:34 +00001191 II->getUnwindDest(), Args);
Eli Friedmanef819d02011-05-18 01:28:27 +00001192 NC->takeName(II);
Chris Lattner753a2b42010-01-05 07:32:13 +00001193 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
1194 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
1195 } else {
Chris Lattner753a2b42010-01-05 07:32:13 +00001196 CallInst *CI = cast<CallInst>(Caller);
Jay Foada3efbb12011-07-15 08:37:34 +00001197 NC = Builder->CreateCall(Callee, Args);
Eli Friedmanef819d02011-05-18 01:28:27 +00001198 NC->takeName(CI);
Chris Lattner753a2b42010-01-05 07:32:13 +00001199 if (CI->isTailCall())
1200 cast<CallInst>(NC)->setTailCall();
1201 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
1202 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
1203 }
1204
1205 // Insert a cast of the return type as necessary.
1206 Value *NV = NC;
1207 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
1208 if (!NV->getType()->isVoidTy()) {
Chris Lattnerab215bc2010-12-20 08:25:06 +00001209 Instruction::CastOps opcode =
1210 CastInst::getCastOpcode(NC, false, OldRetTy, false);
Benjamin Kramera9390a42011-09-27 20:39:19 +00001211 NV = NC = CastInst::Create(opcode, NC, OldRetTy);
Eli Friedmana311c342011-05-27 00:19:40 +00001212 NC->setDebugLoc(Caller->getDebugLoc());
Chris Lattner753a2b42010-01-05 07:32:13 +00001213
1214 // If this is an invoke instruction, we should insert it after the first
1215 // non-phi, instruction in the normal successor block.
1216 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Bill Wendling89d44112011-08-25 01:08:34 +00001217 BasicBlock::iterator I = II->getNormalDest()->getFirstInsertionPt();
Chris Lattner753a2b42010-01-05 07:32:13 +00001218 InsertNewInstBefore(NC, *I);
1219 } else {
Chris Lattnerab215bc2010-12-20 08:25:06 +00001220 // Otherwise, it's a call, just insert cast right after the call.
Chris Lattner753a2b42010-01-05 07:32:13 +00001221 InsertNewInstBefore(NC, *Caller);
1222 }
1223 Worklist.AddUsersToWorkList(*Caller);
1224 } else {
1225 NV = UndefValue::get(Caller->getType());
1226 }
1227 }
1228
Chris Lattner753a2b42010-01-05 07:32:13 +00001229 if (!Caller->use_empty())
Eli Friedman3e22cb92011-05-18 00:32:01 +00001230 ReplaceInstUsesWith(*Caller, NV);
1231
Chris Lattner753a2b42010-01-05 07:32:13 +00001232 EraseInstFromFunction(*Caller);
1233 return true;
1234}
1235
Duncan Sands4a544a72011-09-06 13:37:06 +00001236// transformCallThroughTrampoline - Turn a call to a function created by
1237// init_trampoline / adjust_trampoline intrinsic pair into a direct call to the
1238// underlying function.
Chris Lattner753a2b42010-01-05 07:32:13 +00001239//
Duncan Sands4a544a72011-09-06 13:37:06 +00001240Instruction *
1241InstCombiner::transformCallThroughTrampoline(CallSite CS,
1242 IntrinsicInst *Tramp) {
Chris Lattner753a2b42010-01-05 07:32:13 +00001243 Value *Callee = CS.getCalledValue();
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001244 PointerType *PTy = cast<PointerType>(Callee->getType());
1245 FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner753a2b42010-01-05 07:32:13 +00001246 const AttrListPtr &Attrs = CS.getAttributes();
1247
1248 // If the call already has the 'nest' attribute somewhere then give up -
1249 // otherwise 'nest' would occur twice after splicing in the chain.
Bill Wendling8831c062012-10-09 00:01:21 +00001250 for (unsigned I = 0, E = Attrs.getNumAttrs(); I != E; ++I)
Bill Wendling67658342012-10-09 07:45:08 +00001251 if (Attrs.getAttributesAtIndex(I).hasAttribute(Attributes::Nest))
Bill Wendling8831c062012-10-09 00:01:21 +00001252 return 0;
Chris Lattner753a2b42010-01-05 07:32:13 +00001253
Duncan Sands4a544a72011-09-06 13:37:06 +00001254 assert(Tramp &&
1255 "transformCallThroughTrampoline called with incorrect CallSite.");
Chris Lattner753a2b42010-01-05 07:32:13 +00001256
Gabor Greifa3997812010-07-22 10:37:47 +00001257 Function *NestF =cast<Function>(Tramp->getArgOperand(1)->stripPointerCasts());
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001258 PointerType *NestFPTy = cast<PointerType>(NestF->getType());
1259 FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
Chris Lattner753a2b42010-01-05 07:32:13 +00001260
1261 const AttrListPtr &NestAttrs = NestF->getAttributes();
1262 if (!NestAttrs.isEmpty()) {
1263 unsigned NestIdx = 1;
Jay Foad5fdd6c82011-07-12 14:06:48 +00001264 Type *NestTy = 0;
Bill Wendling8831c062012-10-09 00:01:21 +00001265 Attributes NestAttr;
Chris Lattner753a2b42010-01-05 07:32:13 +00001266
1267 // Look for a parameter marked with the 'nest' attribute.
1268 for (FunctionType::param_iterator I = NestFTy->param_begin(),
1269 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Bill Wendling67658342012-10-09 07:45:08 +00001270 if (NestAttrs.getParamAttributes(NestIdx).hasAttribute(Attributes::Nest)){
Chris Lattner753a2b42010-01-05 07:32:13 +00001271 // Record the parameter type and any other attributes.
1272 NestTy = *I;
1273 NestAttr = NestAttrs.getParamAttributes(NestIdx);
1274 break;
1275 }
1276
1277 if (NestTy) {
1278 Instruction *Caller = CS.getInstruction();
1279 std::vector<Value*> NewArgs;
1280 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
1281
1282 SmallVector<AttributeWithIndex, 8> NewAttrs;
1283 NewAttrs.reserve(Attrs.getNumSlots() + 1);
1284
1285 // Insert the nest argument into the call argument list, which may
1286 // mean appending it. Likewise for attributes.
1287
1288 // Add any result attributes.
Bill Wendling7be78482012-10-14 08:54:26 +00001289 Attributes Attr = Attrs.getRetAttributes();
1290 if (Attr.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00001291 NewAttrs.push_back(AttributeWithIndex::get(AttrListPtr::ReturnIndex,
1292 Attr));
Chris Lattner753a2b42010-01-05 07:32:13 +00001293
1294 {
1295 unsigned Idx = 1;
1296 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
1297 do {
1298 if (Idx == NestIdx) {
1299 // Add the chain argument and attributes.
Gabor Greifcea7ac72010-06-24 12:58:35 +00001300 Value *NestVal = Tramp->getArgOperand(2);
Chris Lattner753a2b42010-01-05 07:32:13 +00001301 if (NestVal->getType() != NestTy)
Eli Friedmane6f364b2011-05-18 23:58:37 +00001302 NestVal = Builder->CreateBitCast(NestVal, NestTy, "nest");
Chris Lattner753a2b42010-01-05 07:32:13 +00001303 NewArgs.push_back(NestVal);
1304 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
1305 }
1306
1307 if (I == E)
1308 break;
1309
1310 // Add the original argument and attributes.
1311 NewArgs.push_back(*I);
Bill Wendling7be78482012-10-14 08:54:26 +00001312 Attr = Attrs.getParamAttributes(Idx);
1313 if (Attr.hasAttributes())
Chris Lattner753a2b42010-01-05 07:32:13 +00001314 NewAttrs.push_back
1315 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
1316
1317 ++Idx, ++I;
1318 } while (1);
1319 }
1320
1321 // Add any function attributes.
Bill Wendling7be78482012-10-14 08:54:26 +00001322 Attr = Attrs.getFnAttributes();
1323 if (Attr.hasAttributes())
Bill Wendling07aae2e2012-10-15 07:29:08 +00001324 NewAttrs.push_back(AttributeWithIndex::get(AttrListPtr::FunctionIndex,
1325 Attr));
Chris Lattner753a2b42010-01-05 07:32:13 +00001326
1327 // The trampoline may have been bitcast to a bogus type (FTy).
1328 // Handle this by synthesizing a new function type, equal to FTy
1329 // with the chain parameter inserted.
1330
Jay Foad5fdd6c82011-07-12 14:06:48 +00001331 std::vector<Type*> NewTypes;
Chris Lattner753a2b42010-01-05 07:32:13 +00001332 NewTypes.reserve(FTy->getNumParams()+1);
1333
1334 // Insert the chain's type into the list of parameter types, which may
1335 // mean appending it.
1336 {
1337 unsigned Idx = 1;
1338 FunctionType::param_iterator I = FTy->param_begin(),
1339 E = FTy->param_end();
1340
1341 do {
1342 if (Idx == NestIdx)
1343 // Add the chain's type.
1344 NewTypes.push_back(NestTy);
1345
1346 if (I == E)
1347 break;
1348
1349 // Add the original type.
1350 NewTypes.push_back(*I);
1351
1352 ++Idx, ++I;
1353 } while (1);
1354 }
1355
1356 // Replace the trampoline call with a direct call. Let the generic
1357 // code sort out any function type mismatches.
Jim Grosbach00e403a2012-02-03 00:07:04 +00001358 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Chris Lattner753a2b42010-01-05 07:32:13 +00001359 FTy->isVarArg());
1360 Constant *NewCallee =
1361 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Jim Grosbach00e403a2012-02-03 00:07:04 +00001362 NestF : ConstantExpr::getBitCast(NestF,
Chris Lattner753a2b42010-01-05 07:32:13 +00001363 PointerType::getUnqual(NewFTy));
Bill Wendling0976e002012-11-20 05:09:20 +00001364 const AttrListPtr &NewPAL = AttrListPtr::get(FTy->getContext(), NewAttrs);
Chris Lattner753a2b42010-01-05 07:32:13 +00001365
1366 Instruction *NewCaller;
1367 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1368 NewCaller = InvokeInst::Create(NewCallee,
1369 II->getNormalDest(), II->getUnwindDest(),
Jay Foada3efbb12011-07-15 08:37:34 +00001370 NewArgs);
Chris Lattner753a2b42010-01-05 07:32:13 +00001371 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
1372 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
1373 } else {
Jay Foada3efbb12011-07-15 08:37:34 +00001374 NewCaller = CallInst::Create(NewCallee, NewArgs);
Chris Lattner753a2b42010-01-05 07:32:13 +00001375 if (cast<CallInst>(Caller)->isTailCall())
1376 cast<CallInst>(NewCaller)->setTailCall();
1377 cast<CallInst>(NewCaller)->
1378 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
1379 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
1380 }
Eli Friedman59f15912011-05-18 19:57:14 +00001381
1382 return NewCaller;
Chris Lattner753a2b42010-01-05 07:32:13 +00001383 }
1384 }
1385
1386 // Replace the trampoline call with a direct call. Since there is no 'nest'
1387 // parameter, there is no need to adjust the argument list. Let the generic
1388 // code sort out any function type mismatches.
1389 Constant *NewCallee =
Jim Grosbach00e403a2012-02-03 00:07:04 +00001390 NestF->getType() == PTy ? NestF :
Chris Lattner753a2b42010-01-05 07:32:13 +00001391 ConstantExpr::getBitCast(NestF, PTy);
1392 CS.setCalledFunction(NewCallee);
1393 return CS.getInstruction();
1394}