blob: 72308c80af3c8ad5faaba90b15f8879c17ef14c9 [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
12// library functions). For example, a call to the function "exit(3)" that
13// occurs within the main() function can be transformed into a simple "return 3"
14// instruction. Any optimization that takes this form (replace call to library
15// function with simpler code that provides the same result) belongs in this
16// file.
17//
18//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "simplify-libcalls"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Intrinsics.h"
Owen Andersonfa5cbd62009-07-03 19:42:02 +000023#include "llvm/LLVMContext.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
26#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000027#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000028#include "llvm/Target/TargetData.h"
29#include "llvm/ADT/SmallPtrSet.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/Support/Compiler.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000033#include "llvm/Support/Debug.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000034#include "llvm/Config/config.h"
35using namespace llvm;
36
37STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000038STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000039
40//===----------------------------------------------------------------------===//
41// Optimizer Base Class
42//===----------------------------------------------------------------------===//
43
44/// This class is the abstract base class for the set of optimizations that
45/// corresponds to one library call.
46namespace {
47class VISIBILITY_HIDDEN LibCallOptimization {
48protected:
49 Function *Caller;
50 const TargetData *TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000051 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000052public:
53 LibCallOptimization() { }
54 virtual ~LibCallOptimization() {}
55
56 /// CallOptimizer - This pure virtual method is implemented by base classes to
57 /// do various optimizations. If this returns null then no transformation was
58 /// performed. If it returns CI, then it transformed the call and CI is to be
59 /// deleted. If it returns something else, replace CI with the new value and
60 /// delete CI.
Eric Christopher7a61d702008-08-08 19:39:37 +000061 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
62 =0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000063
Eric Christopher7a61d702008-08-08 19:39:37 +000064 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000065 Caller = CI->getParent()->getParent();
66 this->TD = &TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000067 if (CI->getCalledFunction())
68 Context = CI->getCalledFunction()->getContext();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000069 return CallOptimizer(CI->getCalledFunction(), CI, B);
70 }
71
72 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +000073 Value *CastToCStr(Value *V, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000074
75 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
76 /// specified pointer. Ptr is required to be some pointer type, and the
77 /// return value has 'intptr_t' type.
Eric Christopher7a61d702008-08-08 19:39:37 +000078 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000079
80 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
81 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
82 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +000083 unsigned Align, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000084
85 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
86 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
Eric Christopher7a61d702008-08-08 19:39:37 +000087 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +000088
89 /// EmitMemCmp - Emit a call to the memcmp function.
90 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
91
Chris Lattnerf5b6bc72009-04-12 05:06:39 +000092 /// EmitMemSet - Emit a call to the memset function
93 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
94
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000095 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
96 /// 'floor'). This function is known to take a single of type matching 'Op'
97 /// and returns one value with the same type. If 'Op' is a long double, 'l'
98 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
Eric Christopher7a61d702008-08-08 19:39:37 +000099 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000100
101 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
102 /// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000103 void EmitPutChar(Value *Char, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000104
105 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
106 /// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000107 void EmitPutS(Value *Str, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000108
109 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
110 /// an i32, and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000111 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000112
113 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
114 /// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000115 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000116
117 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
118 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000119 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000120
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000121};
122} // End anonymous namespace.
123
124/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +0000125Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000126 return
127 B.CreateBitCast(V, Context->getPointerTypeUnqual(Type::Int8Ty), "cstr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000128}
129
130/// EmitStrLen - Emit a call to the strlen function to the builder, for the
131/// specified pointer. This always returns an integer value of size intptr_t.
Eric Christopher7a61d702008-08-08 19:39:37 +0000132Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000133 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000134 AttributeWithIndex AWI[2];
135 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
136 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
137 Attribute::NoUnwind);
138
139 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
140 TD->getIntPtrType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000141 Context->getPointerTypeUnqual(Type::Int8Ty),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000142 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000143 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
144 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
145 CI->setCallingConv(F->getCallingConv());
146
147 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000148}
149
150/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
151/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
152Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +0000153 unsigned Align, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000154 Module *M = Caller->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +0000155 Intrinsic::ID IID = Intrinsic::memcpy;
156 const Type *Tys[1];
157 Tys[0] = Len->getType();
158 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000159 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000160 Context->getConstantInt(Type::Int32Ty, Align));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000161}
162
163/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
164/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
165Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
Eric Christopher7a61d702008-08-08 19:39:37 +0000166 Value *Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000167 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000168 AttributeWithIndex AWI;
169 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
170
171 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000172 Context->getPointerTypeUnqual(Type::Int8Ty),
173 Context->getPointerTypeUnqual(Type::Int8Ty),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000174 Type::Int32Ty, TD->getIntPtrType(),
175 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000176 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
177
178 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
179 CI->setCallingConv(F->getCallingConv());
180
181 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000182}
183
Nick Lewycky13a09e22008-12-21 00:19:21 +0000184/// EmitMemCmp - Emit a call to the memcmp function.
185Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
186 Value *Len, IRBuilder<> &B) {
187 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000188 AttributeWithIndex AWI[3];
189 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
190 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
191 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
192 Attribute::NoUnwind);
193
194 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
Nick Lewycky13a09e22008-12-21 00:19:21 +0000195 Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000196 Context->getPointerTypeUnqual(Type::Int8Ty),
197 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky13a09e22008-12-21 00:19:21 +0000198 TD->getIntPtrType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000199 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
200 Len, "memcmp");
201
202 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
203 CI->setCallingConv(F->getCallingConv());
204
205 return CI;
Nick Lewycky13a09e22008-12-21 00:19:21 +0000206}
207
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000208/// EmitMemSet - Emit a call to the memset function
209Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
210 Value *Len, IRBuilder<> &B) {
211 Module *M = Caller->getParent();
212 Intrinsic::ID IID = Intrinsic::memset;
213 const Type *Tys[1];
214 Tys[0] = Len->getType();
215 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000216 Value *Align = Context->getConstantInt(Type::Int32Ty, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000217 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
218}
219
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000220/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
221/// 'floor'). This function is known to take a single of type matching 'Op' and
222/// returns one value with the same type. If 'Op' is a long double, 'l' is
223/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
224Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
Eric Christopher7a61d702008-08-08 19:39:37 +0000225 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000226 char NameBuffer[20];
227 if (Op->getType() != Type::DoubleTy) {
228 // If we need to add a suffix, copy into NameBuffer.
229 unsigned NameLen = strlen(Name);
230 assert(NameLen < sizeof(NameBuffer)-2);
231 memcpy(NameBuffer, Name, NameLen);
232 if (Op->getType() == Type::FloatTy)
233 NameBuffer[NameLen] = 'f'; // floorf
234 else
235 NameBuffer[NameLen] = 'l'; // floorl
236 NameBuffer[NameLen+1] = 0;
237 Name = NameBuffer;
238 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000239
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000240 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000241 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000242 Op->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000243 CallInst *CI = B.CreateCall(Callee, Op, Name);
244
245 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
246 CI->setCallingConv(F->getCallingConv());
247
248 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000249}
250
251/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
252/// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000253void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000254 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000255 Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
256 Type::Int32Ty, NULL);
257 CallInst *CI = B.CreateCall(PutChar,
258 B.CreateIntCast(Char, Type::Int32Ty, "chari"),
259 "putchar");
260
261 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
262 CI->setCallingConv(F->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000263}
264
265/// EmitPutS - Emit a call to the puts function. This assumes that Str is
266/// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000267void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000268 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000269 AttributeWithIndex AWI[2];
270 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
271 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
272
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000273 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
274 Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000275 Context->getPointerTypeUnqual(Type::Int8Ty),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000276 NULL);
277 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
278 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
279 CI->setCallingConv(F->getCallingConv());
280
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000281}
282
283/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
284/// an integer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000285void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000286 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000287 AttributeWithIndex AWI[2];
288 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
289 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
290 Constant *F;
291 if (isa<PointerType>(File->getType()))
292 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
293 Type::Int32Ty, File->getType(), NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000294 else
295 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
296 File->getType(), NULL);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000297 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000298 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
299
300 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
301 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000302}
303
304/// EmitFPutS - Emit a call to the puts function. Str is required to be a
305/// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000306void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000307 Module *M = Caller->getParent();
Nick Lewycky225f7472009-02-15 22:47:25 +0000308 AttributeWithIndex AWI[3];
309 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
310 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
311 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000312 Constant *F;
313 if (isa<PointerType>(File->getType()))
Nick Lewycky225f7472009-02-15 22:47:25 +0000314 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000315 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000316 File->getType(), NULL);
317 else
318 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000319 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000320 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000321 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
322
323 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
324 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000325}
326
327/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
328/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
329void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
Eric Christopher7a61d702008-08-08 19:39:37 +0000330 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000331 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000332 AttributeWithIndex AWI[3];
333 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
334 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
335 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
336 Constant *F;
337 if (isa<PointerType>(File->getType()))
338 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
339 TD->getIntPtrType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000340 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000341 TD->getIntPtrType(), TD->getIntPtrType(),
342 File->getType(), NULL);
343 else
344 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000345 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000346 TD->getIntPtrType(), TD->getIntPtrType(),
347 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000348 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000349 Context->getConstantInt(TD->getIntPtrType(), 1), File);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000350
351 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
352 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000353}
354
355//===----------------------------------------------------------------------===//
356// Helper Functions
357//===----------------------------------------------------------------------===//
358
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000359/// GetStringLengthH - If we can compute the length of the string pointed to by
360/// the specified pointer, return 'len+1'. If we can't, return 0.
361static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
362 // Look through noop bitcast instructions.
363 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
364 return GetStringLengthH(BCI->getOperand(0), PHIs);
365
366 // If this is a PHI node, there are two cases: either we have already seen it
367 // or we haven't.
368 if (PHINode *PN = dyn_cast<PHINode>(V)) {
369 if (!PHIs.insert(PN))
370 return ~0ULL; // already in the set.
371
372 // If it was new, see if all the input strings are the same length.
373 uint64_t LenSoFar = ~0ULL;
374 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
375 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
376 if (Len == 0) return 0; // Unknown length -> unknown.
377
378 if (Len == ~0ULL) continue;
379
380 if (Len != LenSoFar && LenSoFar != ~0ULL)
381 return 0; // Disagree -> unknown.
382 LenSoFar = Len;
383 }
384
385 // Success, all agree.
386 return LenSoFar;
387 }
388
389 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
390 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
391 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
392 if (Len1 == 0) return 0;
393 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
394 if (Len2 == 0) return 0;
395 if (Len1 == ~0ULL) return Len2;
396 if (Len2 == ~0ULL) return Len1;
397 if (Len1 != Len2) return 0;
398 return Len1;
399 }
400
401 // If the value is not a GEP instruction nor a constant expression with a
402 // GEP instruction, then return unknown.
403 User *GEP = 0;
404 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
405 GEP = GEPI;
406 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
407 if (CE->getOpcode() != Instruction::GetElementPtr)
408 return 0;
409 GEP = CE;
410 } else {
411 return 0;
412 }
413
414 // Make sure the GEP has exactly three arguments.
415 if (GEP->getNumOperands() != 3)
416 return 0;
417
418 // Check to make sure that the first operand of the GEP is an integer and
419 // has value 0 so that we are sure we're indexing into the initializer.
420 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
421 if (!Idx->isZero())
422 return 0;
423 } else
424 return 0;
425
426 // If the second index isn't a ConstantInt, then this is a variable index
427 // into the array. If this occurs, we can't say anything meaningful about
428 // the string.
429 uint64_t StartIdx = 0;
430 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
431 StartIdx = CI->getZExtValue();
432 else
433 return 0;
434
435 // The GEP instruction, constant or instruction, must reference a global
436 // variable that is a constant and is initialized. The referenced constant
437 // initializer is the array that we'll use for optimization.
438 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
439 if (!GV || !GV->isConstant() || !GV->hasInitializer())
440 return 0;
441 Constant *GlobalInit = GV->getInitializer();
442
443 // Handle the ConstantAggregateZero case, which is a degenerate case. The
444 // initializer is constant zero so the length of the string must be zero.
445 if (isa<ConstantAggregateZero>(GlobalInit))
446 return 1; // Len = 0 offset by 1.
447
448 // Must be a Constant Array
449 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
450 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
451 return false;
452
453 // Get the number of elements in the array
454 uint64_t NumElts = Array->getType()->getNumElements();
455
456 // Traverse the constant array from StartIdx (derived above) which is
457 // the place the GEP refers to in the array.
458 for (unsigned i = StartIdx; i != NumElts; ++i) {
459 Constant *Elt = Array->getOperand(i);
460 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
461 if (!CI) // This array isn't suitable, non-int initializer.
462 return 0;
463 if (CI->isZero())
464 return i-StartIdx+1; // We found end of string, success!
465 }
466
467 return 0; // The array isn't null terminated, conservatively return 'unknown'.
468}
469
470/// GetStringLength - If we can compute the length of the string pointed to by
471/// the specified pointer, return 'len+1'. If we can't, return 0.
472static uint64_t GetStringLength(Value *V) {
473 if (!isa<PointerType>(V->getType())) return 0;
474
475 SmallPtrSet<PHINode*, 32> PHIs;
476 uint64_t Len = GetStringLengthH(V, PHIs);
477 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
478 // an empty string as a length.
479 return Len == ~0ULL ? 1 : Len;
480}
481
482/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
483/// value is equal or not-equal to zero.
484static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
485 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
486 UI != E; ++UI) {
487 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
488 if (IC->isEquality())
489 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
490 if (C->isNullValue())
491 continue;
492 // Unknown instruction.
493 return false;
494 }
495 return true;
496}
497
498//===----------------------------------------------------------------------===//
499// Miscellaneous LibCall Optimizations
500//===----------------------------------------------------------------------===//
501
Bill Wendlingac178222008-05-05 21:37:59 +0000502namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000503//===---------------------------------------===//
504// 'exit' Optimizations
505
506/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
507struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000508 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000509 // Verify we have a reasonable prototype for exit.
510 if (Callee->arg_size() == 0 || !CI->use_empty())
511 return 0;
512
513 // Verify the caller is main, and that the result type of main matches the
514 // argument type of exit.
515 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
516 Caller->getReturnType() != CI->getOperand(1)->getType())
517 return 0;
518
519 TerminatorInst *OldTI = CI->getParent()->getTerminator();
520
521 // Create the return after the call.
522 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
523
524 // Drop all successor phi node entries.
525 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
526 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
527
528 // Erase all instructions from after our return instruction until the end of
529 // the block.
530 BasicBlock::iterator FirstDead = RI; ++FirstDead;
531 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
532 return CI;
533 }
534};
535
536//===----------------------------------------------------------------------===//
537// String and Memory LibCall Optimizations
538//===----------------------------------------------------------------------===//
539
540//===---------------------------------------===//
541// 'strcat' Optimizations
542
543struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000544 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000545 // Verify the "strcat" function prototype.
546 const FunctionType *FT = Callee->getFunctionType();
547 if (FT->getNumParams() != 2 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000548 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000549 FT->getParamType(0) != FT->getReturnType() ||
550 FT->getParamType(1) != FT->getReturnType())
551 return 0;
552
553 // Extract some information from the instruction
554 Value *Dst = CI->getOperand(1);
555 Value *Src = CI->getOperand(2);
556
557 // See if we can get the length of the input string.
558 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000559 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000560 --Len; // Unbias length.
561
562 // Handle the simple, do-nothing case: strcat(x, "") -> x
563 if (Len == 0)
564 return Dst;
565
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000566 EmitStrLenMemCpy(Src, Dst, Len, B);
567 return Dst;
568 }
569
570 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000571 // We need to find the end of the destination string. That's where the
572 // memory is to be moved to. We just generate a call to strlen.
573 Value *DstLen = EmitStrLen(Dst, B);
574
575 // Now that we have the destination's length, we must index into the
576 // destination's pointer to get the actual memcpy destination (end of
577 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000578 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000579
580 // We have enough information to now generate the memcpy call to do the
581 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000582 EmitMemCpy(CpyDst, Src,
583 Context->getConstantInt(TD->getIntPtrType(), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000584 }
585};
586
587//===---------------------------------------===//
588// 'strncat' Optimizations
589
590struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
591 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
592 // Verify the "strncat" function prototype.
593 const FunctionType *FT = Callee->getFunctionType();
594 if (FT->getNumParams() != 3 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000595 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000596 FT->getParamType(0) != FT->getReturnType() ||
597 FT->getParamType(1) != FT->getReturnType() ||
598 !isa<IntegerType>(FT->getParamType(2)))
599 return 0;
600
601 // Extract some information from the instruction
602 Value *Dst = CI->getOperand(1);
603 Value *Src = CI->getOperand(2);
604 uint64_t Len;
605
606 // We don't do anything if length is not constant
607 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
608 Len = LengthArg->getZExtValue();
609 else
610 return 0;
611
612 // See if we can get the length of the input string.
613 uint64_t SrcLen = GetStringLength(Src);
614 if (SrcLen == 0) return 0;
615 --SrcLen; // Unbias length.
616
617 // Handle the simple, do-nothing cases:
618 // strncat(x, "", c) -> x
619 // strncat(x, c, 0) -> x
620 if (SrcLen == 0 || Len == 0) return Dst;
621
622 // We don't optimize this case
623 if (Len < SrcLen) return 0;
624
625 // strncat(x, s, c) -> strcat(x, s)
626 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000627 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000628 return Dst;
629 }
630};
631
632//===---------------------------------------===//
633// 'strchr' Optimizations
634
635struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000636 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000637 // Verify the "strchr" function prototype.
638 const FunctionType *FT = Callee->getFunctionType();
639 if (FT->getNumParams() != 2 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000640 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000641 FT->getParamType(0) != FT->getReturnType())
642 return 0;
643
644 Value *SrcStr = CI->getOperand(1);
645
646 // If the second operand is non-constant, see if we can compute the length
647 // of the input string and turn this into memchr.
648 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
649 if (CharC == 0) {
650 uint64_t Len = GetStringLength(SrcStr);
651 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
652 return 0;
653
654 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000655 Context->getConstantInt(TD->getIntPtrType(), Len), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000656 }
657
658 // Otherwise, the character is a constant, see if the first argument is
659 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000660 std::string Str;
661 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000662 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000663
664 // strchr can find the nul character.
665 Str += '\0';
666 char CharValue = CharC->getSExtValue();
667
668 // Compute the offset.
669 uint64_t i = 0;
670 while (1) {
671 if (i == Str.size()) // Didn't find the char. strchr returns null.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000672 return Context->getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000673 // Did we find our match?
674 if (Str[i] == CharValue)
675 break;
676 ++i;
677 }
678
679 // strchr(s+n,c) -> gep(s+n+i,c)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000680 Value *Idx = Context->getConstantInt(Type::Int64Ty, i);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000681 return B.CreateGEP(SrcStr, Idx, "strchr");
682 }
683};
684
685//===---------------------------------------===//
686// 'strcmp' Optimizations
687
688struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000689 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000690 // Verify the "strcmp" function prototype.
691 const FunctionType *FT = Callee->getFunctionType();
692 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
693 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000694 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000695 return 0;
696
697 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
698 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000699 return Context->getConstantInt(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000700
Bill Wendling0582ae92009-03-13 04:39:26 +0000701 std::string Str1, Str2;
702 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
703 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
704
705 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000706 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
707
Bill Wendling0582ae92009-03-13 04:39:26 +0000708 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000709 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
710
711 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000712 if (HasStr1 && HasStr2)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000713 return Context->getConstantInt(CI->getType(),
714 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000715
716 // strcmp(P, "x") -> memcmp(P, "x", 2)
717 uint64_t Len1 = GetStringLength(Str1P);
718 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000719 if (Len1 && Len2) {
Nick Lewycky13a09e22008-12-21 00:19:21 +0000720 return EmitMemCmp(Str1P, Str2P,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000721 Context->getConstantInt(TD->getIntPtrType(),
Chris Lattner849832c2009-06-19 04:17:36 +0000722 std::min(Len1, Len2)), B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000723 }
724
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000725 return 0;
726 }
727};
728
729//===---------------------------------------===//
730// 'strncmp' Optimizations
731
732struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000733 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000734 // Verify the "strncmp" function prototype.
735 const FunctionType *FT = Callee->getFunctionType();
736 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
737 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000738 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000739 !isa<IntegerType>(FT->getParamType(2)))
740 return 0;
741
742 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
743 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000744 return Context->getConstantInt(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000745
746 // Get the length argument if it is constant.
747 uint64_t Length;
748 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
749 Length = LengthArg->getZExtValue();
750 else
751 return 0;
752
753 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000754 return Context->getConstantInt(CI->getType(), 0);
Bill Wendling0582ae92009-03-13 04:39:26 +0000755
756 std::string Str1, Str2;
757 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
758 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
759
760 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000761 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
762
Bill Wendling0582ae92009-03-13 04:39:26 +0000763 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000764 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
765
766 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000767 if (HasStr1 && HasStr2)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000768 return Context->getConstantInt(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000769 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000770 return 0;
771 }
772};
773
774
775//===---------------------------------------===//
776// 'strcpy' Optimizations
777
778struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000779 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000780 // Verify the "strcpy" function prototype.
781 const FunctionType *FT = Callee->getFunctionType();
782 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
783 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000784 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000785 return 0;
786
787 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
788 if (Dst == Src) // strcpy(x,x) -> x
789 return Src;
790
791 // See if we can get the length of the input string.
792 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000793 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000794
795 // We have enough information to now generate the memcpy call to do the
796 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000797 EmitMemCpy(Dst, Src,
798 Context->getConstantInt(TD->getIntPtrType(), Len), 1, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000799 return Dst;
800 }
801};
802
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000803//===---------------------------------------===//
804// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000805
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000806struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
807 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
808 const FunctionType *FT = Callee->getFunctionType();
809 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
810 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000811 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000812 !isa<IntegerType>(FT->getParamType(2)))
813 return 0;
814
815 Value *Dst = CI->getOperand(1);
816 Value *Src = CI->getOperand(2);
817 Value *LenOp = CI->getOperand(3);
818
819 // See if we can get the length of the input string.
820 uint64_t SrcLen = GetStringLength(Src);
821 if (SrcLen == 0) return 0;
822 --SrcLen;
823
824 if (SrcLen == 0) {
825 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000826 EmitMemSet(Dst, Context->getConstantInt(Type::Int8Ty, '\0'), LenOp, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000827 return Dst;
828 }
829
830 uint64_t Len;
831 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
832 Len = LengthArg->getZExtValue();
833 else
834 return 0;
835
836 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
837
838 // Let strncpy handle the zero padding
839 if (Len > SrcLen+1) return 0;
840
841 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000842 EmitMemCpy(Dst, Src,
843 Context->getConstantInt(TD->getIntPtrType(), Len), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000844
845 return Dst;
846 }
847};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000848
849//===---------------------------------------===//
850// 'strlen' Optimizations
851
852struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000853 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000854 const FunctionType *FT = Callee->getFunctionType();
855 if (FT->getNumParams() != 1 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000856 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000857 !isa<IntegerType>(FT->getReturnType()))
858 return 0;
859
860 Value *Src = CI->getOperand(1);
861
862 // Constant folding: strlen("xyz") -> 3
863 if (uint64_t Len = GetStringLength(Src))
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000864 return Context->getConstantInt(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000865
866 // Handle strlen(p) != 0.
867 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
868
869 // strlen(x) != 0 --> *x != 0
870 // strlen(x) == 0 --> *x == 0
871 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
872 }
873};
874
875//===---------------------------------------===//
Nick Lewycky4c498412009-02-13 15:31:46 +0000876// 'strto*' Optimizations
877
878struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
879 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
880 const FunctionType *FT = Callee->getFunctionType();
881 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
882 !isa<PointerType>(FT->getParamType(0)) ||
883 !isa<PointerType>(FT->getParamType(1)))
884 return 0;
885
886 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000887 if (isa<ConstantPointerNull>(EndPtr)) {
888 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000889 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000890 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000891
892 return 0;
893 }
894};
895
896
897//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000898// 'memcmp' Optimizations
899
900struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000901 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000902 const FunctionType *FT = Callee->getFunctionType();
903 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
904 !isa<PointerType>(FT->getParamType(1)) ||
905 FT->getReturnType() != Type::Int32Ty)
906 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000907
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000908 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000909
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000910 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000911 return Context->getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000912
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000913 // Make sure we have a constant length.
914 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000915 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000916 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000917
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000918 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000919 return Context->getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000920
921 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
922 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
923 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +0000924 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000925 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000926
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000927 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
928 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
929 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000930 const Type *PTy = Context->getPointerTypeUnqual(Len == 2 ?
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000931 Type::Int16Ty : Type::Int32Ty);
932 LHS = B.CreateBitCast(LHS, PTy, "tmp");
933 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000934 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
935 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
936 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
937 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
938 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000939
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000940 return 0;
941 }
942};
943
944//===---------------------------------------===//
945// 'memcpy' Optimizations
946
947struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000948 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000949 const FunctionType *FT = Callee->getFunctionType();
950 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
951 !isa<PointerType>(FT->getParamType(0)) ||
952 !isa<PointerType>(FT->getParamType(1)) ||
953 FT->getParamType(2) != TD->getIntPtrType())
954 return 0;
955
956 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
957 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
958 return CI->getOperand(1);
959 }
960};
961
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000962//===---------------------------------------===//
963// 'memmove' Optimizations
964
965struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
966 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
967 const FunctionType *FT = Callee->getFunctionType();
968 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
969 !isa<PointerType>(FT->getParamType(0)) ||
970 !isa<PointerType>(FT->getParamType(1)) ||
971 FT->getParamType(2) != TD->getIntPtrType())
972 return 0;
973
974 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
975 Module *M = Caller->getParent();
976 Intrinsic::ID IID = Intrinsic::memmove;
977 const Type *Tys[1];
978 Tys[0] = TD->getIntPtrType();
979 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
980 Value *Dst = CastToCStr(CI->getOperand(1), B);
981 Value *Src = CastToCStr(CI->getOperand(2), B);
982 Value *Size = CI->getOperand(3);
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000983 Value *Align = Context->getConstantInt(Type::Int32Ty, 1);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000984 B.CreateCall4(MemMove, Dst, Src, Size, Align);
985 return CI->getOperand(1);
986 }
987};
988
989//===---------------------------------------===//
990// 'memset' Optimizations
991
992struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
993 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
994 const FunctionType *FT = Callee->getFunctionType();
995 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
996 !isa<PointerType>(FT->getParamType(0)) ||
997 FT->getParamType(1) != TD->getIntPtrType() ||
998 FT->getParamType(2) != TD->getIntPtrType())
999 return 0;
1000
1001 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001002 Value *Val = B.CreateTrunc(CI->getOperand(2), Type::Int8Ty);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001003 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001004 return CI->getOperand(1);
1005 }
1006};
1007
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001008//===----------------------------------------------------------------------===//
1009// Math Library Optimizations
1010//===----------------------------------------------------------------------===//
1011
1012//===---------------------------------------===//
1013// 'pow*' Optimizations
1014
1015struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001016 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001017 const FunctionType *FT = Callee->getFunctionType();
1018 // Just make sure this has 2 arguments of the same FP type, which match the
1019 // result type.
1020 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1021 FT->getParamType(0) != FT->getParamType(1) ||
1022 !FT->getParamType(0)->isFloatingPoint())
1023 return 0;
1024
1025 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1026 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1027 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1028 return Op1C;
1029 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1030 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1031 }
1032
1033 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1034 if (Op2C == 0) return 0;
1035
1036 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001037 return Context->getConstantFP(CI->getType(), 1.0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001038
1039 if (Op2C->isExactlyValue(0.5)) {
1040 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1041 // 'unsafe' math optimizations are allowed.
1042 // x pow(x, 0.5) sqrt(x)
1043 // ---------------------------------------------
1044 // -0.0 +0.0 -0.0
1045 // -inf +inf NaN
1046#if 0
1047 // pow(x, 0.5) -> sqrt(x)
1048 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1049#endif
1050 }
1051
1052 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1053 return Op1;
1054 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001055 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001056 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001057 return B.CreateFDiv(Context->getConstantFP(CI->getType(), 1.0),
1058 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001059 return 0;
1060 }
1061};
1062
1063//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001064// 'exp2' Optimizations
1065
1066struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001067 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001068 const FunctionType *FT = Callee->getFunctionType();
1069 // Just make sure this has 1 argument of FP type, which matches the
1070 // result type.
1071 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1072 !FT->getParamType(0)->isFloatingPoint())
1073 return 0;
1074
1075 Value *Op = CI->getOperand(1);
1076 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1077 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1078 Value *LdExpArg = 0;
1079 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1080 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1081 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1082 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1083 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1084 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1085 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001086
Chris Lattnere818f772008-05-02 18:43:35 +00001087 if (LdExpArg) {
1088 const char *Name;
1089 if (Op->getType() == Type::FloatTy)
1090 Name = "ldexpf";
1091 else if (Op->getType() == Type::DoubleTy)
1092 Name = "ldexp";
1093 else
1094 Name = "ldexpl";
1095
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001096 Constant *One = Context->getConstantFP(APFloat(1.0f));
Chris Lattnere818f772008-05-02 18:43:35 +00001097 if (Op->getType() != Type::FloatTy)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001098 One = Context->getConstantExprFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001099
1100 Module *M = Caller->getParent();
1101 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1102 Op->getType(), Type::Int32Ty,NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001103 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1104 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1105 CI->setCallingConv(F->getCallingConv());
1106
1107 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001108 }
1109 return 0;
1110 }
1111};
Chris Lattnere818f772008-05-02 18:43:35 +00001112
1113//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001114// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1115
1116struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001117 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001118 const FunctionType *FT = Callee->getFunctionType();
1119 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1120 FT->getParamType(0) != Type::DoubleTy)
1121 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001122
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001123 // If this is something like 'floor((double)floatval)', convert to floorf.
1124 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1125 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1126 return 0;
1127
1128 // floor((double)floatval) -> (double)floorf(floatval)
1129 Value *V = Cast->getOperand(0);
1130 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
1131 return B.CreateFPExt(V, Type::DoubleTy);
1132 }
1133};
1134
1135//===----------------------------------------------------------------------===//
1136// Integer Optimizations
1137//===----------------------------------------------------------------------===//
1138
1139//===---------------------------------------===//
1140// 'ffs*' Optimizations
1141
1142struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001143 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001144 const FunctionType *FT = Callee->getFunctionType();
1145 // Just make sure this has 2 arguments of the same FP type, which match the
1146 // result type.
1147 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1148 !isa<IntegerType>(FT->getParamType(0)))
1149 return 0;
1150
1151 Value *Op = CI->getOperand(1);
1152
1153 // Constant fold.
1154 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1155 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001156 return Context->getNullValue(CI->getType());
1157 return Context->getConstantInt(Type::Int32Ty, // ffs(c) -> cttz(c)+1
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001158 CI->getValue().countTrailingZeros()+1);
1159 }
1160
1161 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1162 const Type *ArgType = Op->getType();
1163 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1164 Intrinsic::cttz, &ArgType, 1);
1165 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001166 V = B.CreateAdd(V, Context->getConstantInt(V->getType(), 1), "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001167 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1168
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001169 Value *Cond = B.CreateICmpNE(Op, Context->getNullValue(ArgType), "tmp");
1170 return B.CreateSelect(Cond, V, Context->getConstantInt(Type::Int32Ty, 0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001171 }
1172};
1173
1174//===---------------------------------------===//
1175// 'isdigit' Optimizations
1176
1177struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001178 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001179 const FunctionType *FT = Callee->getFunctionType();
1180 // We require integer(i32)
1181 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1182 FT->getParamType(0) != Type::Int32Ty)
1183 return 0;
1184
1185 // isdigit(c) -> (c-'0') <u 10
1186 Value *Op = CI->getOperand(1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001187 Op = B.CreateSub(Op, Context->getConstantInt(Type::Int32Ty, '0'),
1188 "isdigittmp");
1189 Op = B.CreateICmpULT(Op, Context->getConstantInt(Type::Int32Ty, 10),
1190 "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001191 return B.CreateZExt(Op, CI->getType());
1192 }
1193};
1194
1195//===---------------------------------------===//
1196// 'isascii' Optimizations
1197
1198struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001199 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001200 const FunctionType *FT = Callee->getFunctionType();
1201 // We require integer(i32)
1202 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1203 FT->getParamType(0) != Type::Int32Ty)
1204 return 0;
1205
1206 // isascii(c) -> c <u 128
1207 Value *Op = CI->getOperand(1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001208 Op = B.CreateICmpULT(Op, Context->getConstantInt(Type::Int32Ty, 128),
1209 "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210 return B.CreateZExt(Op, CI->getType());
1211 }
1212};
Chris Lattner313f0e62008-06-09 08:26:51 +00001213
1214//===---------------------------------------===//
1215// 'abs', 'labs', 'llabs' Optimizations
1216
1217struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001218 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001219 const FunctionType *FT = Callee->getFunctionType();
1220 // We require integer(integer) where the types agree.
1221 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1222 FT->getParamType(0) != FT->getReturnType())
1223 return 0;
1224
1225 // abs(x) -> x >s -1 ? x : -x
1226 Value *Op = CI->getOperand(1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001227 Value *Pos = B.CreateICmpSGT(Op,
1228 Context->getConstantIntAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001229 "ispos");
1230 Value *Neg = B.CreateNeg(Op, "neg");
1231 return B.CreateSelect(Pos, Op, Neg);
1232 }
1233};
1234
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001235
1236//===---------------------------------------===//
1237// 'toascii' Optimizations
1238
1239struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001240 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001241 const FunctionType *FT = Callee->getFunctionType();
1242 // We require i32(i32)
1243 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1244 FT->getParamType(0) != Type::Int32Ty)
1245 return 0;
1246
1247 // isascii(c) -> c & 0x7f
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001248 return B.CreateAnd(CI->getOperand(1),
1249 Context->getConstantInt(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001250 }
1251};
1252
1253//===----------------------------------------------------------------------===//
1254// Formatting and IO Optimizations
1255//===----------------------------------------------------------------------===//
1256
1257//===---------------------------------------===//
1258// 'printf' Optimizations
1259
1260struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001261 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001262 // Require one fixed pointer argument and an integer/void result.
1263 const FunctionType *FT = Callee->getFunctionType();
1264 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1265 !(isa<IntegerType>(FT->getReturnType()) ||
1266 FT->getReturnType() == Type::VoidTy))
1267 return 0;
1268
1269 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001270 std::string FormatStr;
1271 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1272 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001273
1274 // Empty format string -> noop.
1275 if (FormatStr.empty()) // Tolerate printf's declared void.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001276 return CI->use_empty() ? (Value*)CI :
1277 Context->getConstantInt(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001278
1279 // printf("x") -> putchar('x'), even for '%'.
1280 if (FormatStr.size() == 1) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001281 EmitPutChar(Context->getConstantInt(Type::Int32Ty, FormatStr[0]), B);
1282 return CI->use_empty() ? (Value*)CI :
1283 Context->getConstantInt(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001284 }
1285
1286 // printf("foo\n") --> puts("foo")
1287 if (FormatStr[FormatStr.size()-1] == '\n' &&
1288 FormatStr.find('%') == std::string::npos) { // no format characters.
1289 // Create a string literal with no \n on it. We expect the constant merge
1290 // pass to be run after this pass, to merge duplicate strings.
1291 FormatStr.erase(FormatStr.end()-1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001292 Constant *C = Context->getConstantArray(FormatStr, true);
Owen Anderson3d29df32009-07-08 01:26:06 +00001293 C = new GlobalVariable(*Context, C->getType(),
1294 true, GlobalVariable::InternalLinkage,
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001295 C, "str", Callee->getParent());
1296 EmitPutS(C, B);
1297 return CI->use_empty() ? (Value*)CI :
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001298 Context->getConstantInt(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001299 }
1300
1301 // Optimize specific format strings.
1302 // printf("%c", chr) --> putchar(*(i8*)dst)
1303 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1304 isa<IntegerType>(CI->getOperand(2)->getType())) {
1305 EmitPutChar(CI->getOperand(2), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001306 return CI->use_empty() ? (Value*)CI :
1307 Context->getConstantInt(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001308 }
1309
1310 // printf("%s\n", str) --> puts(str)
1311 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1312 isa<PointerType>(CI->getOperand(2)->getType()) &&
1313 CI->use_empty()) {
1314 EmitPutS(CI->getOperand(2), B);
1315 return CI;
1316 }
1317 return 0;
1318 }
1319};
1320
1321//===---------------------------------------===//
1322// 'sprintf' Optimizations
1323
1324struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001325 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001326 // Require two fixed pointer arguments and an integer result.
1327 const FunctionType *FT = Callee->getFunctionType();
1328 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1329 !isa<PointerType>(FT->getParamType(1)) ||
1330 !isa<IntegerType>(FT->getReturnType()))
1331 return 0;
1332
1333 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001334 std::string FormatStr;
1335 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1336 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001337
1338 // If we just have a format string (nothing else crazy) transform it.
1339 if (CI->getNumOperands() == 3) {
1340 // Make sure there's no % in the constant array. We could try to handle
1341 // %% -> % in the future if we cared.
1342 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1343 if (FormatStr[i] == '%')
1344 return 0; // we found a format specifier, bail out.
1345
1346 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1347 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001348 Context->getConstantInt(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1349 return Context->getConstantInt(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001350 }
1351
1352 // The remaining optimizations require the format string to be "%s" or "%c"
1353 // and have an extra operand.
1354 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1355 return 0;
1356
1357 // Decode the second character of the format string.
1358 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001359 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001360 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1361 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001362 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1363 B.CreateStore(V, Ptr);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001364 Ptr = B.CreateGEP(Ptr, Context->getConstantInt(Type::Int32Ty, 1), "nul");
1365 B.CreateStore(Context->getNullValue(Type::Int8Ty), Ptr);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001366
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001367 return Context->getConstantInt(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001368 }
1369
1370 if (FormatStr[1] == 's') {
1371 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1372 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1373
1374 Value *Len = EmitStrLen(CI->getOperand(3), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001375 Value *IncLen = B.CreateAdd(Len,
1376 Context->getConstantInt(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001377 "leninc");
1378 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1379
1380 // The sprintf result is the unincremented number of bytes in the string.
1381 return B.CreateIntCast(Len, CI->getType(), false);
1382 }
1383 return 0;
1384 }
1385};
1386
1387//===---------------------------------------===//
1388// 'fwrite' Optimizations
1389
1390struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001391 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001392 // Require a pointer, an integer, an integer, a pointer, returning integer.
1393 const FunctionType *FT = Callee->getFunctionType();
1394 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1395 !isa<IntegerType>(FT->getParamType(1)) ||
1396 !isa<IntegerType>(FT->getParamType(2)) ||
1397 !isa<PointerType>(FT->getParamType(3)) ||
1398 !isa<IntegerType>(FT->getReturnType()))
1399 return 0;
1400
1401 // Get the element size and count.
1402 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1403 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1404 if (!SizeC || !CountC) return 0;
1405 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1406
1407 // If this is writing zero records, remove the call (it's a noop).
1408 if (Bytes == 0)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001409 return Context->getConstantInt(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001410
1411 // If this is writing one byte, turn it into fputc.
1412 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1413 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1414 EmitFPutC(Char, CI->getOperand(4), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001415 return Context->getConstantInt(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001416 }
1417
1418 return 0;
1419 }
1420};
1421
1422//===---------------------------------------===//
1423// 'fputs' Optimizations
1424
1425struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001426 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001427 // Require two pointers. Also, we can't optimize if return value is used.
1428 const FunctionType *FT = Callee->getFunctionType();
1429 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1430 !isa<PointerType>(FT->getParamType(1)) ||
1431 !CI->use_empty())
1432 return 0;
1433
1434 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1435 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001436 if (!Len) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001437 EmitFWrite(CI->getOperand(1),
1438 Context->getConstantInt(TD->getIntPtrType(), Len-1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001439 CI->getOperand(2), B);
1440 return CI; // Known to have no uses (see above).
1441 }
1442};
1443
1444//===---------------------------------------===//
1445// 'fprintf' Optimizations
1446
1447struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001448 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001449 // Require two fixed paramters as pointers and integer result.
1450 const FunctionType *FT = Callee->getFunctionType();
1451 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1452 !isa<PointerType>(FT->getParamType(1)) ||
1453 !isa<IntegerType>(FT->getReturnType()))
1454 return 0;
1455
1456 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001457 std::string FormatStr;
1458 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1459 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001460
1461 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1462 if (CI->getNumOperands() == 3) {
1463 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1464 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001465 return 0; // We found a format specifier.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001466
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001467 EmitFWrite(CI->getOperand(2), Context->getConstantInt(TD->getIntPtrType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001468 FormatStr.size()),
1469 CI->getOperand(1), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001470 return Context->getConstantInt(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001471 }
1472
1473 // The remaining optimizations require the format string to be "%s" or "%c"
1474 // and have an extra operand.
1475 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1476 return 0;
1477
1478 // Decode the second character of the format string.
1479 if (FormatStr[1] == 'c') {
1480 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1481 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1482 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001483 return Context->getConstantInt(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001484 }
1485
1486 if (FormatStr[1] == 's') {
1487 // fprintf(F, "%s", str) -> fputs(str, F)
1488 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1489 return 0;
1490 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1491 return CI;
1492 }
1493 return 0;
1494 }
1495};
1496
Bill Wendlingac178222008-05-05 21:37:59 +00001497} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001498
1499//===----------------------------------------------------------------------===//
1500// SimplifyLibCalls Pass Implementation
1501//===----------------------------------------------------------------------===//
1502
1503namespace {
1504 /// This pass optimizes well known library functions from libc and libm.
1505 ///
1506 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1507 StringMap<LibCallOptimization*> Optimizations;
1508 // Miscellaneous LibCall Optimizations
1509 ExitOpt Exit;
1510 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001511 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1512 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1513 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1514 MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001515 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001516 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001517 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001518 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1519 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001520 // Formatting and IO Optimizations
1521 SPrintFOpt SPrintF; PrintFOpt PrintF;
1522 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001523
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001524 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001525 public:
1526 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001527 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001528
1529 void InitOptimizations();
1530 bool runOnFunction(Function &F);
1531
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001532 void setDoesNotAccessMemory(Function &F);
1533 void setOnlyReadsMemory(Function &F);
1534 void setDoesNotThrow(Function &F);
1535 void setDoesNotCapture(Function &F, unsigned n);
1536 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001537 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001538
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001539 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1540 AU.addRequired<TargetData>();
1541 }
1542 };
1543 char SimplifyLibCalls::ID = 0;
1544} // end anonymous namespace.
1545
1546static RegisterPass<SimplifyLibCalls>
1547X("simplify-libcalls", "Simplify well-known library calls");
1548
1549// Public interface to the Simplify LibCalls pass.
1550FunctionPass *llvm::createSimplifyLibCallsPass() {
1551 return new SimplifyLibCalls();
1552}
1553
1554/// Optimizations - Populate the Optimizations map with all the optimizations
1555/// we know.
1556void SimplifyLibCalls::InitOptimizations() {
1557 // Miscellaneous LibCall Optimizations
1558 Optimizations["exit"] = &Exit;
1559
1560 // String and Memory LibCall Optimizations
1561 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001562 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001563 Optimizations["strchr"] = &StrChr;
1564 Optimizations["strcmp"] = &StrCmp;
1565 Optimizations["strncmp"] = &StrNCmp;
1566 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001567 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001568 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001569 Optimizations["strtol"] = &StrTo;
1570 Optimizations["strtod"] = &StrTo;
1571 Optimizations["strtof"] = &StrTo;
1572 Optimizations["strtoul"] = &StrTo;
1573 Optimizations["strtoll"] = &StrTo;
1574 Optimizations["strtold"] = &StrTo;
1575 Optimizations["strtoull"] = &StrTo;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001576 Optimizations["memcmp"] = &MemCmp;
1577 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001578 Optimizations["memmove"] = &MemMove;
1579 Optimizations["memset"] = &MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001580
1581 // Math Library Optimizations
1582 Optimizations["powf"] = &Pow;
1583 Optimizations["pow"] = &Pow;
1584 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001585 Optimizations["llvm.pow.f32"] = &Pow;
1586 Optimizations["llvm.pow.f64"] = &Pow;
1587 Optimizations["llvm.pow.f80"] = &Pow;
1588 Optimizations["llvm.pow.f128"] = &Pow;
1589 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001590 Optimizations["exp2l"] = &Exp2;
1591 Optimizations["exp2"] = &Exp2;
1592 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001593 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1594 Optimizations["llvm.exp2.f128"] = &Exp2;
1595 Optimizations["llvm.exp2.f80"] = &Exp2;
1596 Optimizations["llvm.exp2.f64"] = &Exp2;
1597 Optimizations["llvm.exp2.f32"] = &Exp2;
Chris Lattnere818f772008-05-02 18:43:35 +00001598
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001599#ifdef HAVE_FLOORF
1600 Optimizations["floor"] = &UnaryDoubleFP;
1601#endif
1602#ifdef HAVE_CEILF
1603 Optimizations["ceil"] = &UnaryDoubleFP;
1604#endif
1605#ifdef HAVE_ROUNDF
1606 Optimizations["round"] = &UnaryDoubleFP;
1607#endif
1608#ifdef HAVE_RINTF
1609 Optimizations["rint"] = &UnaryDoubleFP;
1610#endif
1611#ifdef HAVE_NEARBYINTF
1612 Optimizations["nearbyint"] = &UnaryDoubleFP;
1613#endif
1614
1615 // Integer Optimizations
1616 Optimizations["ffs"] = &FFS;
1617 Optimizations["ffsl"] = &FFS;
1618 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001619 Optimizations["abs"] = &Abs;
1620 Optimizations["labs"] = &Abs;
1621 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001622 Optimizations["isdigit"] = &IsDigit;
1623 Optimizations["isascii"] = &IsAscii;
1624 Optimizations["toascii"] = &ToAscii;
1625
1626 // Formatting and IO Optimizations
1627 Optimizations["sprintf"] = &SPrintF;
1628 Optimizations["printf"] = &PrintF;
1629 Optimizations["fwrite"] = &FWrite;
1630 Optimizations["fputs"] = &FPuts;
1631 Optimizations["fprintf"] = &FPrintF;
1632}
1633
1634
1635/// runOnFunction - Top level algorithm.
1636///
1637bool SimplifyLibCalls::runOnFunction(Function &F) {
1638 if (Optimizations.empty())
1639 InitOptimizations();
1640
1641 const TargetData &TD = getAnalysis<TargetData>();
1642
Eric Christopher7a61d702008-08-08 19:39:37 +00001643 IRBuilder<> Builder;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001644
1645 bool Changed = false;
1646 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1647 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1648 // Ignore non-calls.
1649 CallInst *CI = dyn_cast<CallInst>(I++);
1650 if (!CI) continue;
1651
1652 // Ignore indirect calls and calls to non-external functions.
1653 Function *Callee = CI->getCalledFunction();
1654 if (Callee == 0 || !Callee->isDeclaration() ||
1655 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1656 continue;
1657
1658 // Ignore unknown calls.
1659 const char *CalleeName = Callee->getNameStart();
1660 StringMap<LibCallOptimization*>::iterator OMI =
1661 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1662 if (OMI == Optimizations.end()) continue;
1663
1664 // Set the builder to the instruction after the call.
1665 Builder.SetInsertPoint(BB, I);
1666
1667 // Try to optimize this call.
1668 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1669 if (Result == 0) continue;
1670
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001671 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1672 DOUT << " into: " << *Result << "\n");
1673
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001674 // Something changed!
1675 Changed = true;
1676 ++NumSimplified;
1677
1678 // Inspect the instruction after the call (which was potentially just
1679 // added) next.
1680 I = CI; ++I;
1681
1682 if (CI != Result && !CI->use_empty()) {
1683 CI->replaceAllUsesWith(Result);
1684 if (!Result->hasName())
1685 Result->takeName(CI);
1686 }
1687 CI->eraseFromParent();
1688 }
1689 }
1690 return Changed;
1691}
1692
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001693// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001694
1695void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1696 if (!F.doesNotAccessMemory()) {
1697 F.setDoesNotAccessMemory();
1698 ++NumAnnotated;
1699 Modified = true;
1700 }
1701}
1702void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1703 if (!F.onlyReadsMemory()) {
1704 F.setOnlyReadsMemory();
1705 ++NumAnnotated;
1706 Modified = true;
1707 }
1708}
1709void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1710 if (!F.doesNotThrow()) {
1711 F.setDoesNotThrow();
1712 ++NumAnnotated;
1713 Modified = true;
1714 }
1715}
1716void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1717 if (!F.doesNotCapture(n)) {
1718 F.setDoesNotCapture(n);
1719 ++NumAnnotated;
1720 Modified = true;
1721 }
1722}
1723void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1724 if (!F.doesNotAlias(n)) {
1725 F.setDoesNotAlias(n);
1726 ++NumAnnotated;
1727 Modified = true;
1728 }
1729}
1730
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001731/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001732///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001733bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001734 Modified = false;
1735 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1736 Function &F = *I;
1737 if (!F.isDeclaration())
1738 continue;
1739
1740 unsigned NameLen = F.getNameLen();
1741 if (!NameLen)
1742 continue;
1743
1744 const FunctionType *FTy = F.getFunctionType();
1745
1746 const char *NameStr = F.getNameStart();
1747 switch (NameStr[0]) {
1748 case 's':
1749 if (NameLen == 6 && !strcmp(NameStr, "strlen")) {
1750 if (FTy->getNumParams() != 1 ||
1751 !isa<PointerType>(FTy->getParamType(0)))
1752 continue;
1753 setOnlyReadsMemory(F);
1754 setDoesNotThrow(F);
1755 setDoesNotCapture(F, 1);
1756 } else if ((NameLen == 6 && !strcmp(NameStr, "strcpy")) ||
1757 (NameLen == 6 && !strcmp(NameStr, "stpcpy")) ||
1758 (NameLen == 6 && !strcmp(NameStr, "strcat")) ||
Nick Lewycky4c498412009-02-13 15:31:46 +00001759 (NameLen == 6 && !strcmp(NameStr, "strtol")) ||
1760 (NameLen == 6 && !strcmp(NameStr, "strtod")) ||
1761 (NameLen == 6 && !strcmp(NameStr, "strtof")) ||
1762 (NameLen == 7 && !strcmp(NameStr, "strtoul")) ||
1763 (NameLen == 7 && !strcmp(NameStr, "strtoll")) ||
1764 (NameLen == 7 && !strcmp(NameStr, "strtold")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001765 (NameLen == 7 && !strcmp(NameStr, "strncat")) ||
Nick Lewycky4c498412009-02-13 15:31:46 +00001766 (NameLen == 7 && !strcmp(NameStr, "strncpy")) ||
1767 (NameLen == 8 && !strcmp(NameStr, "strtoull"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001768 if (FTy->getNumParams() < 2 ||
1769 !isa<PointerType>(FTy->getParamType(1)))
1770 continue;
1771 setDoesNotThrow(F);
1772 setDoesNotCapture(F, 2);
1773 } else if (NameLen == 7 && !strcmp(NameStr, "strxfrm")) {
1774 if (FTy->getNumParams() != 3 ||
1775 !isa<PointerType>(FTy->getParamType(0)) ||
1776 !isa<PointerType>(FTy->getParamType(1)))
1777 continue;
1778 setDoesNotThrow(F);
1779 setDoesNotCapture(F, 1);
1780 setDoesNotCapture(F, 2);
1781 } else if ((NameLen == 6 && !strcmp(NameStr, "strcmp")) ||
1782 (NameLen == 6 && !strcmp(NameStr, "strspn")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001783 (NameLen == 7 && !strcmp(NameStr, "strncmp")) ||
1784 (NameLen == 7 && !strcmp(NameStr, "strcspn")) ||
1785 (NameLen == 7 && !strcmp(NameStr, "strcoll")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001786 (NameLen == 10 && !strcmp(NameStr, "strcasecmp")) ||
1787 (NameLen == 11 && !strcmp(NameStr, "strncasecmp"))) {
1788 if (FTy->getNumParams() < 2 ||
1789 !isa<PointerType>(FTy->getParamType(0)) ||
1790 !isa<PointerType>(FTy->getParamType(1)))
1791 continue;
1792 setOnlyReadsMemory(F);
1793 setDoesNotThrow(F);
1794 setDoesNotCapture(F, 1);
1795 setDoesNotCapture(F, 2);
1796 } else if ((NameLen == 6 && !strcmp(NameStr, "strstr")) ||
1797 (NameLen == 7 && !strcmp(NameStr, "strpbrk"))) {
1798 if (FTy->getNumParams() != 2 ||
1799 !isa<PointerType>(FTy->getParamType(1)))
1800 continue;
1801 setOnlyReadsMemory(F);
1802 setDoesNotThrow(F);
1803 setDoesNotCapture(F, 2);
1804 } else if ((NameLen == 6 && !strcmp(NameStr, "strtok")) ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001805 (NameLen == 8 && !strcmp(NameStr, "strtok_r"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001806 if (FTy->getNumParams() < 2 ||
1807 !isa<PointerType>(FTy->getParamType(1)))
1808 continue;
1809 setDoesNotThrow(F);
1810 setDoesNotCapture(F, 2);
1811 } else if ((NameLen == 5 && !strcmp(NameStr, "scanf")) ||
1812 (NameLen == 6 && !strcmp(NameStr, "setbuf")) ||
1813 (NameLen == 7 && !strcmp(NameStr, "setvbuf"))) {
1814 if (FTy->getNumParams() < 1 ||
1815 !isa<PointerType>(FTy->getParamType(0)))
1816 continue;
1817 setDoesNotThrow(F);
1818 setDoesNotCapture(F, 1);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001819 } else if ((NameLen == 6 && !strcmp(NameStr, "strdup")) ||
1820 (NameLen == 7 && !strcmp(NameStr, "strndup"))) {
1821 if (FTy->getNumParams() < 1 ||
1822 !isa<PointerType>(FTy->getReturnType()) ||
1823 !isa<PointerType>(FTy->getParamType(0)))
1824 continue;
1825 setDoesNotThrow(F);
1826 setDoesNotAlias(F, 0);
1827 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00001828 } else if ((NameLen == 4 && !strcmp(NameStr, "stat")) ||
1829 (NameLen == 6 && !strcmp(NameStr, "sscanf")) ||
1830 (NameLen == 7 && !strcmp(NameStr, "sprintf")) ||
1831 (NameLen == 7 && !strcmp(NameStr, "statvfs"))) {
1832 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001833 !isa<PointerType>(FTy->getParamType(0)) ||
1834 !isa<PointerType>(FTy->getParamType(1)))
1835 continue;
1836 setDoesNotThrow(F);
1837 setDoesNotCapture(F, 1);
1838 setDoesNotCapture(F, 2);
1839 } else if (NameLen == 8 && !strcmp(NameStr, "snprintf")) {
1840 if (FTy->getNumParams() != 3 ||
1841 !isa<PointerType>(FTy->getParamType(0)) ||
1842 !isa<PointerType>(FTy->getParamType(2)))
1843 continue;
1844 setDoesNotThrow(F);
1845 setDoesNotCapture(F, 1);
1846 setDoesNotCapture(F, 3);
Nick Lewycky225f7472009-02-15 22:47:25 +00001847 } else if (NameLen == 9 && !strcmp(NameStr, "setitimer")) {
1848 if (FTy->getNumParams() != 3 ||
1849 !isa<PointerType>(FTy->getParamType(1)) ||
1850 !isa<PointerType>(FTy->getParamType(2)))
1851 continue;
1852 setDoesNotThrow(F);
1853 setDoesNotCapture(F, 2);
1854 setDoesNotCapture(F, 3);
1855 } else if (NameLen == 6 && !strcmp(NameStr, "system")) {
1856 if (FTy->getNumParams() != 1 ||
1857 !isa<PointerType>(FTy->getParamType(0)))
1858 continue;
1859 // May throw; "system" is a valid pthread cancellation point.
1860 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001861 }
1862 break;
1863 case 'm':
1864 if (NameLen == 6 && !strcmp(NameStr, "memcmp")) {
1865 if (FTy->getNumParams() != 3 ||
1866 !isa<PointerType>(FTy->getParamType(0)) ||
1867 !isa<PointerType>(FTy->getParamType(1)))
1868 continue;
1869 setOnlyReadsMemory(F);
1870 setDoesNotThrow(F);
1871 setDoesNotCapture(F, 1);
1872 setDoesNotCapture(F, 2);
1873 } else if ((NameLen == 6 && !strcmp(NameStr, "memchr")) ||
1874 (NameLen == 7 && !strcmp(NameStr, "memrchr"))) {
1875 if (FTy->getNumParams() != 3)
1876 continue;
1877 setOnlyReadsMemory(F);
1878 setDoesNotThrow(F);
Nick Lewycky225f7472009-02-15 22:47:25 +00001879 } else if ((NameLen == 4 && !strcmp(NameStr, "modf")) ||
1880 (NameLen == 5 && !strcmp(NameStr, "modff")) ||
1881 (NameLen == 5 && !strcmp(NameStr, "modfl")) ||
1882 (NameLen == 6 && !strcmp(NameStr, "memcpy")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001883 (NameLen == 7 && !strcmp(NameStr, "memccpy")) ||
1884 (NameLen == 7 && !strcmp(NameStr, "memmove"))) {
Nick Lewycky225f7472009-02-15 22:47:25 +00001885 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001886 !isa<PointerType>(FTy->getParamType(1)))
1887 continue;
1888 setDoesNotThrow(F);
1889 setDoesNotCapture(F, 2);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001890 } else if (NameLen == 8 && !strcmp(NameStr, "memalign")) {
1891 if (!isa<PointerType>(FTy->getReturnType()))
1892 continue;
1893 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00001894 } else if ((NameLen == 5 && !strcmp(NameStr, "mkdir")) ||
1895 (NameLen == 6 && !strcmp(NameStr, "mktime"))) {
1896 if (FTy->getNumParams() == 0 ||
1897 !isa<PointerType>(FTy->getParamType(0)))
1898 continue;
1899 setDoesNotThrow(F);
1900 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001901 }
1902 break;
1903 case 'r':
1904 if (NameLen == 7 && !strcmp(NameStr, "realloc")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001905 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001906 !isa<PointerType>(FTy->getParamType(0)) ||
1907 !isa<PointerType>(FTy->getReturnType()))
1908 continue;
1909 setDoesNotThrow(F);
1910 setDoesNotAlias(F, 0);
1911 setDoesNotCapture(F, 1);
1912 } else if (NameLen == 4 && !strcmp(NameStr, "read")) {
1913 if (FTy->getNumParams() != 3 ||
1914 !isa<PointerType>(FTy->getParamType(1)))
1915 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001916 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001917 setDoesNotCapture(F, 2);
1918 } else if ((NameLen == 5 && !strcmp(NameStr, "rmdir")) ||
1919 (NameLen == 6 && !strcmp(NameStr, "rewind")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00001920 (NameLen == 6 && !strcmp(NameStr, "remove")) ||
1921 (NameLen == 8 && !strcmp(NameStr, "realpath"))) {
1922 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001923 !isa<PointerType>(FTy->getParamType(0)))
1924 continue;
1925 setDoesNotThrow(F);
1926 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00001927 } else if ((NameLen == 6 && !strcmp(NameStr, "rename")) ||
1928 (NameLen == 8 && !strcmp(NameStr, "readlink"))) {
1929 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001930 !isa<PointerType>(FTy->getParamType(0)) ||
1931 !isa<PointerType>(FTy->getParamType(1)))
1932 continue;
1933 setDoesNotThrow(F);
1934 setDoesNotCapture(F, 1);
1935 setDoesNotCapture(F, 2);
1936 }
1937 break;
1938 case 'w':
1939 if (NameLen == 5 && !strcmp(NameStr, "write")) {
1940 if (FTy->getNumParams() != 3 ||
1941 !isa<PointerType>(FTy->getParamType(1)))
1942 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001943 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001944 setDoesNotCapture(F, 2);
1945 }
1946 break;
1947 case 'b':
1948 if (NameLen == 5 && !strcmp(NameStr, "bcopy")) {
1949 if (FTy->getNumParams() != 3 ||
1950 !isa<PointerType>(FTy->getParamType(0)) ||
1951 !isa<PointerType>(FTy->getParamType(1)))
1952 continue;
1953 setDoesNotThrow(F);
1954 setDoesNotCapture(F, 1);
1955 setDoesNotCapture(F, 2);
1956 } else if (NameLen == 4 && !strcmp(NameStr, "bcmp")) {
1957 if (FTy->getNumParams() != 3 ||
1958 !isa<PointerType>(FTy->getParamType(0)) ||
1959 !isa<PointerType>(FTy->getParamType(1)))
1960 continue;
1961 setDoesNotThrow(F);
1962 setOnlyReadsMemory(F);
1963 setDoesNotCapture(F, 1);
1964 setDoesNotCapture(F, 2);
1965 } else if (NameLen == 5 && !strcmp(NameStr, "bzero")) {
1966 if (FTy->getNumParams() != 2 ||
1967 !isa<PointerType>(FTy->getParamType(0)))
1968 continue;
1969 setDoesNotThrow(F);
1970 setDoesNotCapture(F, 1);
1971 }
1972 break;
1973 case 'c':
1974 if (NameLen == 6 && !strcmp(NameStr, "calloc")) {
1975 if (FTy->getNumParams() != 2 ||
1976 !isa<PointerType>(FTy->getReturnType()))
1977 continue;
1978 setDoesNotThrow(F);
1979 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00001980 } else if ((NameLen == 5 && !strcmp(NameStr, "chmod")) ||
1981 (NameLen == 5 && !strcmp(NameStr, "chown")) ||
1982 (NameLen == 7 && !strcmp(NameStr, "ctermid")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001983 (NameLen == 8 && !strcmp(NameStr, "clearerr")) ||
1984 (NameLen == 8 && !strcmp(NameStr, "closedir"))) {
1985 if (FTy->getNumParams() == 0 ||
1986 !isa<PointerType>(FTy->getParamType(0)))
1987 continue;
1988 setDoesNotThrow(F);
1989 setDoesNotCapture(F, 1);
1990 }
1991 break;
1992 case 'a':
1993 if ((NameLen == 4 && !strcmp(NameStr, "atoi")) ||
1994 (NameLen == 4 && !strcmp(NameStr, "atol")) ||
1995 (NameLen == 4 && !strcmp(NameStr, "atof")) ||
1996 (NameLen == 5 && !strcmp(NameStr, "atoll"))) {
1997 if (FTy->getNumParams() != 1 ||
1998 !isa<PointerType>(FTy->getParamType(0)))
1999 continue;
2000 setDoesNotThrow(F);
2001 setOnlyReadsMemory(F);
2002 setDoesNotCapture(F, 1);
2003 } else if (NameLen == 6 && !strcmp(NameStr, "access")) {
2004 if (FTy->getNumParams() != 2 ||
2005 !isa<PointerType>(FTy->getParamType(0)))
2006 continue;
2007 setDoesNotThrow(F);
2008 setDoesNotCapture(F, 1);
2009 }
2010 break;
2011 case 'f':
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002012 if (NameLen == 5 && !strcmp(NameStr, "fopen")) {
2013 if (FTy->getNumParams() != 2 ||
2014 !isa<PointerType>(FTy->getReturnType()) ||
2015 !isa<PointerType>(FTy->getParamType(0)) ||
2016 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002017 continue;
2018 setDoesNotThrow(F);
2019 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002020 setDoesNotCapture(F, 1);
2021 setDoesNotCapture(F, 2);
2022 } else if (NameLen == 6 && !strcmp(NameStr, "fdopen")) {
2023 if (FTy->getNumParams() != 2 ||
2024 !isa<PointerType>(FTy->getReturnType()) ||
2025 !isa<PointerType>(FTy->getParamType(1)))
2026 continue;
2027 setDoesNotThrow(F);
2028 setDoesNotAlias(F, 0);
2029 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002030 } else if ((NameLen == 4 && !strcmp(NameStr, "feof")) ||
2031 (NameLen == 4 && !strcmp(NameStr, "free")) ||
2032 (NameLen == 5 && !strcmp(NameStr, "fseek")) ||
2033 (NameLen == 5 && !strcmp(NameStr, "ftell")) ||
2034 (NameLen == 5 && !strcmp(NameStr, "fgetc")) ||
2035 (NameLen == 6 && !strcmp(NameStr, "fseeko")) ||
2036 (NameLen == 6 && !strcmp(NameStr, "ftello")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002037 (NameLen == 6 && !strcmp(NameStr, "fileno")) ||
2038 (NameLen == 6 && !strcmp(NameStr, "fflush")) ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002039 (NameLen == 6 && !strcmp(NameStr, "fclose")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002040 (NameLen == 7 && !strcmp(NameStr, "fsetpos")) ||
2041 (NameLen == 9 && !strcmp(NameStr, "flockfile")) ||
2042 (NameLen == 11 && !strcmp(NameStr, "funlockfile")) ||
2043 (NameLen == 12 && !strcmp(NameStr, "ftrylockfile"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002044 if (FTy->getNumParams() == 0 ||
2045 !isa<PointerType>(FTy->getParamType(0)))
2046 continue;
2047 setDoesNotThrow(F);
2048 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002049 } else if (NameLen == 6 && !strcmp(NameStr, "ferror")) {
2050 if (FTy->getNumParams() != 1 ||
2051 !isa<PointerType>(FTy->getParamType(0)))
2052 continue;
2053 setDoesNotThrow(F);
2054 setDoesNotCapture(F, 1);
2055 setOnlyReadsMemory(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002056 } else if ((NameLen == 5 && !strcmp(NameStr, "fputc")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002057 (NameLen == 5 && !strcmp(NameStr, "fstat")) ||
2058 (NameLen == 5 && !strcmp(NameStr, "frexp")) ||
2059 (NameLen == 6 && !strcmp(NameStr, "frexpf")) ||
2060 (NameLen == 6 && !strcmp(NameStr, "frexpl")) ||
2061 (NameLen == 8 && !strcmp(NameStr, "fstatvfs"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002062 if (FTy->getNumParams() != 2 ||
2063 !isa<PointerType>(FTy->getParamType(1)))
2064 continue;
2065 setDoesNotThrow(F);
2066 setDoesNotCapture(F, 2);
2067 } else if (NameLen == 5 && !strcmp(NameStr, "fgets")) {
2068 if (FTy->getNumParams() != 3 ||
2069 !isa<PointerType>(FTy->getParamType(0)) ||
2070 !isa<PointerType>(FTy->getParamType(2)))
2071 continue;
2072 setDoesNotThrow(F);
2073 setDoesNotCapture(F, 3);
2074 } else if ((NameLen == 5 && !strcmp(NameStr, "fread")) ||
2075 (NameLen == 6 && !strcmp(NameStr, "fwrite"))) {
2076 if (FTy->getNumParams() != 4 ||
2077 !isa<PointerType>(FTy->getParamType(0)) ||
2078 !isa<PointerType>(FTy->getParamType(3)))
2079 continue;
2080 setDoesNotThrow(F);
2081 setDoesNotCapture(F, 1);
2082 setDoesNotCapture(F, 4);
Nick Lewycky225f7472009-02-15 22:47:25 +00002083 } else if ((NameLen == 5 && !strcmp(NameStr, "fputs")) ||
2084 (NameLen == 6 && !strcmp(NameStr, "fscanf")) ||
2085 (NameLen == 7 && !strcmp(NameStr, "fprintf")) ||
2086 (NameLen == 7 && !strcmp(NameStr, "fgetpos"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002087 if (FTy->getNumParams() < 2 ||
2088 !isa<PointerType>(FTy->getParamType(0)) ||
2089 !isa<PointerType>(FTy->getParamType(1)))
2090 continue;
2091 setDoesNotThrow(F);
2092 setDoesNotCapture(F, 1);
2093 setDoesNotCapture(F, 2);
2094 }
2095 break;
2096 case 'g':
2097 if ((NameLen == 4 && !strcmp(NameStr, "getc")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002098 (NameLen == 10 && !strcmp(NameStr, "getlogin_r")) ||
2099 (NameLen == 13 && !strcmp(NameStr, "getc_unlocked"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002100 if (FTy->getNumParams() == 0 ||
2101 !isa<PointerType>(FTy->getParamType(0)))
2102 continue;
2103 setDoesNotThrow(F);
2104 setDoesNotCapture(F, 1);
2105 } else if (NameLen == 6 && !strcmp(NameStr, "getenv")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002106 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002107 !isa<PointerType>(FTy->getParamType(0)))
2108 continue;
2109 setDoesNotThrow(F);
2110 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002111 setDoesNotCapture(F, 1);
2112 } else if ((NameLen == 4 && !strcmp(NameStr, "gets")) ||
2113 (NameLen == 7 && !strcmp(NameStr, "getchar"))) {
2114 setDoesNotThrow(F);
Nick Lewycky225f7472009-02-15 22:47:25 +00002115 } else if (NameLen == 9 && !strcmp(NameStr, "getitimer")) {
2116 if (FTy->getNumParams() != 2 ||
2117 !isa<PointerType>(FTy->getParamType(1)))
2118 continue;
2119 setDoesNotThrow(F);
2120 setDoesNotCapture(F, 2);
2121 } else if (NameLen == 8 && !strcmp(NameStr, "getpwnam")) {
2122 if (FTy->getNumParams() != 1 ||
2123 !isa<PointerType>(FTy->getParamType(0)))
2124 continue;
2125 setDoesNotThrow(F);
2126 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002127 }
2128 break;
2129 case 'u':
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002130 if (NameLen == 6 && !strcmp(NameStr, "ungetc")) {
2131 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002132 !isa<PointerType>(FTy->getParamType(1)))
2133 continue;
2134 setDoesNotThrow(F);
2135 setDoesNotCapture(F, 2);
Nick Lewycky225f7472009-02-15 22:47:25 +00002136 } else if ((NameLen == 5 && !strcmp(NameStr, "uname")) ||
2137 (NameLen == 6 && !strcmp(NameStr, "unlink")) ||
2138 (NameLen == 8 && !strcmp(NameStr, "unsetenv"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002139 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002140 !isa<PointerType>(FTy->getParamType(0)))
2141 continue;
2142 setDoesNotThrow(F);
2143 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00002144 } else if ((NameLen == 5 && !strcmp(NameStr, "utime")) ||
2145 (NameLen == 6 && !strcmp(NameStr, "utimes"))) {
2146 if (FTy->getNumParams() != 2 ||
2147 !isa<PointerType>(FTy->getParamType(0)) ||
2148 !isa<PointerType>(FTy->getParamType(1)))
2149 continue;
2150 setDoesNotThrow(F);
2151 setDoesNotCapture(F, 1);
2152 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002153 }
2154 break;
2155 case 'p':
2156 if (NameLen == 4 && !strcmp(NameStr, "putc")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002157 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002158 !isa<PointerType>(FTy->getParamType(1)))
2159 continue;
2160 setDoesNotThrow(F);
2161 setDoesNotCapture(F, 2);
2162 } else if ((NameLen == 4 && !strcmp(NameStr, "puts")) ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002163 (NameLen == 6 && !strcmp(NameStr, "printf")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002164 (NameLen == 6 && !strcmp(NameStr, "perror"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002165 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002166 !isa<PointerType>(FTy->getParamType(0)))
2167 continue;
2168 setDoesNotThrow(F);
2169 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002170 } else if ((NameLen == 5 && !strcmp(NameStr, "pread")) ||
2171 (NameLen == 6 && !strcmp(NameStr, "pwrite"))) {
2172 if (FTy->getNumParams() != 4 ||
2173 !isa<PointerType>(FTy->getParamType(1)))
2174 continue;
2175 // May throw; these are valid pthread cancellation points.
2176 setDoesNotCapture(F, 2);
2177 } else if (NameLen == 7 && !strcmp(NameStr, "putchar")) {
2178 setDoesNotThrow(F);
Nick Lewycky225f7472009-02-15 22:47:25 +00002179 } else if (NameLen == 5 && !strcmp(NameStr, "popen")) {
2180 if (FTy->getNumParams() != 2 ||
2181 !isa<PointerType>(FTy->getReturnType()) ||
2182 !isa<PointerType>(FTy->getParamType(0)) ||
2183 !isa<PointerType>(FTy->getParamType(1)))
2184 continue;
2185 setDoesNotThrow(F);
2186 setDoesNotAlias(F, 0);
2187 setDoesNotCapture(F, 1);
2188 setDoesNotCapture(F, 2);
2189 } else if (NameLen == 6 && !strcmp(NameStr, "pclose")) {
2190 if (FTy->getNumParams() != 1 ||
2191 !isa<PointerType>(FTy->getParamType(0)))
2192 continue;
2193 setDoesNotThrow(F);
2194 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002195 }
2196 break;
2197 case 'v':
2198 if (NameLen == 6 && !strcmp(NameStr, "vscanf")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002199 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002200 !isa<PointerType>(FTy->getParamType(1)))
2201 continue;
2202 setDoesNotThrow(F);
2203 setDoesNotCapture(F, 1);
2204 } else if ((NameLen == 7 && !strcmp(NameStr, "vsscanf")) ||
2205 (NameLen == 7 && !strcmp(NameStr, "vfscanf"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002206 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002207 !isa<PointerType>(FTy->getParamType(1)) ||
2208 !isa<PointerType>(FTy->getParamType(2)))
2209 continue;
2210 setDoesNotThrow(F);
2211 setDoesNotCapture(F, 1);
2212 setDoesNotCapture(F, 2);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002213 } else if (NameLen == 6 && !strcmp(NameStr, "valloc")) {
2214 if (!isa<PointerType>(FTy->getReturnType()))
2215 continue;
2216 setDoesNotThrow(F);
2217 setDoesNotAlias(F, 0);
2218 } else if (NameLen == 7 && !strcmp(NameStr, "vprintf")) {
2219 if (FTy->getNumParams() != 2 ||
2220 !isa<PointerType>(FTy->getParamType(0)))
2221 continue;
2222 setDoesNotThrow(F);
2223 setDoesNotCapture(F, 1);
2224 } else if ((NameLen == 8 && !strcmp(NameStr, "vfprintf")) ||
2225 (NameLen == 8 && !strcmp(NameStr, "vsprintf"))) {
2226 if (FTy->getNumParams() != 3 ||
2227 !isa<PointerType>(FTy->getParamType(0)) ||
2228 !isa<PointerType>(FTy->getParamType(1)))
2229 continue;
2230 setDoesNotThrow(F);
2231 setDoesNotCapture(F, 1);
2232 setDoesNotCapture(F, 2);
2233 } else if (NameLen == 9 && !strcmp(NameStr, "vsnprintf")) {
2234 if (FTy->getNumParams() != 4 ||
2235 !isa<PointerType>(FTy->getParamType(0)) ||
2236 !isa<PointerType>(FTy->getParamType(2)))
2237 continue;
2238 setDoesNotThrow(F);
2239 setDoesNotCapture(F, 1);
2240 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002241 }
2242 break;
2243 case 'o':
Nick Lewycky225f7472009-02-15 22:47:25 +00002244 if (NameLen == 4 && !strcmp(NameStr, "open")) {
2245 if (FTy->getNumParams() < 2 ||
2246 !isa<PointerType>(FTy->getParamType(0)))
2247 continue;
2248 // May throw; "open" is a valid pthread cancellation point.
2249 setDoesNotCapture(F, 1);
2250 } else if (NameLen == 7 && !strcmp(NameStr, "opendir")) {
2251 if (FTy->getNumParams() != 1 ||
2252 !isa<PointerType>(FTy->getReturnType()) ||
2253 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002254 continue;
2255 setDoesNotThrow(F);
2256 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002257 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002258 }
2259 break;
2260 case 't':
2261 if (NameLen == 7 && !strcmp(NameStr, "tmpfile")) {
2262 if (!isa<PointerType>(FTy->getReturnType()))
2263 continue;
2264 setDoesNotThrow(F);
2265 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002266 } else if (NameLen == 5 && !strcmp(NameStr, "times")) {
2267 if (FTy->getNumParams() != 1 ||
2268 !isa<PointerType>(FTy->getParamType(0)))
2269 continue;
2270 setDoesNotThrow(F);
2271 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002272 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002273 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002274 case 'h':
2275 if ((NameLen == 5 && !strcmp(NameStr, "htonl")) ||
2276 (NameLen == 5 && !strcmp(NameStr, "htons"))) {
2277 setDoesNotThrow(F);
2278 setDoesNotAccessMemory(F);
2279 }
2280 break;
2281 case 'n':
2282 if ((NameLen == 5 && !strcmp(NameStr, "ntohl")) ||
2283 (NameLen == 5 && !strcmp(NameStr, "ntohs"))) {
2284 setDoesNotThrow(F);
2285 setDoesNotAccessMemory(F);
2286 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002287 break;
2288 case 'l':
2289 if (NameLen == 5 && !strcmp(NameStr, "lstat")) {
2290 if (FTy->getNumParams() != 2 ||
2291 !isa<PointerType>(FTy->getParamType(0)) ||
2292 !isa<PointerType>(FTy->getParamType(1)))
2293 continue;
2294 setDoesNotThrow(F);
2295 setDoesNotCapture(F, 1);
2296 setDoesNotCapture(F, 2);
2297 } else if (NameLen == 6 && !strcmp(NameStr, "lchown")) {
2298 if (FTy->getNumParams() != 3 ||
2299 !isa<PointerType>(FTy->getParamType(0)))
2300 continue;
2301 setDoesNotThrow(F);
2302 setDoesNotCapture(F, 1);
2303 }
2304 break;
2305 case 'q':
2306 if (NameLen == 5 && !strcmp(NameStr, "qsort")) {
2307 if (FTy->getNumParams() != 4 ||
2308 !isa<PointerType>(FTy->getParamType(3)))
2309 continue;
2310 // May throw; places call through function pointer.
2311 setDoesNotCapture(F, 4);
2312 }
2313 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002314 case '_':
2315 if ((NameLen == 8 && !strcmp(NameStr, "__strdup")) ||
2316 (NameLen == 9 && !strcmp(NameStr, "__strndup"))) {
2317 if (FTy->getNumParams() < 1 ||
2318 !isa<PointerType>(FTy->getReturnType()) ||
2319 !isa<PointerType>(FTy->getParamType(0)))
2320 continue;
2321 setDoesNotThrow(F);
2322 setDoesNotAlias(F, 0);
2323 setDoesNotCapture(F, 1);
2324 } else if (NameLen == 10 && !strcmp(NameStr, "__strtok_r")) {
2325 if (FTy->getNumParams() != 3 ||
2326 !isa<PointerType>(FTy->getParamType(1)))
2327 continue;
2328 setDoesNotThrow(F);
2329 setDoesNotCapture(F, 2);
2330 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_getc")) {
2331 if (FTy->getNumParams() != 1 ||
2332 !isa<PointerType>(FTy->getParamType(0)))
2333 continue;
2334 setDoesNotThrow(F);
2335 setDoesNotCapture(F, 1);
2336 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_putc")) {
2337 if (FTy->getNumParams() != 2 ||
2338 !isa<PointerType>(FTy->getParamType(1)))
2339 continue;
2340 setDoesNotThrow(F);
2341 setDoesNotCapture(F, 2);
2342 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002343 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002344 case 1:
2345 if (NameLen == 15 && !strcmp(NameStr, "\1__isoc99_scanf")) {
2346 if (FTy->getNumParams() < 1 ||
2347 !isa<PointerType>(FTy->getParamType(0)))
2348 continue;
2349 setDoesNotThrow(F);
2350 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00002351 } else if ((NameLen == 7 && !strcmp(NameStr, "\1stat64")) ||
2352 (NameLen == 8 && !strcmp(NameStr, "\1lstat64")) ||
2353 (NameLen == 10 && !strcmp(NameStr, "\1statvfs64")) ||
2354 (NameLen == 16 && !strcmp(NameStr, "\1__isoc99_sscanf"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002355 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002356 !isa<PointerType>(FTy->getParamType(0)) ||
2357 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002358 continue;
2359 setDoesNotThrow(F);
2360 setDoesNotCapture(F, 1);
2361 setDoesNotCapture(F, 2);
Nick Lewycky225f7472009-02-15 22:47:25 +00002362 } else if (NameLen == 8 && !strcmp(NameStr, "\1fopen64")) {
2363 if (FTy->getNumParams() != 2 ||
2364 !isa<PointerType>(FTy->getReturnType()) ||
2365 !isa<PointerType>(FTy->getParamType(0)) ||
2366 !isa<PointerType>(FTy->getParamType(1)))
2367 continue;
2368 setDoesNotThrow(F);
2369 setDoesNotAlias(F, 0);
2370 setDoesNotCapture(F, 1);
2371 setDoesNotCapture(F, 2);
2372 } else if ((NameLen == 9 && !strcmp(NameStr, "\1fseeko64")) ||
2373 (NameLen == 9 && !strcmp(NameStr, "\1ftello64"))) {
2374 if (FTy->getNumParams() == 0 ||
2375 !isa<PointerType>(FTy->getParamType(0)))
2376 continue;
2377 setDoesNotThrow(F);
2378 setDoesNotCapture(F, 1);
2379 } else if (NameLen == 10 && !strcmp(NameStr, "\1tmpfile64")) {
2380 if (!isa<PointerType>(FTy->getReturnType()))
2381 continue;
2382 setDoesNotThrow(F);
2383 setDoesNotAlias(F, 0);
2384 } else if ((NameLen == 8 && !strcmp(NameStr, "\1fstat64")) ||
2385 (NameLen == 11 && !strcmp(NameStr, "\1fstatvfs64"))) {
2386 if (FTy->getNumParams() != 2 ||
2387 !isa<PointerType>(FTy->getParamType(1)))
2388 continue;
2389 setDoesNotThrow(F);
2390 setDoesNotCapture(F, 2);
2391 } else if (NameLen == 7 && !strcmp(NameStr, "\1open64")) {
2392 if (FTy->getNumParams() < 2 ||
2393 !isa<PointerType>(FTy->getParamType(0)))
2394 continue;
2395 // May throw; "open" is a valid pthread cancellation point.
2396 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002397 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002398 break;
2399 }
2400 }
2401 return Modified;
2402}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002403
2404// TODO:
2405// Additional cases that we need to add to this file:
2406//
2407// cbrt:
2408// * cbrt(expN(X)) -> expN(x/3)
2409// * cbrt(sqrt(x)) -> pow(x,1/6)
2410// * cbrt(sqrt(x)) -> pow(x,1/9)
2411//
2412// cos, cosf, cosl:
2413// * cos(-x) -> cos(x)
2414//
2415// exp, expf, expl:
2416// * exp(log(x)) -> x
2417//
2418// log, logf, logl:
2419// * log(exp(x)) -> x
2420// * log(x**y) -> y*log(x)
2421// * log(exp(y)) -> y*log(e)
2422// * log(exp2(y)) -> y*log(2)
2423// * log(exp10(y)) -> y*log(10)
2424// * log(sqrt(x)) -> 0.5*log(x)
2425// * log(pow(x,y)) -> y*log(x)
2426//
2427// lround, lroundf, lroundl:
2428// * lround(cnst) -> cnst'
2429//
2430// memcmp:
2431// * memcmp(x,y,l) -> cnst
2432// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2433//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002434// pow, powf, powl:
2435// * pow(exp(x),y) -> exp(x*y)
2436// * pow(sqrt(x),y) -> pow(x,y*0.5)
2437// * pow(pow(x,y),z)-> pow(x,y*z)
2438//
2439// puts:
2440// * puts("") -> putchar("\n")
2441//
2442// round, roundf, roundl:
2443// * round(cnst) -> cnst'
2444//
2445// signbit:
2446// * signbit(cnst) -> cnst'
2447// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2448//
2449// sqrt, sqrtf, sqrtl:
2450// * sqrt(expN(x)) -> expN(x*0.5)
2451// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2452// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2453//
2454// stpcpy:
2455// * stpcpy(str, "literal") ->
2456// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2457// strrchr:
2458// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2459// (if c is a constant integer and s is a constant string)
2460// * strrchr(s1,0) -> strchr(s1,0)
2461//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002462// strpbrk:
2463// * strpbrk(s,a) -> offset_in_for(s,a)
2464// (if s and a are both constant strings)
2465// * strpbrk(s,"") -> 0
2466// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2467//
2468// strspn, strcspn:
2469// * strspn(s,a) -> const_int (if both args are constant)
2470// * strspn("",a) -> 0
2471// * strspn(s,"") -> 0
2472// * strcspn(s,a) -> const_int (if both args are constant)
2473// * strcspn("",a) -> 0
2474// * strcspn(s,"") -> strlen(a)
2475//
2476// strstr:
2477// * strstr(x,x) -> x
2478// * strstr(s1,s2) -> offset_of_s2_in(s1)
2479// (if s1 and s2 are constant strings)
2480//
2481// tan, tanf, tanl:
2482// * tan(atan(x)) -> x
2483//
2484// trunc, truncf, truncl:
2485// * trunc(cnst) -> cnst'
2486//
2487//