blob: 43a341856045a45598f0a5f5a8ccf3db8fa77965 [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
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 a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
Chris Lattnere9f9a7e2009-09-03 05:19:59 +000012// library functions). Any optimization that takes the very simple form
13// "replace call to library function with simpler code that provides the same
14// result" belongs in this file.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000015//
16//===----------------------------------------------------------------------===//
17
18#define DEBUG_TYPE "simplify-libcalls"
19#include "llvm/Transforms/Scalar.h"
20#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000021#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000022#include "llvm/Module.h"
23#include "llvm/Pass.h"
24#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000025#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000026#include "llvm/Target/TargetData.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringMap.h"
29#include "llvm/ADT/Statistic.h"
Daniel Dunbar473955f2009-07-29 22:00:43 +000030#include "llvm/ADT/STLExtras.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000031#include "llvm/Support/Debug.h"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000032#include "llvm/Support/raw_ostream.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000033#include "llvm/Config/config.h"
34using namespace llvm;
35
36STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000037STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000038
39//===----------------------------------------------------------------------===//
40// Optimizer Base Class
41//===----------------------------------------------------------------------===//
42
43/// This class is the abstract base class for the set of optimizations that
44/// corresponds to one library call.
45namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +000046class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000047protected:
48 Function *Caller;
49 const TargetData *TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000050 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000051public:
52 LibCallOptimization() { }
53 virtual ~LibCallOptimization() {}
54
55 /// CallOptimizer - This pure virtual method is implemented by base classes to
56 /// do various optimizations. If this returns null then no transformation was
57 /// performed. If it returns CI, then it transformed the call and CI is to be
58 /// deleted. If it returns something else, replace CI with the new value and
59 /// delete CI.
Eric Christopher37c8b862009-10-07 21:14:25 +000060 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
Eric Christopher7a61d702008-08-08 19:39:37 +000061 =0;
Eric Christopher37c8b862009-10-07 21:14:25 +000062
Dan Gohmanf14d9192009-08-18 00:48:13 +000063 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000064 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000065 this->TD = TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000066 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000067 Context = &CI->getCalledFunction()->getContext();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000068 return CallOptimizer(CI->getCalledFunction(), CI, B);
69 }
70
71 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +000072 Value *CastToCStr(Value *V, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000073
74 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
75 /// specified pointer. Ptr is required to be some pointer type, and the
76 /// return value has 'intptr_t' type.
Eric Christopher7a61d702008-08-08 19:39:37 +000077 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +000078
Chris Lattner24604112009-12-16 09:32:05 +000079 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
80 /// specified pointer and character. Ptr is required to be some pointer type,
81 /// and the return value has 'i8*' type.
82 Value *EmitStrChr(Value *Ptr, char C, IRBuilder<> &B);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +000083
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000084 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
85 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
Eric Christopher37c8b862009-10-07 21:14:25 +000086 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +000087 unsigned Align, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +000088
Eric Christopher80bf1d52009-11-21 01:01:30 +000089 /// EmitMemMove - Emit a call to the memmove function to the builder. This
90 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
91 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
92 unsigned Align, IRBuilder<> &B);
93
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000094 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
95 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
Eric Christopher7a61d702008-08-08 19:39:37 +000096 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +000097
98 /// EmitMemCmp - Emit a call to the memcmp function.
99 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
100
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000101 /// EmitMemSet - Emit a call to the memset function
102 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
103
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000104 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name'
105 /// (e.g. 'floor'). This function is known to take a single of type matching
106 /// 'Op' and returns one value with the same type. If 'Op' is a long double,
107 /// 'l' is added as the suffix of name, if 'Op' is a float, we add a 'f'
108 /// suffix.
Dan Gohman79cb8402009-09-25 23:10:17 +0000109 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
110 const AttrListPtr &Attrs);
Eric Christopher37c8b862009-10-07 21:14:25 +0000111
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000112 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
113 /// is an integer.
Chris Lattner74965f22009-11-09 04:57:04 +0000114 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000115
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000116 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
117 /// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000118 void EmitPutS(Value *Str, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000119
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000120 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
121 /// an i32, and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000122 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000123
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000124 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
125 /// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000126 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000127
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000128 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
129 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000130 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000131
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000132};
133} // End anonymous namespace.
134
135/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +0000136Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
Chris Lattnerbf796322009-12-02 06:05:42 +0000137 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000138}
139
140/// EmitStrLen - Emit a call to the strlen function to the builder, for the
141/// specified pointer. This always returns an integer value of size intptr_t.
Eric Christopher7a61d702008-08-08 19:39:37 +0000142Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000143 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000144 AttributeWithIndex AWI[2];
145 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
146 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
147 Attribute::NoUnwind);
148
149 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
Owen Anderson1d0be152009-08-13 21:58:54 +0000150 TD->getIntPtrType(*Context),
Eric Christopher37c8b862009-10-07 21:14:25 +0000151 Type::getInt8PtrTy(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000152 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000153 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
154 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
155 CI->setCallingConv(F->getCallingConv());
156
157 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000158}
159
Chris Lattner24604112009-12-16 09:32:05 +0000160/// EmitStrChr - Emit a call to the strchr function to the builder, for the
161/// specified pointer and character. Ptr is required to be some pointer type,
162/// and the return value has 'i8*' type.
163Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
164 Module *M = Caller->getParent();
165 AttributeWithIndex AWI =
166 AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000167
Chris Lattner24604112009-12-16 09:32:05 +0000168 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
169 const Type *I32Ty = Type::getInt32Ty(*Context);
170 Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
171 I8Ptr, I8Ptr, I32Ty, NULL);
172 CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
173 ConstantInt::get(I32Ty, C), "strchr");
174 if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
175 CI->setCallingConv(F->getCallingConv());
176 return CI;
177}
178
179
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000180/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
181/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
182Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +0000183 unsigned Align, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000184 Module *M = Caller->getParent();
Chris Lattnerbf796322009-12-02 06:05:42 +0000185 const Type *Ty = Len->getType();
186 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
187 Dst = CastToCStr(Dst, B);
188 Src = CastToCStr(Src, B);
189 return B.CreateCall4(MemCpy, Dst, Src, Len,
Owen Anderson1d0be152009-08-13 21:58:54 +0000190 ConstantInt::get(Type::getInt32Ty(*Context), Align));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000191}
192
Chris Lattnerbf796322009-12-02 06:05:42 +0000193/// EmitMemMove - Emit a call to the memmove function to the builder. This
Eric Christopher80bf1d52009-11-21 01:01:30 +0000194/// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
195Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
196 unsigned Align, IRBuilder<> &B) {
197 Module *M = Caller->getParent();
Chris Lattnerbf796322009-12-02 06:05:42 +0000198 const Type *Ty = TD->getIntPtrType(*Context);
199 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
200 Dst = CastToCStr(Dst, B);
201 Src = CastToCStr(Src, B);
Eric Christopher80bf1d52009-11-21 01:01:30 +0000202 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
Chris Lattnerbf796322009-12-02 06:05:42 +0000203 return B.CreateCall4(MemMove, Dst, Src, Len, A);
Eric Christopher80bf1d52009-11-21 01:01:30 +0000204}
205
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000206/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
207/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
208Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
Eric Christopher7a61d702008-08-08 19:39:37 +0000209 Value *Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000210 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000211 AttributeWithIndex AWI;
212 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
213
214 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
Eric Christopher37c8b862009-10-07 21:14:25 +0000215 Type::getInt8PtrTy(*Context),
216 Type::getInt8PtrTy(*Context),
217 Type::getInt32Ty(*Context),
218 TD->getIntPtrType(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000219 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000220 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
221
222 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
223 CI->setCallingConv(F->getCallingConv());
224
225 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000226}
227
Nick Lewycky13a09e22008-12-21 00:19:21 +0000228/// EmitMemCmp - Emit a call to the memcmp function.
229Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
230 Value *Len, IRBuilder<> &B) {
231 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000232 AttributeWithIndex AWI[3];
233 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
234 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
235 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
236 Attribute::NoUnwind);
237
238 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
Owen Anderson1d0be152009-08-13 21:58:54 +0000239 Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000240 Type::getInt8PtrTy(*Context),
241 Type::getInt8PtrTy(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +0000242 TD->getIntPtrType(*Context), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000243 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
244 Len, "memcmp");
245
246 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
247 CI->setCallingConv(F->getCallingConv());
248
249 return CI;
Nick Lewycky13a09e22008-12-21 00:19:21 +0000250}
251
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000252/// EmitMemSet - Emit a call to the memset function
253Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
254 Value *Len, IRBuilder<> &B) {
255 Module *M = Caller->getParent();
256 Intrinsic::ID IID = Intrinsic::memset;
257 const Type *Tys[1];
258 Tys[0] = Len->getType();
259 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
Owen Anderson1d0be152009-08-13 21:58:54 +0000260 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000261 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
262}
263
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000264/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
265/// 'floor'). This function is known to take a single of type matching 'Op' and
266/// returns one value with the same type. If 'Op' is a long double, 'l' is
267/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
268Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
Dan Gohman79cb8402009-09-25 23:10:17 +0000269 IRBuilder<> &B,
270 const AttrListPtr &Attrs) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000271 char NameBuffer[20];
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000272 if (!Op->getType()->isDoubleTy()) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000273 // If we need to add a suffix, copy into NameBuffer.
274 unsigned NameLen = strlen(Name);
275 assert(NameLen < sizeof(NameBuffer)-2);
276 memcpy(NameBuffer, Name, NameLen);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000277 if (Op->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000278 NameBuffer[NameLen] = 'f'; // floorf
279 else
280 NameBuffer[NameLen] = 'l'; // floorl
281 NameBuffer[NameLen+1] = 0;
282 Name = NameBuffer;
283 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000284
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000285 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000286 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000287 Op->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000288 CallInst *CI = B.CreateCall(Callee, Op, Name);
Dan Gohman79cb8402009-09-25 23:10:17 +0000289 CI->setAttributes(Attrs);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000290 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
291 CI->setCallingConv(F->getCallingConv());
292
293 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000294}
295
296/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
297/// is an integer.
Chris Lattner74965f22009-11-09 04:57:04 +0000298Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000299 Module *M = Caller->getParent();
Owen Anderson1d0be152009-08-13 21:58:54 +0000300 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
301 Type::getInt32Ty(*Context), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000302 CallInst *CI = B.CreateCall(PutChar,
Eric Christopher37c8b862009-10-07 21:14:25 +0000303 B.CreateIntCast(Char,
304 Type::getInt32Ty(*Context),
Duncan Sandsf63c4102009-11-16 12:32:28 +0000305 /*isSigned*/true,
Eric Christopher37c8b862009-10-07 21:14:25 +0000306 "chari"),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000307 "putchar");
308
309 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
310 CI->setCallingConv(F->getCallingConv());
Chris Lattner74965f22009-11-09 04:57:04 +0000311 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000312}
313
314/// EmitPutS - Emit a call to the puts function. This assumes that Str is
315/// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000316void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000317 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000318 AttributeWithIndex AWI[2];
319 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
320 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
321
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000322 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
Owen Anderson1d0be152009-08-13 21:58:54 +0000323 Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000324 Type::getInt8PtrTy(*Context),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000325 NULL);
326 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
327 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
328 CI->setCallingConv(F->getCallingConv());
329
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000330}
331
332/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
333/// an integer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000334void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000335 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000336 AttributeWithIndex AWI[2];
337 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
338 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
339 Constant *F;
340 if (isa<PointerType>(File->getType()))
Eric Christopher37c8b862009-10-07 21:14:25 +0000341 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
342 Type::getInt32Ty(*Context),
343 Type::getInt32Ty(*Context), File->getType(),
344 NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000345 else
Eric Christopher37c8b862009-10-07 21:14:25 +0000346 F = M->getOrInsertFunction("fputc",
347 Type::getInt32Ty(*Context),
348 Type::getInt32Ty(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000349 File->getType(), NULL);
Duncan Sandsf63c4102009-11-16 12:32:28 +0000350 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
351 "chari");
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000352 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
353
354 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
355 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000356}
357
358/// EmitFPutS - Emit a call to the puts function. Str is required to be a
359/// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000360void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000361 Module *M = Caller->getParent();
Nick Lewycky225f7472009-02-15 22:47:25 +0000362 AttributeWithIndex AWI[3];
363 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
364 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
365 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000366 Constant *F;
367 if (isa<PointerType>(File->getType()))
Eric Christopher37c8b862009-10-07 21:14:25 +0000368 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
369 Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000370 Type::getInt8PtrTy(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000371 File->getType(), NULL);
372 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000373 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000374 Type::getInt8PtrTy(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000375 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000376 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
377
378 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
379 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000380}
381
382/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
383/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
384void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
Eric Christopher7a61d702008-08-08 19:39:37 +0000385 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000386 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000387 AttributeWithIndex AWI[3];
388 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
389 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
390 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
391 Constant *F;
392 if (isa<PointerType>(File->getType()))
393 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
Owen Anderson1d0be152009-08-13 21:58:54 +0000394 TD->getIntPtrType(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000395 Type::getInt8PtrTy(*Context),
Eric Christopher37c8b862009-10-07 21:14:25 +0000396 TD->getIntPtrType(*Context),
397 TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000398 File->getType(), NULL);
399 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000400 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000401 Type::getInt8PtrTy(*Context),
Eric Christopher37c8b862009-10-07 21:14:25 +0000402 TD->getIntPtrType(*Context),
403 TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000404 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000405 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
Owen Anderson1d0be152009-08-13 21:58:54 +0000406 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000407
408 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
409 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000410}
411
412//===----------------------------------------------------------------------===//
413// Helper Functions
414//===----------------------------------------------------------------------===//
415
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000416/// GetStringLengthH - If we can compute the length of the string pointed to by
417/// the specified pointer, return 'len+1'. If we can't, return 0.
418static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
419 // Look through noop bitcast instructions.
420 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
421 return GetStringLengthH(BCI->getOperand(0), PHIs);
Eric Christopher37c8b862009-10-07 21:14:25 +0000422
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000423 // If this is a PHI node, there are two cases: either we have already seen it
424 // or we haven't.
425 if (PHINode *PN = dyn_cast<PHINode>(V)) {
426 if (!PHIs.insert(PN))
427 return ~0ULL; // already in the set.
Eric Christopher37c8b862009-10-07 21:14:25 +0000428
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000429 // If it was new, see if all the input strings are the same length.
430 uint64_t LenSoFar = ~0ULL;
431 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
432 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
433 if (Len == 0) return 0; // Unknown length -> unknown.
Eric Christopher37c8b862009-10-07 21:14:25 +0000434
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000435 if (Len == ~0ULL) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +0000436
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000437 if (Len != LenSoFar && LenSoFar != ~0ULL)
438 return 0; // Disagree -> unknown.
439 LenSoFar = Len;
440 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000441
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000442 // Success, all agree.
443 return LenSoFar;
444 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000445
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000446 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
447 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
448 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
449 if (Len1 == 0) return 0;
450 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
451 if (Len2 == 0) return 0;
452 if (Len1 == ~0ULL) return Len2;
453 if (Len2 == ~0ULL) return Len1;
454 if (Len1 != Len2) return 0;
455 return Len1;
456 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000457
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000458 // If the value is not a GEP instruction nor a constant expression with a
459 // GEP instruction, then return unknown.
460 User *GEP = 0;
461 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
462 GEP = GEPI;
463 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
464 if (CE->getOpcode() != Instruction::GetElementPtr)
465 return 0;
466 GEP = CE;
467 } else {
468 return 0;
469 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000470
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000471 // Make sure the GEP has exactly three arguments.
472 if (GEP->getNumOperands() != 3)
473 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000474
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000475 // Check to make sure that the first operand of the GEP is an integer and
476 // has value 0 so that we are sure we're indexing into the initializer.
477 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
478 if (!Idx->isZero())
479 return 0;
480 } else
481 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000482
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000483 // If the second index isn't a ConstantInt, then this is a variable index
484 // into the array. If this occurs, we can't say anything meaningful about
485 // the string.
486 uint64_t StartIdx = 0;
487 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
488 StartIdx = CI->getZExtValue();
489 else
490 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000491
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000492 // The GEP instruction, constant or instruction, must reference a global
493 // variable that is a constant and is initialized. The referenced constant
494 // initializer is the array that we'll use for optimization.
495 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
Dan Gohman107f41f2009-08-19 00:11:12 +0000496 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
497 GV->mayBeOverridden())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000498 return 0;
499 Constant *GlobalInit = GV->getInitializer();
Eric Christopher37c8b862009-10-07 21:14:25 +0000500
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000501 // Handle the ConstantAggregateZero case, which is a degenerate case. The
502 // initializer is constant zero so the length of the string must be zero.
503 if (isa<ConstantAggregateZero>(GlobalInit))
504 return 1; // Len = 0 offset by 1.
Eric Christopher37c8b862009-10-07 21:14:25 +0000505
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000506 // Must be a Constant Array
507 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Owen Anderson1d0be152009-08-13 21:58:54 +0000508 if (!Array ||
509 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000510 return false;
Eric Christopher37c8b862009-10-07 21:14:25 +0000511
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000512 // Get the number of elements in the array
513 uint64_t NumElts = Array->getType()->getNumElements();
Eric Christopher37c8b862009-10-07 21:14:25 +0000514
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000515 // Traverse the constant array from StartIdx (derived above) which is
516 // the place the GEP refers to in the array.
517 for (unsigned i = StartIdx; i != NumElts; ++i) {
518 Constant *Elt = Array->getOperand(i);
519 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
520 if (!CI) // This array isn't suitable, non-int initializer.
521 return 0;
522 if (CI->isZero())
523 return i-StartIdx+1; // We found end of string, success!
524 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000525
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000526 return 0; // The array isn't null terminated, conservatively return 'unknown'.
527}
528
529/// GetStringLength - If we can compute the length of the string pointed to by
530/// the specified pointer, return 'len+1'. If we can't, return 0.
531static uint64_t GetStringLength(Value *V) {
532 if (!isa<PointerType>(V->getType())) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000533
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000534 SmallPtrSet<PHINode*, 32> PHIs;
535 uint64_t Len = GetStringLengthH(V, PHIs);
536 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
537 // an empty string as a length.
538 return Len == ~0ULL ? 1 : Len;
539}
540
541/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
Eric Christopher37c8b862009-10-07 21:14:25 +0000542/// value is equal or not-equal to zero.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000543static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
544 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
545 UI != E; ++UI) {
546 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
547 if (IC->isEquality())
548 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
549 if (C->isNullValue())
550 continue;
551 // Unknown instruction.
552 return false;
553 }
554 return true;
555}
556
557//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000558// String and Memory LibCall Optimizations
559//===----------------------------------------------------------------------===//
560
561//===---------------------------------------===//
562// 'strcat' Optimizations
Chris Lattnere9f9a7e2009-09-03 05:19:59 +0000563namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000564struct StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000565 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000566 // Verify the "strcat" function prototype.
567 const FunctionType *FT = Callee->getFunctionType();
568 if (FT->getNumParams() != 2 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000569 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000570 FT->getParamType(0) != FT->getReturnType() ||
571 FT->getParamType(1) != FT->getReturnType())
572 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000573
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000574 // Extract some information from the instruction
575 Value *Dst = CI->getOperand(1);
576 Value *Src = CI->getOperand(2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000577
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000578 // See if we can get the length of the input string.
579 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000580 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000581 --Len; // Unbias length.
Eric Christopher37c8b862009-10-07 21:14:25 +0000582
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000583 // Handle the simple, do-nothing case: strcat(x, "") -> x
584 if (Len == 0)
585 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000586
587 // These optimizations require TargetData.
588 if (!TD) return 0;
589
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000590 EmitStrLenMemCpy(Src, Dst, Len, B);
591 return Dst;
592 }
593
594 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000595 // We need to find the end of the destination string. That's where the
596 // memory is to be moved to. We just generate a call to strlen.
597 Value *DstLen = EmitStrLen(Dst, B);
Eric Christopher37c8b862009-10-07 21:14:25 +0000598
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000599 // Now that we have the destination's length, we must index into the
600 // destination's pointer to get the actual memcpy destination (end of
601 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000602 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Eric Christopher37c8b862009-10-07 21:14:25 +0000603
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000604 // We have enough information to now generate the memcpy call to do the
605 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000606 EmitMemCpy(CpyDst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000607 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000608 }
609};
610
611//===---------------------------------------===//
612// 'strncat' Optimizations
613
Chris Lattner3e8b6632009-09-02 06:11:42 +0000614struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000615 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
616 // Verify the "strncat" function prototype.
617 const FunctionType *FT = Callee->getFunctionType();
618 if (FT->getNumParams() != 3 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000619 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000620 FT->getParamType(0) != FT->getReturnType() ||
621 FT->getParamType(1) != FT->getReturnType() ||
622 !isa<IntegerType>(FT->getParamType(2)))
623 return 0;
624
625 // Extract some information from the instruction
626 Value *Dst = CI->getOperand(1);
627 Value *Src = CI->getOperand(2);
628 uint64_t Len;
629
630 // We don't do anything if length is not constant
631 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
632 Len = LengthArg->getZExtValue();
633 else
634 return 0;
635
636 // See if we can get the length of the input string.
637 uint64_t SrcLen = GetStringLength(Src);
638 if (SrcLen == 0) return 0;
639 --SrcLen; // Unbias length.
640
641 // Handle the simple, do-nothing cases:
642 // strncat(x, "", c) -> x
643 // strncat(x, c, 0) -> x
644 if (SrcLen == 0 || Len == 0) return Dst;
645
Dan Gohmanf14d9192009-08-18 00:48:13 +0000646 // These optimizations require TargetData.
647 if (!TD) return 0;
648
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000649 // We don't optimize this case
650 if (Len < SrcLen) return 0;
651
652 // strncat(x, s, c) -> strcat(x, s)
653 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000654 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000655 return Dst;
656 }
657};
658
659//===---------------------------------------===//
660// 'strchr' Optimizations
661
Chris Lattner3e8b6632009-09-02 06:11:42 +0000662struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000663 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000664 // Verify the "strchr" function prototype.
665 const FunctionType *FT = Callee->getFunctionType();
666 if (FT->getNumParams() != 2 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000667 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000668 FT->getParamType(0) != FT->getReturnType())
669 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000670
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000671 Value *SrcStr = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +0000672
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000673 // If the second operand is non-constant, see if we can compute the length
674 // of the input string and turn this into memchr.
675 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
676 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000677 // These optimizations require TargetData.
678 if (!TD) return 0;
679
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000680 uint64_t Len = GetStringLength(SrcStr);
Chris Lattnercf0fe8d2009-10-05 05:54:46 +0000681 if (Len == 0 ||
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000682 FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs
683 // i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000684 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000685
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000686 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
Owen Anderson1d0be152009-08-13 21:58:54 +0000687 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000688 }
689
690 // Otherwise, the character is a constant, see if the first argument is
691 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000692 std::string Str;
693 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000694 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000695
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000696 // strchr can find the nul character.
697 Str += '\0';
698 char CharValue = CharC->getSExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +0000699
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000700 // Compute the offset.
701 uint64_t i = 0;
702 while (1) {
703 if (i == Str.size()) // Didn't find the char. strchr returns null.
Owen Andersona7235ea2009-07-31 20:28:14 +0000704 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000705 // Did we find our match?
706 if (Str[i] == CharValue)
707 break;
708 ++i;
709 }
Eric Christopher37c8b862009-10-07 21:14:25 +0000710
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000711 // strchr(s+n,c) -> gep(s+n+i,c)
Owen Anderson1d0be152009-08-13 21:58:54 +0000712 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000713 return B.CreateGEP(SrcStr, Idx, "strchr");
714 }
715};
716
717//===---------------------------------------===//
718// 'strcmp' Optimizations
719
Chris Lattner3e8b6632009-09-02 06:11:42 +0000720struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000721 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000722 // Verify the "strcmp" function prototype.
723 const FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000724 if (FT->getNumParams() != 2 ||
725 FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000726 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000727 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000728 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000729
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000730 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
731 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000732 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000733
Bill Wendling0582ae92009-03-13 04:39:26 +0000734 std::string Str1, Str2;
735 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
736 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000737
Bill Wendling0582ae92009-03-13 04:39:26 +0000738 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000739 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000740
Bill Wendling0582ae92009-03-13 04:39:26 +0000741 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000742 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000743
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000744 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000745 if (HasStr1 && HasStr2)
Eric Christopher37c8b862009-10-07 21:14:25 +0000746 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000747 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000748
749 // strcmp(P, "x") -> memcmp(P, "x", 2)
750 uint64_t Len1 = GetStringLength(Str1P);
751 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000752 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000753 // These optimizations require TargetData.
754 if (!TD) return 0;
755
Nick Lewycky13a09e22008-12-21 00:19:21 +0000756 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000757 ConstantInt::get(TD->getIntPtrType(*Context),
Chris Lattner849832c2009-06-19 04:17:36 +0000758 std::min(Len1, Len2)), B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000759 }
760
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000761 return 0;
762 }
763};
764
765//===---------------------------------------===//
766// 'strncmp' Optimizations
767
Chris Lattner3e8b6632009-09-02 06:11:42 +0000768struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000769 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000770 // Verify the "strncmp" function prototype.
771 const FunctionType *FT = Callee->getFunctionType();
Eric Christopher37c8b862009-10-07 21:14:25 +0000772 if (FT->getNumParams() != 3 ||
773 FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000774 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000775 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000776 !isa<IntegerType>(FT->getParamType(2)))
777 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000778
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000779 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
780 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000781 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000782
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000783 // Get the length argument if it is constant.
784 uint64_t Length;
785 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
786 Length = LengthArg->getZExtValue();
787 else
788 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000789
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000790 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000791 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +0000792
Bill Wendling0582ae92009-03-13 04:39:26 +0000793 std::string Str1, Str2;
794 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
795 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
Eric Christopher37c8b862009-10-07 21:14:25 +0000796
Bill Wendling0582ae92009-03-13 04:39:26 +0000797 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000798 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000799
Bill Wendling0582ae92009-03-13 04:39:26 +0000800 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000801 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
Eric Christopher37c8b862009-10-07 21:14:25 +0000802
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000803 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000804 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000805 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000806 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000807 return 0;
808 }
809};
810
811
812//===---------------------------------------===//
813// 'strcpy' Optimizations
814
Chris Lattner3e8b6632009-09-02 06:11:42 +0000815struct StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000816 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000817 // Verify the "strcpy" function prototype.
818 const FunctionType *FT = Callee->getFunctionType();
819 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
820 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000821 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000822 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000823
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000824 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
825 if (Dst == Src) // strcpy(x,x) -> x
826 return Src;
Eric Christopher37c8b862009-10-07 21:14:25 +0000827
Dan Gohmanf14d9192009-08-18 00:48:13 +0000828 // These optimizations require TargetData.
829 if (!TD) return 0;
830
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000831 // See if we can get the length of the input string.
832 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000833 if (Len == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000834
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000835 // We have enough information to now generate the memcpy call to do the
836 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000837 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000838 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000839 return Dst;
840 }
841};
842
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000843//===---------------------------------------===//
844// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000845
Chris Lattner3e8b6632009-09-02 06:11:42 +0000846struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000847 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
848 const FunctionType *FT = Callee->getFunctionType();
849 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
850 FT->getParamType(0) != FT->getParamType(1) ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000851 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000852 !isa<IntegerType>(FT->getParamType(2)))
853 return 0;
854
855 Value *Dst = CI->getOperand(1);
856 Value *Src = CI->getOperand(2);
857 Value *LenOp = CI->getOperand(3);
858
859 // See if we can get the length of the input string.
860 uint64_t SrcLen = GetStringLength(Src);
861 if (SrcLen == 0) return 0;
862 --SrcLen;
863
864 if (SrcLen == 0) {
865 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Eric Christopher37c8b862009-10-07 21:14:25 +0000866 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
867 B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000868 return Dst;
869 }
870
871 uint64_t Len;
872 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
873 Len = LengthArg->getZExtValue();
874 else
875 return 0;
876
877 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
878
Dan Gohmanf14d9192009-08-18 00:48:13 +0000879 // These optimizations require TargetData.
880 if (!TD) return 0;
881
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000882 // Let strncpy handle the zero padding
883 if (Len > SrcLen+1) return 0;
884
885 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000886 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000887 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000888
889 return Dst;
890 }
891};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000892
893//===---------------------------------------===//
894// 'strlen' Optimizations
895
Chris Lattner3e8b6632009-09-02 06:11:42 +0000896struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000897 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000898 const FunctionType *FT = Callee->getFunctionType();
899 if (FT->getNumParams() != 1 ||
Duncan Sandsac53a0b2009-10-06 15:40:36 +0000900 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000901 !isa<IntegerType>(FT->getReturnType()))
902 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +0000903
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000904 Value *Src = CI->getOperand(1);
905
906 // Constant folding: strlen("xyz") -> 3
907 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000908 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000909
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000910 // strlen(x) != 0 --> *x != 0
911 // strlen(x) == 0 --> *x == 0
Chris Lattner98d67d72009-12-23 23:24:51 +0000912 if (IsOnlyUsedInZeroEqualityComparison(CI))
913 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
914 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000915 }
916};
917
918//===---------------------------------------===//
Chris Lattner24604112009-12-16 09:32:05 +0000919// 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
Nick Lewycky4c498412009-02-13 15:31:46 +0000920
Chris Lattner3e8b6632009-09-02 06:11:42 +0000921struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000922 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
923 const FunctionType *FT = Callee->getFunctionType();
924 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
925 !isa<PointerType>(FT->getParamType(0)) ||
926 !isa<PointerType>(FT->getParamType(1)))
927 return 0;
928
929 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000930 if (isa<ConstantPointerNull>(EndPtr)) {
931 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000932 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000933 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000934
935 return 0;
936 }
937};
938
Chris Lattner24604112009-12-16 09:32:05 +0000939//===---------------------------------------===//
940// 'strstr' Optimizations
941
942struct StrStrOpt : public LibCallOptimization {
943 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
944 const FunctionType *FT = Callee->getFunctionType();
945 if (FT->getNumParams() != 2 ||
946 !isa<PointerType>(FT->getParamType(0)) ||
947 !isa<PointerType>(FT->getParamType(1)) ||
948 !isa<PointerType>(FT->getReturnType()))
949 return 0;
950
951 // fold strstr(x, x) -> x.
952 if (CI->getOperand(1) == CI->getOperand(2))
953 return B.CreateBitCast(CI->getOperand(1), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000954
Chris Lattner24604112009-12-16 09:32:05 +0000955 // See if either input string is a constant string.
956 std::string SearchStr, ToFindStr;
957 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
958 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000959
Chris Lattner24604112009-12-16 09:32:05 +0000960 // fold strstr(x, "") -> x.
961 if (HasStr2 && ToFindStr.empty())
962 return B.CreateBitCast(CI->getOperand(1), CI->getType());
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000963
Chris Lattner24604112009-12-16 09:32:05 +0000964 // If both strings are known, constant fold it.
965 if (HasStr1 && HasStr2) {
966 std::string::size_type Offset = SearchStr.find(ToFindStr);
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000967
Chris Lattner24604112009-12-16 09:32:05 +0000968 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
969 return Constant::getNullValue(CI->getType());
970
971 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
972 Value *Result = CastToCStr(CI->getOperand(1), B);
973 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
974 return B.CreateBitCast(Result, CI->getType());
975 }
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000976
Chris Lattner24604112009-12-16 09:32:05 +0000977 // fold strstr(x, "y") -> strchr(x, 'y').
978 if (HasStr2 && ToFindStr.size() == 1)
979 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
980 CI->getType());
981 return 0;
982 }
983};
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +0000984
Nick Lewycky4c498412009-02-13 15:31:46 +0000985
986//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000987// 'memcmp' Optimizations
988
Chris Lattner3e8b6632009-09-02 06:11:42 +0000989struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000990 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000991 const FunctionType *FT = Callee->getFunctionType();
992 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
993 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000994 FT->getReturnType() != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000995 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000996
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000997 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000998
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000999 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001000 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001001
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001002 // Make sure we have a constant length.
1003 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001004 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001005 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001006
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001007 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00001008 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001009
1010 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1011 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1012 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +00001013 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001014 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +00001015
Benjamin Kramer992a6372009-11-05 17:44:22 +00001016 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1017 std::string LHSStr, RHSStr;
1018 if (GetConstantStringInfo(LHS, LHSStr) &&
1019 GetConstantStringInfo(RHS, RHSStr)) {
1020 // Make sure we're not reading out-of-bounds memory.
1021 if (Len > LHSStr.length() || Len > RHSStr.length())
1022 return 0;
1023 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1024 return ConstantInt::get(CI->getType(), Ret);
1025 }
1026
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001027 return 0;
1028 }
1029};
1030
1031//===---------------------------------------===//
1032// 'memcpy' Optimizations
1033
Chris Lattner3e8b6632009-09-02 06:11:42 +00001034struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001035 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001036 // These optimizations require TargetData.
1037 if (!TD) return 0;
1038
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001039 const FunctionType *FT = Callee->getFunctionType();
1040 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1041 !isa<PointerType>(FT->getParamType(0)) ||
1042 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001043 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001044 return 0;
1045
1046 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1047 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1048 return CI->getOperand(1);
1049 }
1050};
1051
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001052//===---------------------------------------===//
1053// 'memmove' Optimizations
1054
Chris Lattner3e8b6632009-09-02 06:11:42 +00001055struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001056 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001057 // These optimizations require TargetData.
1058 if (!TD) return 0;
1059
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001060 const FunctionType *FT = Callee->getFunctionType();
1061 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1062 !isa<PointerType>(FT->getParamType(0)) ||
1063 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001064 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001065 return 0;
1066
1067 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
Eric Christopher80bf1d52009-11-21 01:01:30 +00001068 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001069 return CI->getOperand(1);
1070 }
1071};
1072
1073//===---------------------------------------===//
1074// 'memset' Optimizations
1075
Chris Lattner3e8b6632009-09-02 06:11:42 +00001076struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001077 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001078 // These optimizations require TargetData.
1079 if (!TD) return 0;
1080
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001081 const FunctionType *FT = Callee->getFunctionType();
1082 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1083 !isa<PointerType>(FT->getParamType(0)) ||
Eli Friedman62bb4132009-07-18 08:34:51 +00001084 !isa<IntegerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001085 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001086 return 0;
1087
1088 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Eric Christopher37c8b862009-10-07 21:14:25 +00001089 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1090 false);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001091 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001092 return CI->getOperand(1);
1093 }
1094};
1095
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001096//===----------------------------------------------------------------------===//
Eric Christopher80bf1d52009-11-21 01:01:30 +00001097// Object Size Checking Optimizations
1098//===----------------------------------------------------------------------===//
1099
1100//===---------------------------------------===//
1101// 'object size'
1102namespace {
1103struct SizeOpt : public LibCallOptimization {
1104 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1105 // TODO: We can do more with this, but delaying to here should be no change
1106 // in behavior.
1107 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
1108
1109 if (!Const) return 0;
1110
1111 const Type *Ty = Callee->getFunctionType()->getReturnType();
1112
Eric Christopherd060b252009-12-23 02:51:48 +00001113 if (Const->getZExtValue() == 0)
Eric Christopher80bf1d52009-11-21 01:01:30 +00001114 return Constant::getAllOnesValue(Ty);
1115 else
1116 return ConstantInt::get(Ty, 0);
1117 }
1118};
1119}
1120
1121//===---------------------------------------===//
1122// 'memcpy_chk' Optimizations
1123
1124struct MemCpyChkOpt : public LibCallOptimization {
1125 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1126 // These optimizations require TargetData.
1127 if (!TD) return 0;
1128
1129 const FunctionType *FT = Callee->getFunctionType();
1130 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1131 !isa<PointerType>(FT->getParamType(0)) ||
1132 !isa<PointerType>(FT->getParamType(1)) ||
Eric Christopherf734be22009-12-22 01:23:51 +00001133 !isa<IntegerType>(FT->getParamType(3)) ||
1134 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eric Christopher80bf1d52009-11-21 01:01:30 +00001135 return 0;
1136
1137 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1138 if (!SizeCI)
1139 return 0;
1140 if (SizeCI->isAllOnesValue()) {
1141 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1142 return CI->getOperand(1);
1143 }
1144
1145 return 0;
1146 }
1147};
1148
1149//===---------------------------------------===//
1150// 'memset_chk' Optimizations
1151
1152struct MemSetChkOpt : public LibCallOptimization {
1153 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1154 // These optimizations require TargetData.
1155 if (!TD) return 0;
1156
1157 const FunctionType *FT = Callee->getFunctionType();
1158 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1159 !isa<PointerType>(FT->getParamType(0)) ||
1160 !isa<IntegerType>(FT->getParamType(1)) ||
Eric Christopherf734be22009-12-22 01:23:51 +00001161 !isa<IntegerType>(FT->getParamType(3)) ||
Eric Christopher80bf1d52009-11-21 01:01:30 +00001162 FT->getParamType(2) != TD->getIntPtrType(*Context))
1163 return 0;
1164
1165 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1166 if (!SizeCI)
1167 return 0;
1168 if (SizeCI->isAllOnesValue()) {
1169 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1170 false);
1171 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1172 return CI->getOperand(1);
1173 }
1174
1175 return 0;
1176 }
1177};
1178
1179//===---------------------------------------===//
1180// 'memmove_chk' Optimizations
1181
1182struct MemMoveChkOpt : public LibCallOptimization {
1183 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1184 // These optimizations require TargetData.
1185 if (!TD) return 0;
1186
1187 const FunctionType *FT = Callee->getFunctionType();
1188 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1189 !isa<PointerType>(FT->getParamType(0)) ||
1190 !isa<PointerType>(FT->getParamType(1)) ||
Eric Christopherf734be22009-12-22 01:23:51 +00001191 !isa<IntegerType>(FT->getParamType(3)) ||
Eric Christopher80bf1d52009-11-21 01:01:30 +00001192 FT->getParamType(2) != TD->getIntPtrType(*Context))
1193 return 0;
1194
1195 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1196 if (!SizeCI)
1197 return 0;
1198 if (SizeCI->isAllOnesValue()) {
1199 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1200 1, B);
1201 return CI->getOperand(1);
1202 }
1203
1204 return 0;
1205 }
1206};
1207
1208//===----------------------------------------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001209// Math Library Optimizations
1210//===----------------------------------------------------------------------===//
1211
1212//===---------------------------------------===//
1213// 'pow*' Optimizations
1214
Chris Lattner3e8b6632009-09-02 06:11:42 +00001215struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001216 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001217 const FunctionType *FT = Callee->getFunctionType();
1218 // Just make sure this has 2 arguments of the same FP type, which match the
1219 // result type.
1220 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1221 FT->getParamType(0) != FT->getParamType(1) ||
1222 !FT->getParamType(0)->isFloatingPoint())
1223 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001224
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001225 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1226 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1227 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1228 return Op1C;
1229 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
Dan Gohman76926b62009-09-26 18:10:13 +00001230 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001231 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001232
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001233 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1234 if (Op2C == 0) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001235
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001236 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001237 return ConstantFP::get(CI->getType(), 1.0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001238
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001239 if (Op2C->isExactlyValue(0.5)) {
Dan Gohman79cb8402009-09-25 23:10:17 +00001240 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1241 // This is faster than calling pow, and still handles negative zero
1242 // and negative infinite correctly.
1243 // TODO: In fast-math mode, this could be just sqrt(x).
1244 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
Dan Gohmana23643d2009-09-25 23:40:21 +00001245 Value *Inf = ConstantFP::getInfinity(CI->getType());
1246 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
Dan Gohman76926b62009-09-26 18:10:13 +00001247 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1248 Callee->getAttributes());
1249 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1250 Callee->getAttributes());
Dan Gohman79cb8402009-09-25 23:10:17 +00001251 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1252 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1253 return Sel;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001254 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001255
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001256 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1257 return Op1;
1258 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001259 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001260 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001261 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001262 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001263 return 0;
1264 }
1265};
1266
1267//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001268// 'exp2' Optimizations
1269
Chris Lattner3e8b6632009-09-02 06:11:42 +00001270struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001271 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001272 const FunctionType *FT = Callee->getFunctionType();
1273 // Just make sure this has 1 argument of FP type, which matches the
1274 // result type.
1275 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1276 !FT->getParamType(0)->isFloatingPoint())
1277 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001278
Chris Lattnere818f772008-05-02 18:43:35 +00001279 Value *Op = CI->getOperand(1);
1280 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1281 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1282 Value *LdExpArg = 0;
1283 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1284 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Eric Christopher37c8b862009-10-07 21:14:25 +00001285 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1286 Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001287 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1288 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Eric Christopher37c8b862009-10-07 21:14:25 +00001289 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1290 Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001291 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001292
Chris Lattnere818f772008-05-02 18:43:35 +00001293 if (LdExpArg) {
1294 const char *Name;
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001295 if (Op->getType()->isFloatTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001296 Name = "ldexpf";
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001297 else if (Op->getType()->isDoubleTy())
Chris Lattnere818f772008-05-02 18:43:35 +00001298 Name = "ldexp";
1299 else
1300 Name = "ldexpl";
1301
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001302 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001303 if (!Op->getType()->isFloatTy())
Owen Andersonbaf3c402009-07-29 18:55:55 +00001304 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001305
1306 Module *M = Caller->getParent();
1307 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Eric Christopher37c8b862009-10-07 21:14:25 +00001308 Op->getType(),
1309 Type::getInt32Ty(*Context),NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001310 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1311 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1312 CI->setCallingConv(F->getCallingConv());
1313
1314 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001315 }
1316 return 0;
1317 }
1318};
Chris Lattnere818f772008-05-02 18:43:35 +00001319
1320//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001321// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1322
Chris Lattner3e8b6632009-09-02 06:11:42 +00001323struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001324 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001325 const FunctionType *FT = Callee->getFunctionType();
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001326 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1327 !FT->getParamType(0)->isDoubleTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001328 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001329
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001330 // If this is something like 'floor((double)floatval)', convert to floorf.
1331 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001332 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001333 return 0;
1334
1335 // floor((double)floatval) -> (double)floorf(floatval)
1336 Value *V = Cast->getOperand(0);
Dan Gohman76926b62009-09-26 18:10:13 +00001337 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1338 Callee->getAttributes());
Owen Anderson1d0be152009-08-13 21:58:54 +00001339 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001340 }
1341};
1342
1343//===----------------------------------------------------------------------===//
1344// Integer Optimizations
1345//===----------------------------------------------------------------------===//
1346
1347//===---------------------------------------===//
1348// 'ffs*' Optimizations
1349
Chris Lattner3e8b6632009-09-02 06:11:42 +00001350struct FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001351 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001352 const FunctionType *FT = Callee->getFunctionType();
1353 // Just make sure this has 2 arguments of the same FP type, which match the
1354 // result type.
Eric Christopher37c8b862009-10-07 21:14:25 +00001355 if (FT->getNumParams() != 1 ||
1356 FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001357 !isa<IntegerType>(FT->getParamType(0)))
1358 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001359
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001360 Value *Op = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001361
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001362 // Constant fold.
1363 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1364 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001365 return Constant::getNullValue(CI->getType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001366 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001367 CI->getValue().countTrailingZeros()+1);
1368 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001369
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001370 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1371 const Type *ArgType = Op->getType();
1372 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1373 Intrinsic::cttz, &ArgType, 1);
1374 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +00001375 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001376 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001377
Owen Andersona7235ea2009-07-31 20:28:14 +00001378 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001379 return B.CreateSelect(Cond, V,
1380 ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001381 }
1382};
1383
1384//===---------------------------------------===//
1385// 'isdigit' Optimizations
1386
Chris Lattner3e8b6632009-09-02 06:11:42 +00001387struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001388 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001389 const FunctionType *FT = Callee->getFunctionType();
1390 // We require integer(i32)
1391 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001392 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001393 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001394
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001395 // isdigit(c) -> (c-'0') <u 10
1396 Value *Op = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001397 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001398 "isdigittmp");
Eric Christopher37c8b862009-10-07 21:14:25 +00001399 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001400 "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001401 return B.CreateZExt(Op, CI->getType());
1402 }
1403};
1404
1405//===---------------------------------------===//
1406// 'isascii' Optimizations
1407
Chris Lattner3e8b6632009-09-02 06:11:42 +00001408struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001409 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001410 const FunctionType *FT = Callee->getFunctionType();
1411 // We require integer(i32)
1412 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001413 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001414 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001415
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001416 // isascii(c) -> c <u 128
1417 Value *Op = CI->getOperand(1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001418 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001419 "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001420 return B.CreateZExt(Op, CI->getType());
1421 }
1422};
Eric Christopher37c8b862009-10-07 21:14:25 +00001423
Chris Lattner313f0e62008-06-09 08:26:51 +00001424//===---------------------------------------===//
1425// 'abs', 'labs', 'llabs' Optimizations
1426
Chris Lattner3e8b6632009-09-02 06:11:42 +00001427struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001428 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001429 const FunctionType *FT = Callee->getFunctionType();
1430 // We require integer(integer) where the types agree.
1431 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1432 FT->getParamType(0) != FT->getReturnType())
1433 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001434
Chris Lattner313f0e62008-06-09 08:26:51 +00001435 // abs(x) -> x >s -1 ? x : -x
1436 Value *Op = CI->getOperand(1);
Eric Christopher37c8b862009-10-07 21:14:25 +00001437 Value *Pos = B.CreateICmpSGT(Op,
Owen Andersona7235ea2009-07-31 20:28:14 +00001438 Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001439 "ispos");
1440 Value *Neg = B.CreateNeg(Op, "neg");
1441 return B.CreateSelect(Pos, Op, Neg);
1442 }
1443};
Eric Christopher37c8b862009-10-07 21:14:25 +00001444
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001445
1446//===---------------------------------------===//
1447// 'toascii' Optimizations
1448
Chris Lattner3e8b6632009-09-02 06:11:42 +00001449struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001450 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001451 const FunctionType *FT = Callee->getFunctionType();
1452 // We require i32(i32)
1453 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001454 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001455 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001456
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001457 // isascii(c) -> c & 0x7f
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001458 return B.CreateAnd(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001459 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001460 }
1461};
1462
1463//===----------------------------------------------------------------------===//
1464// Formatting and IO Optimizations
1465//===----------------------------------------------------------------------===//
1466
1467//===---------------------------------------===//
1468// 'printf' Optimizations
1469
Chris Lattner3e8b6632009-09-02 06:11:42 +00001470struct PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001471 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001472 // Require one fixed pointer argument and an integer/void result.
1473 const FunctionType *FT = Callee->getFunctionType();
1474 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1475 !(isa<IntegerType>(FT->getReturnType()) ||
Chris Lattnercf0fe8d2009-10-05 05:54:46 +00001476 FT->getReturnType()->isVoidTy()))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001477 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001478
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001479 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001480 std::string FormatStr;
1481 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1482 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001483
1484 // Empty format string -> noop.
1485 if (FormatStr.empty()) // Tolerate printf's declared void.
Eric Christopher37c8b862009-10-07 21:14:25 +00001486 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001487 ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001488
Chris Lattner74965f22009-11-09 04:57:04 +00001489 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1490 // in case there is an error writing to stdout.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001491 if (FormatStr.size() == 1) {
Chris Lattner74965f22009-11-09 04:57:04 +00001492 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1493 FormatStr[0]), B);
1494 if (CI->use_empty()) return CI;
1495 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001496 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001497
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001498 // printf("foo\n") --> puts("foo")
1499 if (FormatStr[FormatStr.size()-1] == '\n' &&
1500 FormatStr.find('%') == std::string::npos) { // no format characters.
1501 // Create a string literal with no \n on it. We expect the constant merge
1502 // pass to be run after this pass, to merge duplicate strings.
1503 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001504 Constant *C = ConstantArray::get(*Context, FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001505 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1506 GlobalVariable::InternalLinkage, C, "str");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001507 EmitPutS(C, B);
Eric Christopher37c8b862009-10-07 21:14:25 +00001508 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001509 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001510 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001511
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001512 // Optimize specific format strings.
1513 // printf("%c", chr) --> putchar(*(i8*)dst)
1514 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1515 isa<IntegerType>(CI->getOperand(2)->getType())) {
Chris Lattner74965f22009-11-09 04:57:04 +00001516 Value *Res = EmitPutChar(CI->getOperand(2), B);
Eric Christopher80bf1d52009-11-21 01:01:30 +00001517
Chris Lattner74965f22009-11-09 04:57:04 +00001518 if (CI->use_empty()) return CI;
1519 return B.CreateIntCast(Res, CI->getType(), true);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001520 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001521
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001522 // printf("%s\n", str) --> puts(str)
1523 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1524 isa<PointerType>(CI->getOperand(2)->getType()) &&
1525 CI->use_empty()) {
1526 EmitPutS(CI->getOperand(2), B);
1527 return CI;
1528 }
1529 return 0;
1530 }
1531};
1532
1533//===---------------------------------------===//
1534// 'sprintf' Optimizations
1535
Chris Lattner3e8b6632009-09-02 06:11:42 +00001536struct SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001537 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001538 // Require two fixed pointer arguments and an integer result.
1539 const FunctionType *FT = Callee->getFunctionType();
1540 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1541 !isa<PointerType>(FT->getParamType(1)) ||
1542 !isa<IntegerType>(FT->getReturnType()))
1543 return 0;
1544
1545 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001546 std::string FormatStr;
1547 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1548 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001549
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001550 // If we just have a format string (nothing else crazy) transform it.
1551 if (CI->getNumOperands() == 3) {
1552 // Make sure there's no % in the constant array. We could try to handle
1553 // %% -> % in the future if we cared.
1554 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1555 if (FormatStr[i] == '%')
1556 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001557
1558 // These optimizations require TargetData.
1559 if (!TD) return 0;
1560
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001561 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1562 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001563 ConstantInt::get
1564 (TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001565 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001566 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001567
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001568 // The remaining optimizations require the format string to be "%s" or "%c"
1569 // and have an extra operand.
1570 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1571 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001572
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001573 // Decode the second character of the format string.
1574 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001575 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001576 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001577 Value *V = B.CreateTrunc(CI->getOperand(3),
1578 Type::getInt8Ty(*Context), "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001579 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1580 B.CreateStore(V, Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001581 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1582 "nul");
Owen Anderson1d0be152009-08-13 21:58:54 +00001583 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
Eric Christopher37c8b862009-10-07 21:14:25 +00001584
Owen Andersoneed707b2009-07-24 23:12:02 +00001585 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001586 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001587
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001588 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001589 // These optimizations require TargetData.
1590 if (!TD) return 0;
1591
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001592 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1593 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1594
1595 Value *Len = EmitStrLen(CI->getOperand(3), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001596 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001597 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001598 "leninc");
1599 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
Eric Christopher37c8b862009-10-07 21:14:25 +00001600
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001601 // The sprintf result is the unincremented number of bytes in the string.
1602 return B.CreateIntCast(Len, CI->getType(), false);
1603 }
1604 return 0;
1605 }
1606};
1607
1608//===---------------------------------------===//
1609// 'fwrite' Optimizations
1610
Chris Lattner3e8b6632009-09-02 06:11:42 +00001611struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001612 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001613 // Require a pointer, an integer, an integer, a pointer, returning integer.
1614 const FunctionType *FT = Callee->getFunctionType();
1615 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1616 !isa<IntegerType>(FT->getParamType(1)) ||
1617 !isa<IntegerType>(FT->getParamType(2)) ||
1618 !isa<PointerType>(FT->getParamType(3)) ||
1619 !isa<IntegerType>(FT->getReturnType()))
1620 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001621
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001622 // Get the element size and count.
1623 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1624 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1625 if (!SizeC || !CountC) return 0;
1626 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
Eric Christopher37c8b862009-10-07 21:14:25 +00001627
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001628 // If this is writing zero records, remove the call (it's a noop).
1629 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001630 return ConstantInt::get(CI->getType(), 0);
Eric Christopher37c8b862009-10-07 21:14:25 +00001631
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001632 // If this is writing one byte, turn it into fputc.
1633 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1634 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1635 EmitFPutC(Char, CI->getOperand(4), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001636 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001637 }
1638
1639 return 0;
1640 }
1641};
1642
1643//===---------------------------------------===//
1644// 'fputs' Optimizations
1645
Chris Lattner3e8b6632009-09-02 06:11:42 +00001646struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001647 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001648 // These optimizations require TargetData.
1649 if (!TD) return 0;
1650
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001651 // Require two pointers. Also, we can't optimize if return value is used.
1652 const FunctionType *FT = Callee->getFunctionType();
1653 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1654 !isa<PointerType>(FT->getParamType(1)) ||
1655 !CI->use_empty())
1656 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001657
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001658 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1659 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001660 if (!Len) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001661 EmitFWrite(CI->getOperand(1),
Owen Anderson1d0be152009-08-13 21:58:54 +00001662 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001663 CI->getOperand(2), B);
1664 return CI; // Known to have no uses (see above).
1665 }
1666};
1667
1668//===---------------------------------------===//
1669// 'fprintf' Optimizations
1670
Chris Lattner3e8b6632009-09-02 06:11:42 +00001671struct FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001672 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001673 // Require two fixed paramters as pointers and integer result.
1674 const FunctionType *FT = Callee->getFunctionType();
1675 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1676 !isa<PointerType>(FT->getParamType(1)) ||
1677 !isa<IntegerType>(FT->getReturnType()))
1678 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001679
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001680 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001681 std::string FormatStr;
1682 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1683 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001684
1685 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1686 if (CI->getNumOperands() == 3) {
1687 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1688 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001689 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001690
1691 // These optimizations require TargetData.
1692 if (!TD) return 0;
1693
Mikhail Glushenkoved5cb592010-01-04 07:55:25 +00001694 EmitFWrite(CI->getOperand(2),
1695 ConstantInt::get(TD->getIntPtrType(*Context),
1696 FormatStr.size()),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001697 CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001698 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001699 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001700
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001701 // The remaining optimizations require the format string to be "%s" or "%c"
1702 // and have an extra operand.
1703 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1704 return 0;
Eric Christopher37c8b862009-10-07 21:14:25 +00001705
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001706 // Decode the second character of the format string.
1707 if (FormatStr[1] == 'c') {
1708 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1709 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1710 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001711 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001712 }
Eric Christopher37c8b862009-10-07 21:14:25 +00001713
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001714 if (FormatStr[1] == 's') {
1715 // fprintf(F, "%s", str) -> fputs(str, F)
1716 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1717 return 0;
1718 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1719 return CI;
1720 }
1721 return 0;
1722 }
1723};
1724
Bill Wendlingac178222008-05-05 21:37:59 +00001725} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001726
1727//===----------------------------------------------------------------------===//
1728// SimplifyLibCalls Pass Implementation
1729//===----------------------------------------------------------------------===//
1730
1731namespace {
1732 /// This pass optimizes well known library functions from libc and libm.
1733 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001734 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001735 StringMap<LibCallOptimization*> Optimizations;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001736 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001737 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1738 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
Chris Lattner24604112009-12-16 09:32:05 +00001739 StrToOpt StrTo; StrStrOpt StrStr;
1740 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001741 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001742 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001743 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001744 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1745 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001746 // Formatting and IO Optimizations
1747 SPrintFOpt SPrintF; PrintFOpt PrintF;
1748 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Eric Christopher80bf1d52009-11-21 01:01:30 +00001749
1750 // Object Size Checking
Eric Christopher7b5e6172009-10-27 00:52:25 +00001751 SizeOpt ObjectSize;
Eric Christopher80bf1d52009-11-21 01:01:30 +00001752 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001753
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001754 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001755 public:
1756 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001757 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001758
1759 void InitOptimizations();
1760 bool runOnFunction(Function &F);
1761
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001762 void setDoesNotAccessMemory(Function &F);
1763 void setOnlyReadsMemory(Function &F);
1764 void setDoesNotThrow(Function &F);
1765 void setDoesNotCapture(Function &F, unsigned n);
1766 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001767 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001768
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001769 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001770 }
1771 };
1772 char SimplifyLibCalls::ID = 0;
1773} // end anonymous namespace.
1774
1775static RegisterPass<SimplifyLibCalls>
1776X("simplify-libcalls", "Simplify well-known library calls");
1777
1778// Public interface to the Simplify LibCalls pass.
1779FunctionPass *llvm::createSimplifyLibCallsPass() {
Eric Christopher37c8b862009-10-07 21:14:25 +00001780 return new SimplifyLibCalls();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001781}
1782
1783/// Optimizations - Populate the Optimizations map with all the optimizations
1784/// we know.
1785void SimplifyLibCalls::InitOptimizations() {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001786 // String and Memory LibCall Optimizations
1787 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001788 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001789 Optimizations["strchr"] = &StrChr;
1790 Optimizations["strcmp"] = &StrCmp;
1791 Optimizations["strncmp"] = &StrNCmp;
1792 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001793 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001794 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001795 Optimizations["strtol"] = &StrTo;
1796 Optimizations["strtod"] = &StrTo;
1797 Optimizations["strtof"] = &StrTo;
1798 Optimizations["strtoul"] = &StrTo;
1799 Optimizations["strtoll"] = &StrTo;
1800 Optimizations["strtold"] = &StrTo;
1801 Optimizations["strtoull"] = &StrTo;
Chris Lattner24604112009-12-16 09:32:05 +00001802 Optimizations["strstr"] = &StrStr;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001803 Optimizations["memcmp"] = &MemCmp;
1804 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001805 Optimizations["memmove"] = &MemMove;
1806 Optimizations["memset"] = &MemSet;
Eric Christopher37c8b862009-10-07 21:14:25 +00001807
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001808 // Math Library Optimizations
1809 Optimizations["powf"] = &Pow;
1810 Optimizations["pow"] = &Pow;
1811 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001812 Optimizations["llvm.pow.f32"] = &Pow;
1813 Optimizations["llvm.pow.f64"] = &Pow;
1814 Optimizations["llvm.pow.f80"] = &Pow;
1815 Optimizations["llvm.pow.f128"] = &Pow;
1816 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001817 Optimizations["exp2l"] = &Exp2;
1818 Optimizations["exp2"] = &Exp2;
1819 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001820 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1821 Optimizations["llvm.exp2.f128"] = &Exp2;
1822 Optimizations["llvm.exp2.f80"] = &Exp2;
1823 Optimizations["llvm.exp2.f64"] = &Exp2;
1824 Optimizations["llvm.exp2.f32"] = &Exp2;
Eric Christopher37c8b862009-10-07 21:14:25 +00001825
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001826#ifdef HAVE_FLOORF
1827 Optimizations["floor"] = &UnaryDoubleFP;
1828#endif
1829#ifdef HAVE_CEILF
1830 Optimizations["ceil"] = &UnaryDoubleFP;
1831#endif
1832#ifdef HAVE_ROUNDF
1833 Optimizations["round"] = &UnaryDoubleFP;
1834#endif
1835#ifdef HAVE_RINTF
1836 Optimizations["rint"] = &UnaryDoubleFP;
1837#endif
1838#ifdef HAVE_NEARBYINTF
1839 Optimizations["nearbyint"] = &UnaryDoubleFP;
1840#endif
Eric Christopher37c8b862009-10-07 21:14:25 +00001841
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001842 // Integer Optimizations
1843 Optimizations["ffs"] = &FFS;
1844 Optimizations["ffsl"] = &FFS;
1845 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001846 Optimizations["abs"] = &Abs;
1847 Optimizations["labs"] = &Abs;
1848 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001849 Optimizations["isdigit"] = &IsDigit;
1850 Optimizations["isascii"] = &IsAscii;
1851 Optimizations["toascii"] = &ToAscii;
Eric Christopher37c8b862009-10-07 21:14:25 +00001852
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001853 // Formatting and IO Optimizations
1854 Optimizations["sprintf"] = &SPrintF;
1855 Optimizations["printf"] = &PrintF;
1856 Optimizations["fwrite"] = &FWrite;
1857 Optimizations["fputs"] = &FPuts;
1858 Optimizations["fprintf"] = &FPrintF;
Eric Christopher80bf1d52009-11-21 01:01:30 +00001859
1860 // Object Size Checking
1861 Optimizations["llvm.objectsize.i32"] = &ObjectSize;
1862 Optimizations["llvm.objectsize.i64"] = &ObjectSize;
1863 Optimizations["__memcpy_chk"] = &MemCpyChk;
1864 Optimizations["__memset_chk"] = &MemSetChk;
1865 Optimizations["__memmove_chk"] = &MemMoveChk;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001866}
1867
1868
1869/// runOnFunction - Top level algorithm.
1870///
1871bool SimplifyLibCalls::runOnFunction(Function &F) {
1872 if (Optimizations.empty())
1873 InitOptimizations();
Eric Christopher37c8b862009-10-07 21:14:25 +00001874
Dan Gohmanf14d9192009-08-18 00:48:13 +00001875 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Eric Christopher37c8b862009-10-07 21:14:25 +00001876
Owen Andersone922c022009-07-22 00:24:57 +00001877 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001878
1879 bool Changed = false;
1880 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1881 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1882 // Ignore non-calls.
1883 CallInst *CI = dyn_cast<CallInst>(I++);
1884 if (!CI) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001885
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001886 // Ignore indirect calls and calls to non-external functions.
1887 Function *Callee = CI->getCalledFunction();
1888 if (Callee == 0 || !Callee->isDeclaration() ||
1889 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1890 continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001891
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001892 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001893 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1894 if (!LCO) continue;
Eric Christopher37c8b862009-10-07 21:14:25 +00001895
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001896 // Set the builder to the instruction after the call.
1897 Builder.SetInsertPoint(BB, I);
Eric Christopher37c8b862009-10-07 21:14:25 +00001898
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001899 // Try to optimize this call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001900 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001901 if (Result == 0) continue;
1902
David Greene6a6b90e2010-01-05 01:27:21 +00001903 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1904 dbgs() << " into: " << *Result << "\n");
Eric Christopher37c8b862009-10-07 21:14:25 +00001905
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001906 // Something changed!
1907 Changed = true;
1908 ++NumSimplified;
Eric Christopher37c8b862009-10-07 21:14:25 +00001909
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001910 // Inspect the instruction after the call (which was potentially just
1911 // added) next.
1912 I = CI; ++I;
Eric Christopher37c8b862009-10-07 21:14:25 +00001913
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001914 if (CI != Result && !CI->use_empty()) {
1915 CI->replaceAllUsesWith(Result);
1916 if (!Result->hasName())
1917 Result->takeName(CI);
1918 }
1919 CI->eraseFromParent();
1920 }
1921 }
1922 return Changed;
1923}
1924
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001925// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001926
1927void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1928 if (!F.doesNotAccessMemory()) {
1929 F.setDoesNotAccessMemory();
1930 ++NumAnnotated;
1931 Modified = true;
1932 }
1933}
1934void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1935 if (!F.onlyReadsMemory()) {
1936 F.setOnlyReadsMemory();
1937 ++NumAnnotated;
1938 Modified = true;
1939 }
1940}
1941void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1942 if (!F.doesNotThrow()) {
1943 F.setDoesNotThrow();
1944 ++NumAnnotated;
1945 Modified = true;
1946 }
1947}
1948void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1949 if (!F.doesNotCapture(n)) {
1950 F.setDoesNotCapture(n);
1951 ++NumAnnotated;
1952 Modified = true;
1953 }
1954}
1955void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1956 if (!F.doesNotAlias(n)) {
1957 F.setDoesNotAlias(n);
1958 ++NumAnnotated;
1959 Modified = true;
1960 }
1961}
1962
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001963/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001964///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001965bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001966 Modified = false;
1967 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1968 Function &F = *I;
1969 if (!F.isDeclaration())
1970 continue;
1971
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001972 if (!F.hasName())
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001973 continue;
1974
1975 const FunctionType *FTy = F.getFunctionType();
1976
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001977 StringRef Name = F.getName();
1978 switch (Name[0]) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001979 case 's':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001980 if (Name == "strlen") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001981 if (FTy->getNumParams() != 1 ||
1982 !isa<PointerType>(FTy->getParamType(0)))
1983 continue;
1984 setOnlyReadsMemory(F);
1985 setDoesNotThrow(F);
1986 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001987 } else if (Name == "strcpy" ||
1988 Name == "stpcpy" ||
1989 Name == "strcat" ||
1990 Name == "strtol" ||
1991 Name == "strtod" ||
1992 Name == "strtof" ||
1993 Name == "strtoul" ||
1994 Name == "strtoll" ||
1995 Name == "strtold" ||
1996 Name == "strncat" ||
1997 Name == "strncpy" ||
1998 Name == "strtoull") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001999 if (FTy->getNumParams() < 2 ||
2000 !isa<PointerType>(FTy->getParamType(1)))
2001 continue;
2002 setDoesNotThrow(F);
2003 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002004 } else if (Name == "strxfrm") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002005 if (FTy->getNumParams() != 3 ||
2006 !isa<PointerType>(FTy->getParamType(0)) ||
2007 !isa<PointerType>(FTy->getParamType(1)))
2008 continue;
2009 setDoesNotThrow(F);
2010 setDoesNotCapture(F, 1);
2011 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002012 } else if (Name == "strcmp" ||
2013 Name == "strspn" ||
2014 Name == "strncmp" ||
2015 Name ==" strcspn" ||
2016 Name == "strcoll" ||
2017 Name == "strcasecmp" ||
2018 Name == "strncasecmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002019 if (FTy->getNumParams() < 2 ||
2020 !isa<PointerType>(FTy->getParamType(0)) ||
2021 !isa<PointerType>(FTy->getParamType(1)))
2022 continue;
2023 setOnlyReadsMemory(F);
2024 setDoesNotThrow(F);
2025 setDoesNotCapture(F, 1);
2026 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002027 } else if (Name == "strstr" ||
2028 Name == "strpbrk") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002029 if (FTy->getNumParams() != 2 ||
2030 !isa<PointerType>(FTy->getParamType(1)))
2031 continue;
2032 setOnlyReadsMemory(F);
2033 setDoesNotThrow(F);
2034 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002035 } else if (Name == "strtok" ||
2036 Name == "strtok_r") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002037 if (FTy->getNumParams() < 2 ||
2038 !isa<PointerType>(FTy->getParamType(1)))
2039 continue;
2040 setDoesNotThrow(F);
2041 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002042 } else if (Name == "scanf" ||
2043 Name == "setbuf" ||
2044 Name == "setvbuf") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002045 if (FTy->getNumParams() < 1 ||
2046 !isa<PointerType>(FTy->getParamType(0)))
2047 continue;
2048 setDoesNotThrow(F);
2049 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002050 } else if (Name == "strdup" ||
2051 Name == "strndup") {
Nick Lewycky6cd0c042009-01-05 00:07:50 +00002052 if (FTy->getNumParams() < 1 ||
2053 !isa<PointerType>(FTy->getReturnType()) ||
2054 !isa<PointerType>(FTy->getParamType(0)))
2055 continue;
2056 setDoesNotThrow(F);
2057 setDoesNotAlias(F, 0);
2058 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002059 } else if (Name == "stat" ||
2060 Name == "sscanf" ||
2061 Name == "sprintf" ||
2062 Name == "statvfs") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002063 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002064 !isa<PointerType>(FTy->getParamType(0)) ||
2065 !isa<PointerType>(FTy->getParamType(1)))
2066 continue;
2067 setDoesNotThrow(F);
2068 setDoesNotCapture(F, 1);
2069 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002070 } else if (Name == "snprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002071 if (FTy->getNumParams() != 3 ||
2072 !isa<PointerType>(FTy->getParamType(0)) ||
2073 !isa<PointerType>(FTy->getParamType(2)))
2074 continue;
2075 setDoesNotThrow(F);
2076 setDoesNotCapture(F, 1);
2077 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002078 } else if (Name == "setitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002079 if (FTy->getNumParams() != 3 ||
2080 !isa<PointerType>(FTy->getParamType(1)) ||
2081 !isa<PointerType>(FTy->getParamType(2)))
2082 continue;
2083 setDoesNotThrow(F);
2084 setDoesNotCapture(F, 2);
2085 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002086 } else if (Name == "system") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002087 if (FTy->getNumParams() != 1 ||
2088 !isa<PointerType>(FTy->getParamType(0)))
2089 continue;
2090 // May throw; "system" is a valid pthread cancellation point.
2091 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002092 }
2093 break;
2094 case 'm':
Victor Hernandez83d63912009-09-18 22:35:49 +00002095 if (Name == "malloc") {
2096 if (FTy->getNumParams() != 1 ||
2097 !isa<PointerType>(FTy->getReturnType()))
2098 continue;
2099 setDoesNotThrow(F);
2100 setDoesNotAlias(F, 0);
2101 } else if (Name == "memcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002102 if (FTy->getNumParams() != 3 ||
2103 !isa<PointerType>(FTy->getParamType(0)) ||
2104 !isa<PointerType>(FTy->getParamType(1)))
2105 continue;
2106 setOnlyReadsMemory(F);
2107 setDoesNotThrow(F);
2108 setDoesNotCapture(F, 1);
2109 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002110 } else if (Name == "memchr" ||
2111 Name == "memrchr") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002112 if (FTy->getNumParams() != 3)
2113 continue;
2114 setOnlyReadsMemory(F);
2115 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002116 } else if (Name == "modf" ||
2117 Name == "modff" ||
2118 Name == "modfl" ||
2119 Name == "memcpy" ||
2120 Name == "memccpy" ||
2121 Name == "memmove") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002122 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002123 !isa<PointerType>(FTy->getParamType(1)))
2124 continue;
2125 setDoesNotThrow(F);
2126 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002127 } else if (Name == "memalign") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002128 if (!isa<PointerType>(FTy->getReturnType()))
2129 continue;
2130 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002131 } else if (Name == "mkdir" ||
2132 Name == "mktime") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002133 if (FTy->getNumParams() == 0 ||
2134 !isa<PointerType>(FTy->getParamType(0)))
2135 continue;
2136 setDoesNotThrow(F);
2137 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002138 }
2139 break;
2140 case 'r':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002141 if (Name == "realloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002142 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002143 !isa<PointerType>(FTy->getParamType(0)) ||
2144 !isa<PointerType>(FTy->getReturnType()))
2145 continue;
2146 setDoesNotThrow(F);
2147 setDoesNotAlias(F, 0);
2148 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002149 } else if (Name == "read") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002150 if (FTy->getNumParams() != 3 ||
2151 !isa<PointerType>(FTy->getParamType(1)))
2152 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002153 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002154 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002155 } else if (Name == "rmdir" ||
2156 Name == "rewind" ||
2157 Name == "remove" ||
2158 Name == "realpath") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002159 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002160 !isa<PointerType>(FTy->getParamType(0)))
2161 continue;
2162 setDoesNotThrow(F);
2163 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002164 } else if (Name == "rename" ||
2165 Name == "readlink") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002166 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002167 !isa<PointerType>(FTy->getParamType(0)) ||
2168 !isa<PointerType>(FTy->getParamType(1)))
2169 continue;
2170 setDoesNotThrow(F);
2171 setDoesNotCapture(F, 1);
2172 setDoesNotCapture(F, 2);
2173 }
2174 break;
2175 case 'w':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002176 if (Name == "write") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002177 if (FTy->getNumParams() != 3 ||
2178 !isa<PointerType>(FTy->getParamType(1)))
2179 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002180 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002181 setDoesNotCapture(F, 2);
2182 }
2183 break;
2184 case 'b':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002185 if (Name == "bcopy") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002186 if (FTy->getNumParams() != 3 ||
2187 !isa<PointerType>(FTy->getParamType(0)) ||
2188 !isa<PointerType>(FTy->getParamType(1)))
2189 continue;
2190 setDoesNotThrow(F);
2191 setDoesNotCapture(F, 1);
2192 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002193 } else if (Name == "bcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002194 if (FTy->getNumParams() != 3 ||
2195 !isa<PointerType>(FTy->getParamType(0)) ||
2196 !isa<PointerType>(FTy->getParamType(1)))
2197 continue;
2198 setDoesNotThrow(F);
2199 setOnlyReadsMemory(F);
2200 setDoesNotCapture(F, 1);
2201 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002202 } else if (Name == "bzero") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002203 if (FTy->getNumParams() != 2 ||
2204 !isa<PointerType>(FTy->getParamType(0)))
2205 continue;
2206 setDoesNotThrow(F);
2207 setDoesNotCapture(F, 1);
2208 }
2209 break;
2210 case 'c':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002211 if (Name == "calloc") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002212 if (FTy->getNumParams() != 2 ||
2213 !isa<PointerType>(FTy->getReturnType()))
2214 continue;
2215 setDoesNotThrow(F);
2216 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002217 } else if (Name == "chmod" ||
2218 Name == "chown" ||
2219 Name == "ctermid" ||
2220 Name == "clearerr" ||
2221 Name == "closedir") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002222 if (FTy->getNumParams() == 0 ||
2223 !isa<PointerType>(FTy->getParamType(0)))
2224 continue;
2225 setDoesNotThrow(F);
2226 setDoesNotCapture(F, 1);
2227 }
2228 break;
2229 case 'a':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002230 if (Name == "atoi" ||
2231 Name == "atol" ||
2232 Name == "atof" ||
2233 Name == "atoll") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002234 if (FTy->getNumParams() != 1 ||
2235 !isa<PointerType>(FTy->getParamType(0)))
2236 continue;
2237 setDoesNotThrow(F);
2238 setOnlyReadsMemory(F);
2239 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002240 } else if (Name == "access") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002241 if (FTy->getNumParams() != 2 ||
2242 !isa<PointerType>(FTy->getParamType(0)))
2243 continue;
2244 setDoesNotThrow(F);
2245 setDoesNotCapture(F, 1);
2246 }
2247 break;
2248 case 'f':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002249 if (Name == "fopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002250 if (FTy->getNumParams() != 2 ||
2251 !isa<PointerType>(FTy->getReturnType()) ||
2252 !isa<PointerType>(FTy->getParamType(0)) ||
2253 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002254 continue;
2255 setDoesNotThrow(F);
2256 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002257 setDoesNotCapture(F, 1);
2258 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002259 } else if (Name == "fdopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002260 if (FTy->getNumParams() != 2 ||
2261 !isa<PointerType>(FTy->getReturnType()) ||
2262 !isa<PointerType>(FTy->getParamType(1)))
2263 continue;
2264 setDoesNotThrow(F);
2265 setDoesNotAlias(F, 0);
2266 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002267 } else if (Name == "feof" ||
2268 Name == "free" ||
2269 Name == "fseek" ||
2270 Name == "ftell" ||
2271 Name == "fgetc" ||
2272 Name == "fseeko" ||
2273 Name == "ftello" ||
2274 Name == "fileno" ||
2275 Name == "fflush" ||
2276 Name == "fclose" ||
2277 Name == "fsetpos" ||
2278 Name == "flockfile" ||
2279 Name == "funlockfile" ||
2280 Name == "ftrylockfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002281 if (FTy->getNumParams() == 0 ||
2282 !isa<PointerType>(FTy->getParamType(0)))
2283 continue;
2284 setDoesNotThrow(F);
2285 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002286 } else if (Name == "ferror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002287 if (FTy->getNumParams() != 1 ||
2288 !isa<PointerType>(FTy->getParamType(0)))
2289 continue;
2290 setDoesNotThrow(F);
2291 setDoesNotCapture(F, 1);
2292 setOnlyReadsMemory(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002293 } else if (Name == "fputc" ||
2294 Name == "fstat" ||
2295 Name == "frexp" ||
2296 Name == "frexpf" ||
2297 Name == "frexpl" ||
2298 Name == "fstatvfs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002299 if (FTy->getNumParams() != 2 ||
2300 !isa<PointerType>(FTy->getParamType(1)))
2301 continue;
2302 setDoesNotThrow(F);
2303 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002304 } else if (Name == "fgets") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002305 if (FTy->getNumParams() != 3 ||
2306 !isa<PointerType>(FTy->getParamType(0)) ||
2307 !isa<PointerType>(FTy->getParamType(2)))
2308 continue;
2309 setDoesNotThrow(F);
2310 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002311 } else if (Name == "fread" ||
2312 Name == "fwrite") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002313 if (FTy->getNumParams() != 4 ||
2314 !isa<PointerType>(FTy->getParamType(0)) ||
2315 !isa<PointerType>(FTy->getParamType(3)))
2316 continue;
2317 setDoesNotThrow(F);
2318 setDoesNotCapture(F, 1);
2319 setDoesNotCapture(F, 4);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002320 } else if (Name == "fputs" ||
2321 Name == "fscanf" ||
2322 Name == "fprintf" ||
2323 Name == "fgetpos") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002324 if (FTy->getNumParams() < 2 ||
2325 !isa<PointerType>(FTy->getParamType(0)) ||
2326 !isa<PointerType>(FTy->getParamType(1)))
2327 continue;
2328 setDoesNotThrow(F);
2329 setDoesNotCapture(F, 1);
2330 setDoesNotCapture(F, 2);
2331 }
2332 break;
2333 case 'g':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002334 if (Name == "getc" ||
2335 Name == "getlogin_r" ||
2336 Name == "getc_unlocked") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002337 if (FTy->getNumParams() == 0 ||
2338 !isa<PointerType>(FTy->getParamType(0)))
2339 continue;
2340 setDoesNotThrow(F);
2341 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002342 } else if (Name == "getenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002343 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002344 !isa<PointerType>(FTy->getParamType(0)))
2345 continue;
2346 setDoesNotThrow(F);
2347 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002348 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002349 } else if (Name == "gets" ||
2350 Name == "getchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002351 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002352 } else if (Name == "getitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002353 if (FTy->getNumParams() != 2 ||
2354 !isa<PointerType>(FTy->getParamType(1)))
2355 continue;
2356 setDoesNotThrow(F);
2357 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002358 } else if (Name == "getpwnam") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002359 if (FTy->getNumParams() != 1 ||
2360 !isa<PointerType>(FTy->getParamType(0)))
2361 continue;
2362 setDoesNotThrow(F);
2363 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002364 }
2365 break;
2366 case 'u':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002367 if (Name == "ungetc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002368 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002369 !isa<PointerType>(FTy->getParamType(1)))
2370 continue;
2371 setDoesNotThrow(F);
2372 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002373 } else if (Name == "uname" ||
2374 Name == "unlink" ||
2375 Name == "unsetenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002376 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002377 !isa<PointerType>(FTy->getParamType(0)))
2378 continue;
2379 setDoesNotThrow(F);
2380 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002381 } else if (Name == "utime" ||
2382 Name == "utimes") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002383 if (FTy->getNumParams() != 2 ||
2384 !isa<PointerType>(FTy->getParamType(0)) ||
2385 !isa<PointerType>(FTy->getParamType(1)))
2386 continue;
2387 setDoesNotThrow(F);
2388 setDoesNotCapture(F, 1);
2389 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002390 }
2391 break;
2392 case 'p':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002393 if (Name == "putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002394 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002395 !isa<PointerType>(FTy->getParamType(1)))
2396 continue;
2397 setDoesNotThrow(F);
2398 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002399 } else if (Name == "puts" ||
2400 Name == "printf" ||
2401 Name == "perror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002402 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002403 !isa<PointerType>(FTy->getParamType(0)))
2404 continue;
2405 setDoesNotThrow(F);
2406 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002407 } else if (Name == "pread" ||
2408 Name == "pwrite") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002409 if (FTy->getNumParams() != 4 ||
2410 !isa<PointerType>(FTy->getParamType(1)))
2411 continue;
2412 // May throw; these are valid pthread cancellation points.
2413 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002414 } else if (Name == "putchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002415 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002416 } else if (Name == "popen") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002417 if (FTy->getNumParams() != 2 ||
2418 !isa<PointerType>(FTy->getReturnType()) ||
2419 !isa<PointerType>(FTy->getParamType(0)) ||
2420 !isa<PointerType>(FTy->getParamType(1)))
2421 continue;
2422 setDoesNotThrow(F);
2423 setDoesNotAlias(F, 0);
2424 setDoesNotCapture(F, 1);
2425 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002426 } else if (Name == "pclose") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002427 if (FTy->getNumParams() != 1 ||
2428 !isa<PointerType>(FTy->getParamType(0)))
2429 continue;
2430 setDoesNotThrow(F);
2431 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002432 }
2433 break;
2434 case 'v':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002435 if (Name == "vscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002436 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002437 !isa<PointerType>(FTy->getParamType(1)))
2438 continue;
2439 setDoesNotThrow(F);
2440 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002441 } else if (Name == "vsscanf" ||
2442 Name == "vfscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002443 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002444 !isa<PointerType>(FTy->getParamType(1)) ||
2445 !isa<PointerType>(FTy->getParamType(2)))
2446 continue;
2447 setDoesNotThrow(F);
2448 setDoesNotCapture(F, 1);
2449 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002450 } else if (Name == "valloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002451 if (!isa<PointerType>(FTy->getReturnType()))
2452 continue;
2453 setDoesNotThrow(F);
2454 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002455 } else if (Name == "vprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002456 if (FTy->getNumParams() != 2 ||
2457 !isa<PointerType>(FTy->getParamType(0)))
2458 continue;
2459 setDoesNotThrow(F);
2460 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002461 } else if (Name == "vfprintf" ||
2462 Name == "vsprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002463 if (FTy->getNumParams() != 3 ||
2464 !isa<PointerType>(FTy->getParamType(0)) ||
2465 !isa<PointerType>(FTy->getParamType(1)))
2466 continue;
2467 setDoesNotThrow(F);
2468 setDoesNotCapture(F, 1);
2469 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002470 } else if (Name == "vsnprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002471 if (FTy->getNumParams() != 4 ||
2472 !isa<PointerType>(FTy->getParamType(0)) ||
2473 !isa<PointerType>(FTy->getParamType(2)))
2474 continue;
2475 setDoesNotThrow(F);
2476 setDoesNotCapture(F, 1);
2477 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002478 }
2479 break;
2480 case 'o':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002481 if (Name == "open") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002482 if (FTy->getNumParams() < 2 ||
2483 !isa<PointerType>(FTy->getParamType(0)))
2484 continue;
2485 // May throw; "open" is a valid pthread cancellation point.
2486 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002487 } else if (Name == "opendir") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002488 if (FTy->getNumParams() != 1 ||
2489 !isa<PointerType>(FTy->getReturnType()) ||
2490 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002491 continue;
2492 setDoesNotThrow(F);
2493 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002494 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002495 }
2496 break;
2497 case 't':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002498 if (Name == "tmpfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002499 if (!isa<PointerType>(FTy->getReturnType()))
2500 continue;
2501 setDoesNotThrow(F);
2502 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002503 } else if (Name == "times") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002504 if (FTy->getNumParams() != 1 ||
2505 !isa<PointerType>(FTy->getParamType(0)))
2506 continue;
2507 setDoesNotThrow(F);
2508 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002509 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002510 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002511 case 'h':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002512 if (Name == "htonl" ||
2513 Name == "htons") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002514 setDoesNotThrow(F);
2515 setDoesNotAccessMemory(F);
2516 }
2517 break;
2518 case 'n':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002519 if (Name == "ntohl" ||
2520 Name == "ntohs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002521 setDoesNotThrow(F);
2522 setDoesNotAccessMemory(F);
2523 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002524 break;
2525 case 'l':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002526 if (Name == "lstat") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002527 if (FTy->getNumParams() != 2 ||
2528 !isa<PointerType>(FTy->getParamType(0)) ||
2529 !isa<PointerType>(FTy->getParamType(1)))
2530 continue;
2531 setDoesNotThrow(F);
2532 setDoesNotCapture(F, 1);
2533 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002534 } else if (Name == "lchown") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002535 if (FTy->getNumParams() != 3 ||
2536 !isa<PointerType>(FTy->getParamType(0)))
2537 continue;
2538 setDoesNotThrow(F);
2539 setDoesNotCapture(F, 1);
2540 }
2541 break;
2542 case 'q':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002543 if (Name == "qsort") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002544 if (FTy->getNumParams() != 4 ||
2545 !isa<PointerType>(FTy->getParamType(3)))
2546 continue;
2547 // May throw; places call through function pointer.
2548 setDoesNotCapture(F, 4);
2549 }
2550 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002551 case '_':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002552 if (Name == "__strdup" ||
2553 Name == "__strndup") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002554 if (FTy->getNumParams() < 1 ||
2555 !isa<PointerType>(FTy->getReturnType()) ||
2556 !isa<PointerType>(FTy->getParamType(0)))
2557 continue;
2558 setDoesNotThrow(F);
2559 setDoesNotAlias(F, 0);
2560 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002561 } else if (Name == "__strtok_r") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002562 if (FTy->getNumParams() != 3 ||
2563 !isa<PointerType>(FTy->getParamType(1)))
2564 continue;
2565 setDoesNotThrow(F);
2566 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002567 } else if (Name == "_IO_getc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002568 if (FTy->getNumParams() != 1 ||
2569 !isa<PointerType>(FTy->getParamType(0)))
2570 continue;
2571 setDoesNotThrow(F);
2572 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002573 } else if (Name == "_IO_putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002574 if (FTy->getNumParams() != 2 ||
2575 !isa<PointerType>(FTy->getParamType(1)))
2576 continue;
2577 setDoesNotThrow(F);
2578 setDoesNotCapture(F, 2);
2579 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002580 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002581 case 1:
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002582 if (Name == "\1__isoc99_scanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002583 if (FTy->getNumParams() < 1 ||
2584 !isa<PointerType>(FTy->getParamType(0)))
2585 continue;
2586 setDoesNotThrow(F);
2587 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002588 } else if (Name == "\1stat64" ||
2589 Name == "\1lstat64" ||
2590 Name == "\1statvfs64" ||
2591 Name == "\1__isoc99_sscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002592 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002593 !isa<PointerType>(FTy->getParamType(0)) ||
2594 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002595 continue;
2596 setDoesNotThrow(F);
2597 setDoesNotCapture(F, 1);
2598 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002599 } else if (Name == "\1fopen64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002600 if (FTy->getNumParams() != 2 ||
2601 !isa<PointerType>(FTy->getReturnType()) ||
2602 !isa<PointerType>(FTy->getParamType(0)) ||
2603 !isa<PointerType>(FTy->getParamType(1)))
2604 continue;
2605 setDoesNotThrow(F);
2606 setDoesNotAlias(F, 0);
2607 setDoesNotCapture(F, 1);
2608 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002609 } else if (Name == "\1fseeko64" ||
2610 Name == "\1ftello64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002611 if (FTy->getNumParams() == 0 ||
2612 !isa<PointerType>(FTy->getParamType(0)))
2613 continue;
2614 setDoesNotThrow(F);
2615 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002616 } else if (Name == "\1tmpfile64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002617 if (!isa<PointerType>(FTy->getReturnType()))
2618 continue;
2619 setDoesNotThrow(F);
2620 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002621 } else if (Name == "\1fstat64" ||
2622 Name == "\1fstatvfs64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002623 if (FTy->getNumParams() != 2 ||
2624 !isa<PointerType>(FTy->getParamType(1)))
2625 continue;
2626 setDoesNotThrow(F);
2627 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002628 } else if (Name == "\1open64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002629 if (FTy->getNumParams() < 2 ||
2630 !isa<PointerType>(FTy->getParamType(0)))
2631 continue;
2632 // May throw; "open" is a valid pthread cancellation point.
2633 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002634 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002635 break;
2636 }
2637 }
2638 return Modified;
2639}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002640
2641// TODO:
2642// Additional cases that we need to add to this file:
2643//
2644// cbrt:
2645// * cbrt(expN(X)) -> expN(x/3)
2646// * cbrt(sqrt(x)) -> pow(x,1/6)
2647// * cbrt(sqrt(x)) -> pow(x,1/9)
2648//
2649// cos, cosf, cosl:
2650// * cos(-x) -> cos(x)
2651//
2652// exp, expf, expl:
2653// * exp(log(x)) -> x
2654//
2655// log, logf, logl:
2656// * log(exp(x)) -> x
2657// * log(x**y) -> y*log(x)
2658// * log(exp(y)) -> y*log(e)
2659// * log(exp2(y)) -> y*log(2)
2660// * log(exp10(y)) -> y*log(10)
2661// * log(sqrt(x)) -> 0.5*log(x)
2662// * log(pow(x,y)) -> y*log(x)
2663//
2664// lround, lroundf, lroundl:
2665// * lround(cnst) -> cnst'
2666//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002667// pow, powf, powl:
2668// * pow(exp(x),y) -> exp(x*y)
2669// * pow(sqrt(x),y) -> pow(x,y*0.5)
2670// * pow(pow(x,y),z)-> pow(x,y*z)
2671//
2672// puts:
2673// * puts("") -> putchar("\n")
2674//
2675// round, roundf, roundl:
2676// * round(cnst) -> cnst'
2677//
2678// signbit:
2679// * signbit(cnst) -> cnst'
2680// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2681//
2682// sqrt, sqrtf, sqrtl:
2683// * sqrt(expN(x)) -> expN(x*0.5)
2684// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2685// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2686//
2687// stpcpy:
2688// * stpcpy(str, "literal") ->
2689// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2690// strrchr:
2691// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2692// (if c is a constant integer and s is a constant string)
2693// * strrchr(s1,0) -> strchr(s1,0)
2694//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002695// strpbrk:
2696// * strpbrk(s,a) -> offset_in_for(s,a)
2697// (if s and a are both constant strings)
2698// * strpbrk(s,"") -> 0
2699// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2700//
2701// strspn, strcspn:
2702// * strspn(s,a) -> const_int (if both args are constant)
2703// * strspn("",a) -> 0
2704// * strspn(s,"") -> 0
2705// * strcspn(s,a) -> const_int (if both args are constant)
2706// * strcspn("",a) -> 0
2707// * strcspn(s,"") -> strlen(a)
2708//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002709// tan, tanf, tanl:
2710// * tan(atan(x)) -> x
2711//
2712// trunc, truncf, truncl:
2713// * trunc(cnst) -> cnst'
2714//
2715//