blob: 14212bc5799eb63c4385b7d8a56b8b8bcbdab25e [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"
Daniel Dunbarf0443c12009-07-26 08:34:35 +000034#include "llvm/Support/raw_ostream.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000035#include "llvm/Config/config.h"
36using namespace llvm;
37
38STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000039STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000040
41//===----------------------------------------------------------------------===//
42// Optimizer Base Class
43//===----------------------------------------------------------------------===//
44
45/// This class is the abstract base class for the set of optimizations that
46/// corresponds to one library call.
47namespace {
48class VISIBILITY_HIDDEN LibCallOptimization {
49protected:
50 Function *Caller;
51 const TargetData *TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000052 LLVMContext* Context;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000053public:
54 LibCallOptimization() { }
55 virtual ~LibCallOptimization() {}
56
57 /// CallOptimizer - This pure virtual method is implemented by base classes to
58 /// do various optimizations. If this returns null then no transformation was
59 /// performed. If it returns CI, then it transformed the call and CI is to be
60 /// deleted. If it returns something else, replace CI with the new value and
61 /// delete CI.
Eric Christopher7a61d702008-08-08 19:39:37 +000062 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
63 =0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000064
Eric Christopher7a61d702008-08-08 19:39:37 +000065 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000066 Caller = CI->getParent()->getParent();
67 this->TD = &TD;
Owen Andersonfa5cbd62009-07-03 19:42:02 +000068 if (CI->getCalledFunction())
Owen Andersone922c022009-07-22 00:24:57 +000069 Context = &CI->getCalledFunction()->getContext();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000070 return CallOptimizer(CI->getCalledFunction(), CI, B);
71 }
72
73 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +000074 Value *CastToCStr(Value *V, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000075
76 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
77 /// specified pointer. Ptr is required to be some pointer type, and the
78 /// return value has 'intptr_t' type.
Eric Christopher7a61d702008-08-08 19:39:37 +000079 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000080
81 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
82 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
83 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +000084 unsigned Align, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000085
86 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
87 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
Eric Christopher7a61d702008-08-08 19:39:37 +000088 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +000089
90 /// EmitMemCmp - Emit a call to the memcmp function.
91 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
92
Chris Lattnerf5b6bc72009-04-12 05:06:39 +000093 /// EmitMemSet - Emit a call to the memset function
94 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
95
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000096 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
97 /// 'floor'). This function is known to take a single of type matching 'Op'
98 /// and returns one value with the same type. If 'Op' is a long double, 'l'
99 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
Eric Christopher7a61d702008-08-08 19:39:37 +0000100 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000101
102 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
103 /// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000104 void EmitPutChar(Value *Char, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000105
106 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
107 /// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000108 void EmitPutS(Value *Str, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000109
110 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
111 /// an i32, and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000112 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000113
114 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
115 /// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000116 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000117
118 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
119 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000120 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000121
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000122};
123} // End anonymous namespace.
124
125/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +0000126Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000127 return
128 B.CreateBitCast(V, Context->getPointerTypeUnqual(Type::Int8Ty), "cstr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000129}
130
131/// EmitStrLen - Emit a call to the strlen function to the builder, for the
132/// specified pointer. This always returns an integer value of size intptr_t.
Eric Christopher7a61d702008-08-08 19:39:37 +0000133Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000134 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000135 AttributeWithIndex AWI[2];
136 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
137 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
138 Attribute::NoUnwind);
139
140 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
141 TD->getIntPtrType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000142 Context->getPointerTypeUnqual(Type::Int8Ty),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000143 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000144 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
145 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
146 CI->setCallingConv(F->getCallingConv());
147
148 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000149}
150
151/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
152/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
153Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +0000154 unsigned Align, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000155 Module *M = Caller->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +0000156 Intrinsic::ID IID = Intrinsic::memcpy;
157 const Type *Tys[1];
158 Tys[0] = Len->getType();
159 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000160 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
Owen Andersoneed707b2009-07-24 23:12:02 +0000161 ConstantInt::get(Type::Int32Ty, Align));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000162}
163
164/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
165/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
166Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
Eric Christopher7a61d702008-08-08 19:39:37 +0000167 Value *Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000168 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000169 AttributeWithIndex AWI;
170 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
171
172 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000173 Context->getPointerTypeUnqual(Type::Int8Ty),
174 Context->getPointerTypeUnqual(Type::Int8Ty),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000175 Type::Int32Ty, TD->getIntPtrType(),
176 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000177 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
178
179 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
180 CI->setCallingConv(F->getCallingConv());
181
182 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000183}
184
Nick Lewycky13a09e22008-12-21 00:19:21 +0000185/// EmitMemCmp - Emit a call to the memcmp function.
186Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
187 Value *Len, IRBuilder<> &B) {
188 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000189 AttributeWithIndex AWI[3];
190 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
191 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
192 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
193 Attribute::NoUnwind);
194
195 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
Nick Lewycky13a09e22008-12-21 00:19:21 +0000196 Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000197 Context->getPointerTypeUnqual(Type::Int8Ty),
198 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky13a09e22008-12-21 00:19:21 +0000199 TD->getIntPtrType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000200 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
201 Len, "memcmp");
202
203 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
204 CI->setCallingConv(F->getCallingConv());
205
206 return CI;
Nick Lewycky13a09e22008-12-21 00:19:21 +0000207}
208
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000209/// EmitMemSet - Emit a call to the memset function
210Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
211 Value *Len, IRBuilder<> &B) {
212 Module *M = Caller->getParent();
213 Intrinsic::ID IID = Intrinsic::memset;
214 const Type *Tys[1];
215 Tys[0] = Len->getType();
216 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
Owen Andersoneed707b2009-07-24 23:12:02 +0000217 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000218 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
219}
220
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000221/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
222/// 'floor'). This function is known to take a single of type matching 'Op' and
223/// returns one value with the same type. If 'Op' is a long double, 'l' is
224/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
225Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
Eric Christopher7a61d702008-08-08 19:39:37 +0000226 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000227 char NameBuffer[20];
228 if (Op->getType() != Type::DoubleTy) {
229 // If we need to add a suffix, copy into NameBuffer.
230 unsigned NameLen = strlen(Name);
231 assert(NameLen < sizeof(NameBuffer)-2);
232 memcpy(NameBuffer, Name, NameLen);
233 if (Op->getType() == Type::FloatTy)
234 NameBuffer[NameLen] = 'f'; // floorf
235 else
236 NameBuffer[NameLen] = 'l'; // floorl
237 NameBuffer[NameLen+1] = 0;
238 Name = NameBuffer;
239 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000240
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000241 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000242 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000243 Op->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000244 CallInst *CI = B.CreateCall(Callee, Op, Name);
245
246 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
247 CI->setCallingConv(F->getCallingConv());
248
249 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000250}
251
252/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
253/// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000254void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000255 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000256 Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
257 Type::Int32Ty, NULL);
258 CallInst *CI = B.CreateCall(PutChar,
259 B.CreateIntCast(Char, Type::Int32Ty, "chari"),
260 "putchar");
261
262 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
263 CI->setCallingConv(F->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000264}
265
266/// EmitPutS - Emit a call to the puts function. This assumes that Str is
267/// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000268void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000269 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000270 AttributeWithIndex AWI[2];
271 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
272 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
273
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000274 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
275 Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000276 Context->getPointerTypeUnqual(Type::Int8Ty),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000277 NULL);
278 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
279 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
280 CI->setCallingConv(F->getCallingConv());
281
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000282}
283
284/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
285/// an integer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000286void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000287 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000288 AttributeWithIndex AWI[2];
289 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
290 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
291 Constant *F;
292 if (isa<PointerType>(File->getType()))
293 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
294 Type::Int32Ty, File->getType(), NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000295 else
296 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
297 File->getType(), NULL);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000298 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000299 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
300
301 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
302 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000303}
304
305/// EmitFPutS - Emit a call to the puts function. Str is required to be a
306/// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000307void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000308 Module *M = Caller->getParent();
Nick Lewycky225f7472009-02-15 22:47:25 +0000309 AttributeWithIndex AWI[3];
310 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
311 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
312 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000313 Constant *F;
314 if (isa<PointerType>(File->getType()))
Nick Lewycky225f7472009-02-15 22:47:25 +0000315 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000316 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000317 File->getType(), NULL);
318 else
319 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000320 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000321 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000322 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
323
324 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
325 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000326}
327
328/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
329/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
330void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
Eric Christopher7a61d702008-08-08 19:39:37 +0000331 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000332 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000333 AttributeWithIndex AWI[3];
334 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
335 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
336 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
337 Constant *F;
338 if (isa<PointerType>(File->getType()))
339 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
340 TD->getIntPtrType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000341 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000342 TD->getIntPtrType(), TD->getIntPtrType(),
343 File->getType(), NULL);
344 else
345 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000346 Context->getPointerTypeUnqual(Type::Int8Ty),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000347 TD->getIntPtrType(), TD->getIntPtrType(),
348 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000349 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
Owen Andersoneed707b2009-07-24 23:12:02 +0000350 ConstantInt::get(TD->getIntPtrType(), 1), File);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000351
352 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
353 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000354}
355
356//===----------------------------------------------------------------------===//
357// Helper Functions
358//===----------------------------------------------------------------------===//
359
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000360/// GetStringLengthH - If we can compute the length of the string pointed to by
361/// the specified pointer, return 'len+1'. If we can't, return 0.
362static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
363 // Look through noop bitcast instructions.
364 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
365 return GetStringLengthH(BCI->getOperand(0), PHIs);
366
367 // If this is a PHI node, there are two cases: either we have already seen it
368 // or we haven't.
369 if (PHINode *PN = dyn_cast<PHINode>(V)) {
370 if (!PHIs.insert(PN))
371 return ~0ULL; // already in the set.
372
373 // If it was new, see if all the input strings are the same length.
374 uint64_t LenSoFar = ~0ULL;
375 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
376 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
377 if (Len == 0) return 0; // Unknown length -> unknown.
378
379 if (Len == ~0ULL) continue;
380
381 if (Len != LenSoFar && LenSoFar != ~0ULL)
382 return 0; // Disagree -> unknown.
383 LenSoFar = Len;
384 }
385
386 // Success, all agree.
387 return LenSoFar;
388 }
389
390 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
391 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
392 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
393 if (Len1 == 0) return 0;
394 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
395 if (Len2 == 0) return 0;
396 if (Len1 == ~0ULL) return Len2;
397 if (Len2 == ~0ULL) return Len1;
398 if (Len1 != Len2) return 0;
399 return Len1;
400 }
401
402 // If the value is not a GEP instruction nor a constant expression with a
403 // GEP instruction, then return unknown.
404 User *GEP = 0;
405 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
406 GEP = GEPI;
407 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
408 if (CE->getOpcode() != Instruction::GetElementPtr)
409 return 0;
410 GEP = CE;
411 } else {
412 return 0;
413 }
414
415 // Make sure the GEP has exactly three arguments.
416 if (GEP->getNumOperands() != 3)
417 return 0;
418
419 // Check to make sure that the first operand of the GEP is an integer and
420 // has value 0 so that we are sure we're indexing into the initializer.
421 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
422 if (!Idx->isZero())
423 return 0;
424 } else
425 return 0;
426
427 // If the second index isn't a ConstantInt, then this is a variable index
428 // into the array. If this occurs, we can't say anything meaningful about
429 // the string.
430 uint64_t StartIdx = 0;
431 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
432 StartIdx = CI->getZExtValue();
433 else
434 return 0;
435
436 // The GEP instruction, constant or instruction, must reference a global
437 // variable that is a constant and is initialized. The referenced constant
438 // initializer is the array that we'll use for optimization.
439 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
440 if (!GV || !GV->isConstant() || !GV->hasInitializer())
441 return 0;
442 Constant *GlobalInit = GV->getInitializer();
443
444 // Handle the ConstantAggregateZero case, which is a degenerate case. The
445 // initializer is constant zero so the length of the string must be zero.
446 if (isa<ConstantAggregateZero>(GlobalInit))
447 return 1; // Len = 0 offset by 1.
448
449 // Must be a Constant Array
450 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
451 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
452 return false;
453
454 // Get the number of elements in the array
455 uint64_t NumElts = Array->getType()->getNumElements();
456
457 // Traverse the constant array from StartIdx (derived above) which is
458 // the place the GEP refers to in the array.
459 for (unsigned i = StartIdx; i != NumElts; ++i) {
460 Constant *Elt = Array->getOperand(i);
461 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
462 if (!CI) // This array isn't suitable, non-int initializer.
463 return 0;
464 if (CI->isZero())
465 return i-StartIdx+1; // We found end of string, success!
466 }
467
468 return 0; // The array isn't null terminated, conservatively return 'unknown'.
469}
470
471/// GetStringLength - If we can compute the length of the string pointed to by
472/// the specified pointer, return 'len+1'. If we can't, return 0.
473static uint64_t GetStringLength(Value *V) {
474 if (!isa<PointerType>(V->getType())) return 0;
475
476 SmallPtrSet<PHINode*, 32> PHIs;
477 uint64_t Len = GetStringLengthH(V, PHIs);
478 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
479 // an empty string as a length.
480 return Len == ~0ULL ? 1 : Len;
481}
482
483/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
484/// value is equal or not-equal to zero.
485static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
486 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
487 UI != E; ++UI) {
488 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
489 if (IC->isEquality())
490 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
491 if (C->isNullValue())
492 continue;
493 // Unknown instruction.
494 return false;
495 }
496 return true;
497}
498
499//===----------------------------------------------------------------------===//
500// Miscellaneous LibCall Optimizations
501//===----------------------------------------------------------------------===//
502
Bill Wendlingac178222008-05-05 21:37:59 +0000503namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000504//===---------------------------------------===//
505// 'exit' Optimizations
506
507/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
508struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000509 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000510 // Verify we have a reasonable prototype for exit.
511 if (Callee->arg_size() == 0 || !CI->use_empty())
512 return 0;
513
514 // Verify the caller is main, and that the result type of main matches the
515 // argument type of exit.
Daniel Dunbar03d76512009-07-25 23:55:21 +0000516 if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000517 Caller->getReturnType() != CI->getOperand(1)->getType())
518 return 0;
519
520 TerminatorInst *OldTI = CI->getParent()->getTerminator();
521
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000522 // Drop all successor phi node entries.
523 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
524 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
525
Nick Lewycky0efa9212009-07-29 05:17:50 +0000526 // Split the basic block after the call to exit.
527 BasicBlock::iterator FirstDead = CI; ++FirstDead;
528 CI->getParent()->splitBasicBlock(FirstDead);
529 B.SetInsertPoint(B.GetInsertBlock());
530
531 // Remove the branch that splitBB created and insert a return instead.
532 CI->getParent()->getTerminator()->eraseFromParent();
533 B.CreateRet(CI->getOperand(1));
534
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000535 return CI;
536 }
537};
538
539//===----------------------------------------------------------------------===//
540// String and Memory LibCall Optimizations
541//===----------------------------------------------------------------------===//
542
543//===---------------------------------------===//
544// 'strcat' Optimizations
545
546struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000547 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000548 // Verify the "strcat" function prototype.
549 const FunctionType *FT = Callee->getFunctionType();
550 if (FT->getNumParams() != 2 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000551 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000552 FT->getParamType(0) != FT->getReturnType() ||
553 FT->getParamType(1) != FT->getReturnType())
554 return 0;
555
556 // Extract some information from the instruction
557 Value *Dst = CI->getOperand(1);
558 Value *Src = CI->getOperand(2);
559
560 // See if we can get the length of the input string.
561 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000562 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000563 --Len; // Unbias length.
564
565 // Handle the simple, do-nothing case: strcat(x, "") -> x
566 if (Len == 0)
567 return Dst;
568
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000569 EmitStrLenMemCpy(Src, Dst, Len, B);
570 return Dst;
571 }
572
573 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000574 // We need to find the end of the destination string. That's where the
575 // memory is to be moved to. We just generate a call to strlen.
576 Value *DstLen = EmitStrLen(Dst, B);
577
578 // Now that we have the destination's length, we must index into the
579 // destination's pointer to get the actual memcpy destination (end of
580 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000581 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000582
583 // We have enough information to now generate the memcpy call to do the
584 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000585 EmitMemCpy(CpyDst, Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000586 ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000587 }
588};
589
590//===---------------------------------------===//
591// 'strncat' Optimizations
592
593struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
594 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
595 // Verify the "strncat" function prototype.
596 const FunctionType *FT = Callee->getFunctionType();
597 if (FT->getNumParams() != 3 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000598 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000599 FT->getParamType(0) != FT->getReturnType() ||
600 FT->getParamType(1) != FT->getReturnType() ||
601 !isa<IntegerType>(FT->getParamType(2)))
602 return 0;
603
604 // Extract some information from the instruction
605 Value *Dst = CI->getOperand(1);
606 Value *Src = CI->getOperand(2);
607 uint64_t Len;
608
609 // We don't do anything if length is not constant
610 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
611 Len = LengthArg->getZExtValue();
612 else
613 return 0;
614
615 // See if we can get the length of the input string.
616 uint64_t SrcLen = GetStringLength(Src);
617 if (SrcLen == 0) return 0;
618 --SrcLen; // Unbias length.
619
620 // Handle the simple, do-nothing cases:
621 // strncat(x, "", c) -> x
622 // strncat(x, c, 0) -> x
623 if (SrcLen == 0 || Len == 0) return Dst;
624
625 // We don't optimize this case
626 if (Len < SrcLen) return 0;
627
628 // strncat(x, s, c) -> strcat(x, s)
629 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000630 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000631 return Dst;
632 }
633};
634
635//===---------------------------------------===//
636// 'strchr' Optimizations
637
638struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000639 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000640 // Verify the "strchr" function prototype.
641 const FunctionType *FT = Callee->getFunctionType();
642 if (FT->getNumParams() != 2 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000643 FT->getReturnType() != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000644 FT->getParamType(0) != FT->getReturnType())
645 return 0;
646
647 Value *SrcStr = CI->getOperand(1);
648
649 // If the second operand is non-constant, see if we can compute the length
650 // of the input string and turn this into memchr.
651 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
652 if (CharC == 0) {
653 uint64_t Len = GetStringLength(SrcStr);
654 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
655 return 0;
656
657 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
Owen Andersoneed707b2009-07-24 23:12:02 +0000658 ConstantInt::get(TD->getIntPtrType(), Len), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000659 }
660
661 // Otherwise, the character is a constant, see if the first argument is
662 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000663 std::string Str;
664 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000665 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000666
667 // strchr can find the nul character.
668 Str += '\0';
669 char CharValue = CharC->getSExtValue();
670
671 // Compute the offset.
672 uint64_t i = 0;
673 while (1) {
674 if (i == Str.size()) // Didn't find the char. strchr returns null.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000675 return Context->getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000676 // Did we find our match?
677 if (Str[i] == CharValue)
678 break;
679 ++i;
680 }
681
682 // strchr(s+n,c) -> gep(s+n+i,c)
Owen Andersoneed707b2009-07-24 23:12:02 +0000683 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000684 return B.CreateGEP(SrcStr, Idx, "strchr");
685 }
686};
687
688//===---------------------------------------===//
689// 'strcmp' Optimizations
690
691struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000692 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000693 // Verify the "strcmp" function prototype.
694 const FunctionType *FT = Callee->getFunctionType();
695 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
696 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000697 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000698 return 0;
699
700 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
701 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000702 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000703
Bill Wendling0582ae92009-03-13 04:39:26 +0000704 std::string Str1, Str2;
705 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
706 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
707
708 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000709 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
710
Bill Wendling0582ae92009-03-13 04:39:26 +0000711 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000712 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
713
714 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000715 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000716 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000717 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000718
719 // strcmp(P, "x") -> memcmp(P, "x", 2)
720 uint64_t Len1 = GetStringLength(Str1P);
721 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000722 if (Len1 && Len2) {
Nick Lewycky13a09e22008-12-21 00:19:21 +0000723 return EmitMemCmp(Str1P, Str2P,
Owen Andersoneed707b2009-07-24 23:12:02 +0000724 ConstantInt::get(TD->getIntPtrType(),
Chris Lattner849832c2009-06-19 04:17:36 +0000725 std::min(Len1, Len2)), B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000726 }
727
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000728 return 0;
729 }
730};
731
732//===---------------------------------------===//
733// 'strncmp' Optimizations
734
735struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000736 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000737 // Verify the "strncmp" function prototype.
738 const FunctionType *FT = Callee->getFunctionType();
739 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
740 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000741 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000742 !isa<IntegerType>(FT->getParamType(2)))
743 return 0;
744
745 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
746 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000747 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000748
749 // Get the length argument if it is constant.
750 uint64_t Length;
751 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
752 Length = LengthArg->getZExtValue();
753 else
754 return 0;
755
756 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000757 return ConstantInt::get(CI->getType(), 0);
Bill Wendling0582ae92009-03-13 04:39:26 +0000758
759 std::string Str1, Str2;
760 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
761 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
762
763 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000764 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
765
Bill Wendling0582ae92009-03-13 04:39:26 +0000766 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000767 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
768
769 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000770 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000771 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000772 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000773 return 0;
774 }
775};
776
777
778//===---------------------------------------===//
779// 'strcpy' Optimizations
780
781struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000782 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000783 // Verify the "strcpy" function prototype.
784 const FunctionType *FT = Callee->getFunctionType();
785 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
786 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000787 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000788 return 0;
789
790 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
791 if (Dst == Src) // strcpy(x,x) -> x
792 return Src;
793
794 // See if we can get the length of the input string.
795 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000796 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000797
798 // We have enough information to now generate the memcpy call to do the
799 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000800 EmitMemCpy(Dst, Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000801 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000802 return Dst;
803 }
804};
805
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000806//===---------------------------------------===//
807// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000808
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000809struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
810 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
811 const FunctionType *FT = Callee->getFunctionType();
812 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
813 FT->getParamType(0) != FT->getParamType(1) ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000814 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000815 !isa<IntegerType>(FT->getParamType(2)))
816 return 0;
817
818 Value *Dst = CI->getOperand(1);
819 Value *Src = CI->getOperand(2);
820 Value *LenOp = CI->getOperand(3);
821
822 // See if we can get the length of the input string.
823 uint64_t SrcLen = GetStringLength(Src);
824 if (SrcLen == 0) return 0;
825 --SrcLen;
826
827 if (SrcLen == 0) {
828 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Owen Andersoneed707b2009-07-24 23:12:02 +0000829 EmitMemSet(Dst, ConstantInt::get(Type::Int8Ty, '\0'), LenOp, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000830 return Dst;
831 }
832
833 uint64_t Len;
834 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
835 Len = LengthArg->getZExtValue();
836 else
837 return 0;
838
839 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
840
841 // Let strncpy handle the zero padding
842 if (Len > SrcLen+1) return 0;
843
844 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000845 EmitMemCpy(Dst, Src,
Owen Andersoneed707b2009-07-24 23:12:02 +0000846 ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000847
848 return Dst;
849 }
850};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000851
852//===---------------------------------------===//
853// 'strlen' Optimizations
854
855struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000856 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000857 const FunctionType *FT = Callee->getFunctionType();
858 if (FT->getNumParams() != 1 ||
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000859 FT->getParamType(0) != Context->getPointerTypeUnqual(Type::Int8Ty) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000860 !isa<IntegerType>(FT->getReturnType()))
861 return 0;
862
863 Value *Src = CI->getOperand(1);
864
865 // Constant folding: strlen("xyz") -> 3
866 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000867 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000868
869 // Handle strlen(p) != 0.
870 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
871
872 // strlen(x) != 0 --> *x != 0
873 // strlen(x) == 0 --> *x == 0
874 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
875 }
876};
877
878//===---------------------------------------===//
Nick Lewycky4c498412009-02-13 15:31:46 +0000879// 'strto*' Optimizations
880
881struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
882 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
883 const FunctionType *FT = Callee->getFunctionType();
884 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
885 !isa<PointerType>(FT->getParamType(0)) ||
886 !isa<PointerType>(FT->getParamType(1)))
887 return 0;
888
889 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000890 if (isa<ConstantPointerNull>(EndPtr)) {
891 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000892 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000893 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000894
895 return 0;
896 }
897};
898
899
900//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000901// 'memcmp' Optimizations
902
903struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000904 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000905 const FunctionType *FT = Callee->getFunctionType();
906 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
907 !isa<PointerType>(FT->getParamType(1)) ||
908 FT->getReturnType() != Type::Int32Ty)
909 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000910
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000911 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000912
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000913 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000914 return Context->getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000915
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000916 // Make sure we have a constant length.
917 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000918 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000919 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000920
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000921 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000922 return Context->getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000923
924 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
925 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
926 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +0000927 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000928 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000929
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000930 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
931 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
932 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000933 const Type *PTy = Context->getPointerTypeUnqual(Len == 2 ?
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000934 Type::Int16Ty : Type::Int32Ty);
935 LHS = B.CreateBitCast(LHS, PTy, "tmp");
936 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000937 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
938 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
939 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
940 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
941 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000942
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000943 return 0;
944 }
945};
946
947//===---------------------------------------===//
948// 'memcpy' Optimizations
949
950struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000951 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000952 const FunctionType *FT = Callee->getFunctionType();
953 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
954 !isa<PointerType>(FT->getParamType(0)) ||
955 !isa<PointerType>(FT->getParamType(1)) ||
956 FT->getParamType(2) != TD->getIntPtrType())
957 return 0;
958
959 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
960 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
961 return CI->getOperand(1);
962 }
963};
964
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000965//===---------------------------------------===//
966// 'memmove' Optimizations
967
968struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
969 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
970 const FunctionType *FT = Callee->getFunctionType();
971 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
972 !isa<PointerType>(FT->getParamType(0)) ||
973 !isa<PointerType>(FT->getParamType(1)) ||
974 FT->getParamType(2) != TD->getIntPtrType())
975 return 0;
976
977 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
978 Module *M = Caller->getParent();
979 Intrinsic::ID IID = Intrinsic::memmove;
980 const Type *Tys[1];
981 Tys[0] = TD->getIntPtrType();
982 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
983 Value *Dst = CastToCStr(CI->getOperand(1), B);
984 Value *Src = CastToCStr(CI->getOperand(2), B);
985 Value *Size = CI->getOperand(3);
Owen Andersoneed707b2009-07-24 23:12:02 +0000986 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000987 B.CreateCall4(MemMove, Dst, Src, Size, Align);
988 return CI->getOperand(1);
989 }
990};
991
992//===---------------------------------------===//
993// 'memset' Optimizations
994
995struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
996 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
997 const FunctionType *FT = Callee->getFunctionType();
998 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
999 !isa<PointerType>(FT->getParamType(0)) ||
Eli Friedman62bb4132009-07-18 08:34:51 +00001000 !isa<IntegerType>(FT->getParamType(1)) ||
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001001 FT->getParamType(2) != TD->getIntPtrType())
1002 return 0;
1003
1004 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Eli Friedman62bb4132009-07-18 08:34:51 +00001005 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::Int8Ty, false);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001006 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001007 return CI->getOperand(1);
1008 }
1009};
1010
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001011//===----------------------------------------------------------------------===//
1012// Math Library Optimizations
1013//===----------------------------------------------------------------------===//
1014
1015//===---------------------------------------===//
1016// 'pow*' Optimizations
1017
1018struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001019 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001020 const FunctionType *FT = Callee->getFunctionType();
1021 // Just make sure this has 2 arguments of the same FP type, which match the
1022 // result type.
1023 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1024 FT->getParamType(0) != FT->getParamType(1) ||
1025 !FT->getParamType(0)->isFloatingPoint())
1026 return 0;
1027
1028 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1029 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1030 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1031 return Op1C;
1032 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1033 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1034 }
1035
1036 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1037 if (Op2C == 0) return 0;
1038
1039 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001040 return ConstantFP::get(CI->getType(), 1.0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001041
1042 if (Op2C->isExactlyValue(0.5)) {
1043 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1044 // 'unsafe' math optimizations are allowed.
1045 // x pow(x, 0.5) sqrt(x)
1046 // ---------------------------------------------
1047 // -0.0 +0.0 -0.0
1048 // -inf +inf NaN
1049#if 0
1050 // pow(x, 0.5) -> sqrt(x)
1051 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1052#endif
1053 }
1054
1055 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1056 return Op1;
1057 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001058 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001059 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001060 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001061 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001062 return 0;
1063 }
1064};
1065
1066//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001067// 'exp2' Optimizations
1068
1069struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001070 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001071 const FunctionType *FT = Callee->getFunctionType();
1072 // Just make sure this has 1 argument of FP type, which matches the
1073 // result type.
1074 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1075 !FT->getParamType(0)->isFloatingPoint())
1076 return 0;
1077
1078 Value *Op = CI->getOperand(1);
1079 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1080 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1081 Value *LdExpArg = 0;
1082 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1083 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1084 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1085 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1086 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1087 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1088 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001089
Chris Lattnere818f772008-05-02 18:43:35 +00001090 if (LdExpArg) {
1091 const char *Name;
1092 if (Op->getType() == Type::FloatTy)
1093 Name = "ldexpf";
1094 else if (Op->getType() == Type::DoubleTy)
1095 Name = "ldexp";
1096 else
1097 Name = "ldexpl";
1098
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001099 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Chris Lattnere818f772008-05-02 18:43:35 +00001100 if (Op->getType() != Type::FloatTy)
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001101 One = Context->getConstantExprFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001102
1103 Module *M = Caller->getParent();
1104 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1105 Op->getType(), Type::Int32Ty,NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001106 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1107 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1108 CI->setCallingConv(F->getCallingConv());
1109
1110 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001111 }
1112 return 0;
1113 }
1114};
Chris Lattnere818f772008-05-02 18:43:35 +00001115
1116//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001117// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1118
1119struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001120 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001121 const FunctionType *FT = Callee->getFunctionType();
1122 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1123 FT->getParamType(0) != Type::DoubleTy)
1124 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001125
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001126 // If this is something like 'floor((double)floatval)', convert to floorf.
1127 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1128 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1129 return 0;
1130
1131 // floor((double)floatval) -> (double)floorf(floatval)
1132 Value *V = Cast->getOperand(0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001133 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001134 return B.CreateFPExt(V, Type::DoubleTy);
1135 }
1136};
1137
1138//===----------------------------------------------------------------------===//
1139// Integer Optimizations
1140//===----------------------------------------------------------------------===//
1141
1142//===---------------------------------------===//
1143// 'ffs*' Optimizations
1144
1145struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001146 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001147 const FunctionType *FT = Callee->getFunctionType();
1148 // Just make sure this has 2 arguments of the same FP type, which match the
1149 // result type.
1150 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1151 !isa<IntegerType>(FT->getParamType(0)))
1152 return 0;
1153
1154 Value *Op = CI->getOperand(1);
1155
1156 // Constant fold.
1157 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1158 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001159 return Context->getNullValue(CI->getType());
Owen Andersoneed707b2009-07-24 23:12:02 +00001160 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001161 CI->getValue().countTrailingZeros()+1);
1162 }
1163
1164 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1165 const Type *ArgType = Op->getType();
1166 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1167 Intrinsic::cttz, &ArgType, 1);
1168 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +00001169 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001170 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1171
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001172 Value *Cond = B.CreateICmpNE(Op, Context->getNullValue(ArgType), "tmp");
Owen Andersoneed707b2009-07-24 23:12:02 +00001173 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001174 }
1175};
1176
1177//===---------------------------------------===//
1178// 'isdigit' Optimizations
1179
1180struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001181 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001182 const FunctionType *FT = Callee->getFunctionType();
1183 // We require integer(i32)
1184 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1185 FT->getParamType(0) != Type::Int32Ty)
1186 return 0;
1187
1188 // isdigit(c) -> (c-'0') <u 10
1189 Value *Op = CI->getOperand(1);
Owen Andersoneed707b2009-07-24 23:12:02 +00001190 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001191 "isdigittmp");
Owen Andersoneed707b2009-07-24 23:12:02 +00001192 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001193 "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001194 return B.CreateZExt(Op, CI->getType());
1195 }
1196};
1197
1198//===---------------------------------------===//
1199// 'isascii' Optimizations
1200
1201struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001202 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001203 const FunctionType *FT = Callee->getFunctionType();
1204 // We require integer(i32)
1205 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1206 FT->getParamType(0) != Type::Int32Ty)
1207 return 0;
1208
1209 // isascii(c) -> c <u 128
1210 Value *Op = CI->getOperand(1);
Owen Andersoneed707b2009-07-24 23:12:02 +00001211 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001212 "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001213 return B.CreateZExt(Op, CI->getType());
1214 }
1215};
Chris Lattner313f0e62008-06-09 08:26:51 +00001216
1217//===---------------------------------------===//
1218// 'abs', 'labs', 'llabs' Optimizations
1219
1220struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001221 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001222 const FunctionType *FT = Callee->getFunctionType();
1223 // We require integer(integer) where the types agree.
1224 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1225 FT->getParamType(0) != FT->getReturnType())
1226 return 0;
1227
1228 // abs(x) -> x >s -1 ? x : -x
1229 Value *Op = CI->getOperand(1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001230 Value *Pos = B.CreateICmpSGT(Op,
Owen Anderson73c6b712009-07-13 20:58:05 +00001231 Context->getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001232 "ispos");
1233 Value *Neg = B.CreateNeg(Op, "neg");
1234 return B.CreateSelect(Pos, Op, Neg);
1235 }
1236};
1237
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001238
1239//===---------------------------------------===//
1240// 'toascii' Optimizations
1241
1242struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001243 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001244 const FunctionType *FT = Callee->getFunctionType();
1245 // We require i32(i32)
1246 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1247 FT->getParamType(0) != Type::Int32Ty)
1248 return 0;
1249
1250 // isascii(c) -> c & 0x7f
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001251 return B.CreateAnd(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001252 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001253 }
1254};
1255
1256//===----------------------------------------------------------------------===//
1257// Formatting and IO Optimizations
1258//===----------------------------------------------------------------------===//
1259
1260//===---------------------------------------===//
1261// 'printf' Optimizations
1262
1263struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001264 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001265 // Require one fixed pointer argument and an integer/void result.
1266 const FunctionType *FT = Callee->getFunctionType();
1267 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1268 !(isa<IntegerType>(FT->getReturnType()) ||
1269 FT->getReturnType() == Type::VoidTy))
1270 return 0;
1271
1272 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001273 std::string FormatStr;
1274 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1275 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001276
1277 // Empty format string -> noop.
1278 if (FormatStr.empty()) // Tolerate printf's declared void.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001279 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001280 ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001281
1282 // printf("x") -> putchar('x'), even for '%'.
1283 if (FormatStr.size() == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00001284 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001285 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001286 ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001287 }
1288
1289 // printf("foo\n") --> puts("foo")
1290 if (FormatStr[FormatStr.size()-1] == '\n' &&
1291 FormatStr.find('%') == std::string::npos) { // no format characters.
1292 // Create a string literal with no \n on it. We expect the constant merge
1293 // pass to be run after this pass, to merge duplicate strings.
1294 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1fd70962009-07-28 18:32:17 +00001295 Constant *C = ConstantArray::get(FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001296 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1297 GlobalVariable::InternalLinkage, C, "str");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001298 EmitPutS(C, B);
1299 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001300 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001301 }
1302
1303 // Optimize specific format strings.
1304 // printf("%c", chr) --> putchar(*(i8*)dst)
1305 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1306 isa<IntegerType>(CI->getOperand(2)->getType())) {
1307 EmitPutChar(CI->getOperand(2), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001308 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001309 ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001310 }
1311
1312 // printf("%s\n", str) --> puts(str)
1313 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1314 isa<PointerType>(CI->getOperand(2)->getType()) &&
1315 CI->use_empty()) {
1316 EmitPutS(CI->getOperand(2), B);
1317 return CI;
1318 }
1319 return 0;
1320 }
1321};
1322
1323//===---------------------------------------===//
1324// 'sprintf' Optimizations
1325
1326struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001327 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001328 // Require two fixed pointer arguments and an integer result.
1329 const FunctionType *FT = Callee->getFunctionType();
1330 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1331 !isa<PointerType>(FT->getParamType(1)) ||
1332 !isa<IntegerType>(FT->getReturnType()))
1333 return 0;
1334
1335 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001336 std::string FormatStr;
1337 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1338 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001339
1340 // If we just have a format string (nothing else crazy) transform it.
1341 if (CI->getNumOperands() == 3) {
1342 // Make sure there's no % in the constant array. We could try to handle
1343 // %% -> % in the future if we cared.
1344 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1345 if (FormatStr[i] == '%')
1346 return 0; // we found a format specifier, bail out.
1347
1348 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1349 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
Owen Andersoneed707b2009-07-24 23:12:02 +00001350 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1351 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001352 }
1353
1354 // The remaining optimizations require the format string to be "%s" or "%c"
1355 // and have an extra operand.
1356 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1357 return 0;
1358
1359 // Decode the second character of the format string.
1360 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001361 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001362 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1363 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001364 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1365 B.CreateStore(V, Ptr);
Owen Andersoneed707b2009-07-24 23:12:02 +00001366 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001367 B.CreateStore(Context->getNullValue(Type::Int8Ty), Ptr);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001368
Owen Andersoneed707b2009-07-24 23:12:02 +00001369 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001370 }
1371
1372 if (FormatStr[1] == 's') {
1373 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1374 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1375
1376 Value *Len = EmitStrLen(CI->getOperand(3), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001377 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001378 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001379 "leninc");
1380 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1381
1382 // The sprintf result is the unincremented number of bytes in the string.
1383 return B.CreateIntCast(Len, CI->getType(), false);
1384 }
1385 return 0;
1386 }
1387};
1388
1389//===---------------------------------------===//
1390// 'fwrite' Optimizations
1391
1392struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001393 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001394 // Require a pointer, an integer, an integer, a pointer, returning integer.
1395 const FunctionType *FT = Callee->getFunctionType();
1396 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1397 !isa<IntegerType>(FT->getParamType(1)) ||
1398 !isa<IntegerType>(FT->getParamType(2)) ||
1399 !isa<PointerType>(FT->getParamType(3)) ||
1400 !isa<IntegerType>(FT->getReturnType()))
1401 return 0;
1402
1403 // Get the element size and count.
1404 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1405 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1406 if (!SizeC || !CountC) return 0;
1407 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1408
1409 // If this is writing zero records, remove the call (it's a noop).
1410 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001411 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001412
1413 // If this is writing one byte, turn it into fputc.
1414 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1415 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1416 EmitFPutC(Char, CI->getOperand(4), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001417 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001418 }
1419
1420 return 0;
1421 }
1422};
1423
1424//===---------------------------------------===//
1425// 'fputs' Optimizations
1426
1427struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001428 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001429 // Require two pointers. Also, we can't optimize if return value is used.
1430 const FunctionType *FT = Callee->getFunctionType();
1431 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1432 !isa<PointerType>(FT->getParamType(1)) ||
1433 !CI->use_empty())
1434 return 0;
1435
1436 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1437 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001438 if (!Len) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001439 EmitFWrite(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001440 ConstantInt::get(TD->getIntPtrType(), Len-1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001441 CI->getOperand(2), B);
1442 return CI; // Known to have no uses (see above).
1443 }
1444};
1445
1446//===---------------------------------------===//
1447// 'fprintf' Optimizations
1448
1449struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001450 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001451 // Require two fixed paramters as pointers and integer result.
1452 const FunctionType *FT = Callee->getFunctionType();
1453 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1454 !isa<PointerType>(FT->getParamType(1)) ||
1455 !isa<IntegerType>(FT->getReturnType()))
1456 return 0;
1457
1458 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001459 std::string FormatStr;
1460 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1461 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001462
1463 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1464 if (CI->getNumOperands() == 3) {
1465 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1466 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001467 return 0; // We found a format specifier.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001468
Owen Andersoneed707b2009-07-24 23:12:02 +00001469 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001470 FormatStr.size()),
1471 CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001472 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001473 }
1474
1475 // The remaining optimizations require the format string to be "%s" or "%c"
1476 // and have an extra operand.
1477 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1478 return 0;
1479
1480 // Decode the second character of the format string.
1481 if (FormatStr[1] == 'c') {
1482 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1483 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1484 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001485 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001486 }
1487
1488 if (FormatStr[1] == 's') {
1489 // fprintf(F, "%s", str) -> fputs(str, F)
1490 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1491 return 0;
1492 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1493 return CI;
1494 }
1495 return 0;
1496 }
1497};
1498
Bill Wendlingac178222008-05-05 21:37:59 +00001499} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001500
1501//===----------------------------------------------------------------------===//
1502// SimplifyLibCalls Pass Implementation
1503//===----------------------------------------------------------------------===//
1504
1505namespace {
1506 /// This pass optimizes well known library functions from libc and libm.
1507 ///
1508 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1509 StringMap<LibCallOptimization*> Optimizations;
1510 // Miscellaneous LibCall Optimizations
1511 ExitOpt Exit;
1512 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001513 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1514 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1515 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1516 MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001517 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001518 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001519 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001520 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1521 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001522 // Formatting and IO Optimizations
1523 SPrintFOpt SPrintF; PrintFOpt PrintF;
1524 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001525
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001526 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001527 public:
1528 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001529 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001530
1531 void InitOptimizations();
1532 bool runOnFunction(Function &F);
1533
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001534 void setDoesNotAccessMemory(Function &F);
1535 void setOnlyReadsMemory(Function &F);
1536 void setDoesNotThrow(Function &F);
1537 void setDoesNotCapture(Function &F, unsigned n);
1538 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001539 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001540
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001541 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1542 AU.addRequired<TargetData>();
1543 }
1544 };
1545 char SimplifyLibCalls::ID = 0;
1546} // end anonymous namespace.
1547
1548static RegisterPass<SimplifyLibCalls>
1549X("simplify-libcalls", "Simplify well-known library calls");
1550
1551// Public interface to the Simplify LibCalls pass.
1552FunctionPass *llvm::createSimplifyLibCallsPass() {
1553 return new SimplifyLibCalls();
1554}
1555
1556/// Optimizations - Populate the Optimizations map with all the optimizations
1557/// we know.
1558void SimplifyLibCalls::InitOptimizations() {
1559 // Miscellaneous LibCall Optimizations
1560 Optimizations["exit"] = &Exit;
1561
1562 // String and Memory LibCall Optimizations
1563 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001564 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001565 Optimizations["strchr"] = &StrChr;
1566 Optimizations["strcmp"] = &StrCmp;
1567 Optimizations["strncmp"] = &StrNCmp;
1568 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001569 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001570 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001571 Optimizations["strtol"] = &StrTo;
1572 Optimizations["strtod"] = &StrTo;
1573 Optimizations["strtof"] = &StrTo;
1574 Optimizations["strtoul"] = &StrTo;
1575 Optimizations["strtoll"] = &StrTo;
1576 Optimizations["strtold"] = &StrTo;
1577 Optimizations["strtoull"] = &StrTo;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001578 Optimizations["memcmp"] = &MemCmp;
1579 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001580 Optimizations["memmove"] = &MemMove;
1581 Optimizations["memset"] = &MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001582
1583 // Math Library Optimizations
1584 Optimizations["powf"] = &Pow;
1585 Optimizations["pow"] = &Pow;
1586 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001587 Optimizations["llvm.pow.f32"] = &Pow;
1588 Optimizations["llvm.pow.f64"] = &Pow;
1589 Optimizations["llvm.pow.f80"] = &Pow;
1590 Optimizations["llvm.pow.f128"] = &Pow;
1591 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001592 Optimizations["exp2l"] = &Exp2;
1593 Optimizations["exp2"] = &Exp2;
1594 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001595 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1596 Optimizations["llvm.exp2.f128"] = &Exp2;
1597 Optimizations["llvm.exp2.f80"] = &Exp2;
1598 Optimizations["llvm.exp2.f64"] = &Exp2;
1599 Optimizations["llvm.exp2.f32"] = &Exp2;
Chris Lattnere818f772008-05-02 18:43:35 +00001600
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001601#ifdef HAVE_FLOORF
1602 Optimizations["floor"] = &UnaryDoubleFP;
1603#endif
1604#ifdef HAVE_CEILF
1605 Optimizations["ceil"] = &UnaryDoubleFP;
1606#endif
1607#ifdef HAVE_ROUNDF
1608 Optimizations["round"] = &UnaryDoubleFP;
1609#endif
1610#ifdef HAVE_RINTF
1611 Optimizations["rint"] = &UnaryDoubleFP;
1612#endif
1613#ifdef HAVE_NEARBYINTF
1614 Optimizations["nearbyint"] = &UnaryDoubleFP;
1615#endif
1616
1617 // Integer Optimizations
1618 Optimizations["ffs"] = &FFS;
1619 Optimizations["ffsl"] = &FFS;
1620 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001621 Optimizations["abs"] = &Abs;
1622 Optimizations["labs"] = &Abs;
1623 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001624 Optimizations["isdigit"] = &IsDigit;
1625 Optimizations["isascii"] = &IsAscii;
1626 Optimizations["toascii"] = &ToAscii;
1627
1628 // Formatting and IO Optimizations
1629 Optimizations["sprintf"] = &SPrintF;
1630 Optimizations["printf"] = &PrintF;
1631 Optimizations["fwrite"] = &FWrite;
1632 Optimizations["fputs"] = &FPuts;
1633 Optimizations["fprintf"] = &FPrintF;
1634}
1635
1636
1637/// runOnFunction - Top level algorithm.
1638///
1639bool SimplifyLibCalls::runOnFunction(Function &F) {
1640 if (Optimizations.empty())
1641 InitOptimizations();
1642
1643 const TargetData &TD = getAnalysis<TargetData>();
1644
Owen Andersone922c022009-07-22 00:24:57 +00001645 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001646
1647 bool Changed = false;
1648 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1649 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1650 // Ignore non-calls.
1651 CallInst *CI = dyn_cast<CallInst>(I++);
1652 if (!CI) continue;
1653
1654 // Ignore indirect calls and calls to non-external functions.
1655 Function *Callee = CI->getCalledFunction();
1656 if (Callee == 0 || !Callee->isDeclaration() ||
1657 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1658 continue;
1659
1660 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001661 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1662 if (!LCO) continue;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001663
1664 // Set the builder to the instruction after the call.
1665 Builder.SetInsertPoint(BB, I);
1666
1667 // Try to optimize this call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001668 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001669 if (Result == 0) continue;
1670
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001671 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1672 errs() << " into: " << *Result << "\n");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001673
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
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001740 if (!F.hasName())
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001741 continue;
1742
1743 const FunctionType *FTy = F.getFunctionType();
1744
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001745 StringRef Name = F.getName();
1746 switch (Name[0]) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001747 case 's':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001748 if (Name == "strlen") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001749 if (FTy->getNumParams() != 1 ||
1750 !isa<PointerType>(FTy->getParamType(0)))
1751 continue;
1752 setOnlyReadsMemory(F);
1753 setDoesNotThrow(F);
1754 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001755 } else if (Name == "strcpy" ||
1756 Name == "stpcpy" ||
1757 Name == "strcat" ||
1758 Name == "strtol" ||
1759 Name == "strtod" ||
1760 Name == "strtof" ||
1761 Name == "strtoul" ||
1762 Name == "strtoll" ||
1763 Name == "strtold" ||
1764 Name == "strncat" ||
1765 Name == "strncpy" ||
1766 Name == "strtoull") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001767 if (FTy->getNumParams() < 2 ||
1768 !isa<PointerType>(FTy->getParamType(1)))
1769 continue;
1770 setDoesNotThrow(F);
1771 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001772 } else if (Name == "strxfrm") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001773 if (FTy->getNumParams() != 3 ||
1774 !isa<PointerType>(FTy->getParamType(0)) ||
1775 !isa<PointerType>(FTy->getParamType(1)))
1776 continue;
1777 setDoesNotThrow(F);
1778 setDoesNotCapture(F, 1);
1779 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001780 } else if (Name == "strcmp" ||
1781 Name == "strspn" ||
1782 Name == "strncmp" ||
1783 Name ==" strcspn" ||
1784 Name == "strcoll" ||
1785 Name == "strcasecmp" ||
1786 Name == "strncasecmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001787 if (FTy->getNumParams() < 2 ||
1788 !isa<PointerType>(FTy->getParamType(0)) ||
1789 !isa<PointerType>(FTy->getParamType(1)))
1790 continue;
1791 setOnlyReadsMemory(F);
1792 setDoesNotThrow(F);
1793 setDoesNotCapture(F, 1);
1794 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001795 } else if (Name == "strstr" ||
1796 Name == "strpbrk") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001797 if (FTy->getNumParams() != 2 ||
1798 !isa<PointerType>(FTy->getParamType(1)))
1799 continue;
1800 setOnlyReadsMemory(F);
1801 setDoesNotThrow(F);
1802 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001803 } else if (Name == "strtok" ||
1804 Name == "strtok_r") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001805 if (FTy->getNumParams() < 2 ||
1806 !isa<PointerType>(FTy->getParamType(1)))
1807 continue;
1808 setDoesNotThrow(F);
1809 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001810 } else if (Name == "scanf" ||
1811 Name == "setbuf" ||
1812 Name == "setvbuf") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001813 if (FTy->getNumParams() < 1 ||
1814 !isa<PointerType>(FTy->getParamType(0)))
1815 continue;
1816 setDoesNotThrow(F);
1817 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001818 } else if (Name == "strdup" ||
1819 Name == "strndup") {
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001820 if (FTy->getNumParams() < 1 ||
1821 !isa<PointerType>(FTy->getReturnType()) ||
1822 !isa<PointerType>(FTy->getParamType(0)))
1823 continue;
1824 setDoesNotThrow(F);
1825 setDoesNotAlias(F, 0);
1826 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001827 } else if (Name == "stat" ||
1828 Name == "sscanf" ||
1829 Name == "sprintf" ||
1830 Name == "statvfs") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001831 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001832 !isa<PointerType>(FTy->getParamType(0)) ||
1833 !isa<PointerType>(FTy->getParamType(1)))
1834 continue;
1835 setDoesNotThrow(F);
1836 setDoesNotCapture(F, 1);
1837 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001838 } else if (Name == "snprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001839 if (FTy->getNumParams() != 3 ||
1840 !isa<PointerType>(FTy->getParamType(0)) ||
1841 !isa<PointerType>(FTy->getParamType(2)))
1842 continue;
1843 setDoesNotThrow(F);
1844 setDoesNotCapture(F, 1);
1845 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001846 } else if (Name == "setitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001847 if (FTy->getNumParams() != 3 ||
1848 !isa<PointerType>(FTy->getParamType(1)) ||
1849 !isa<PointerType>(FTy->getParamType(2)))
1850 continue;
1851 setDoesNotThrow(F);
1852 setDoesNotCapture(F, 2);
1853 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001854 } else if (Name == "system") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001855 if (FTy->getNumParams() != 1 ||
1856 !isa<PointerType>(FTy->getParamType(0)))
1857 continue;
1858 // May throw; "system" is a valid pthread cancellation point.
1859 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001860 }
1861 break;
1862 case 'm':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001863 if (Name == "memcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001864 if (FTy->getNumParams() != 3 ||
1865 !isa<PointerType>(FTy->getParamType(0)) ||
1866 !isa<PointerType>(FTy->getParamType(1)))
1867 continue;
1868 setOnlyReadsMemory(F);
1869 setDoesNotThrow(F);
1870 setDoesNotCapture(F, 1);
1871 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001872 } else if (Name == "memchr" ||
1873 Name == "memrchr") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001874 if (FTy->getNumParams() != 3)
1875 continue;
1876 setOnlyReadsMemory(F);
1877 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001878 } else if (Name == "modf" ||
1879 Name == "modff" ||
1880 Name == "modfl" ||
1881 Name == "memcpy" ||
1882 Name == "memccpy" ||
1883 Name == "memmove") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001884 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001885 !isa<PointerType>(FTy->getParamType(1)))
1886 continue;
1887 setDoesNotThrow(F);
1888 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001889 } else if (Name == "memalign") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001890 if (!isa<PointerType>(FTy->getReturnType()))
1891 continue;
1892 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001893 } else if (Name == "mkdir" ||
1894 Name == "mktime") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001895 if (FTy->getNumParams() == 0 ||
1896 !isa<PointerType>(FTy->getParamType(0)))
1897 continue;
1898 setDoesNotThrow(F);
1899 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001900 }
1901 break;
1902 case 'r':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001903 if (Name == "realloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001904 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001905 !isa<PointerType>(FTy->getParamType(0)) ||
1906 !isa<PointerType>(FTy->getReturnType()))
1907 continue;
1908 setDoesNotThrow(F);
1909 setDoesNotAlias(F, 0);
1910 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001911 } else if (Name == "read") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001912 if (FTy->getNumParams() != 3 ||
1913 !isa<PointerType>(FTy->getParamType(1)))
1914 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001915 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001916 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001917 } else if (Name == "rmdir" ||
1918 Name == "rewind" ||
1919 Name == "remove" ||
1920 Name == "realpath") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001921 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001922 !isa<PointerType>(FTy->getParamType(0)))
1923 continue;
1924 setDoesNotThrow(F);
1925 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001926 } else if (Name == "rename" ||
1927 Name == "readlink") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001928 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001929 !isa<PointerType>(FTy->getParamType(0)) ||
1930 !isa<PointerType>(FTy->getParamType(1)))
1931 continue;
1932 setDoesNotThrow(F);
1933 setDoesNotCapture(F, 1);
1934 setDoesNotCapture(F, 2);
1935 }
1936 break;
1937 case 'w':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001938 if (Name == "write") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001939 if (FTy->getNumParams() != 3 ||
1940 !isa<PointerType>(FTy->getParamType(1)))
1941 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001942 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001943 setDoesNotCapture(F, 2);
1944 }
1945 break;
1946 case 'b':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001947 if (Name == "bcopy") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001948 if (FTy->getNumParams() != 3 ||
1949 !isa<PointerType>(FTy->getParamType(0)) ||
1950 !isa<PointerType>(FTy->getParamType(1)))
1951 continue;
1952 setDoesNotThrow(F);
1953 setDoesNotCapture(F, 1);
1954 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001955 } else if (Name == "bcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001956 if (FTy->getNumParams() != 3 ||
1957 !isa<PointerType>(FTy->getParamType(0)) ||
1958 !isa<PointerType>(FTy->getParamType(1)))
1959 continue;
1960 setDoesNotThrow(F);
1961 setOnlyReadsMemory(F);
1962 setDoesNotCapture(F, 1);
1963 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001964 } else if (Name == "bzero") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001965 if (FTy->getNumParams() != 2 ||
1966 !isa<PointerType>(FTy->getParamType(0)))
1967 continue;
1968 setDoesNotThrow(F);
1969 setDoesNotCapture(F, 1);
1970 }
1971 break;
1972 case 'c':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001973 if (Name == "calloc") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001974 if (FTy->getNumParams() != 2 ||
1975 !isa<PointerType>(FTy->getReturnType()))
1976 continue;
1977 setDoesNotThrow(F);
1978 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001979 } else if (Name == "chmod" ||
1980 Name == "chown" ||
1981 Name == "ctermid" ||
1982 Name == "clearerr" ||
1983 Name == "closedir") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001984 if (FTy->getNumParams() == 0 ||
1985 !isa<PointerType>(FTy->getParamType(0)))
1986 continue;
1987 setDoesNotThrow(F);
1988 setDoesNotCapture(F, 1);
1989 }
1990 break;
1991 case 'a':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001992 if (Name == "atoi" ||
1993 Name == "atol" ||
1994 Name == "atof" ||
1995 Name == "atoll") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001996 if (FTy->getNumParams() != 1 ||
1997 !isa<PointerType>(FTy->getParamType(0)))
1998 continue;
1999 setDoesNotThrow(F);
2000 setOnlyReadsMemory(F);
2001 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002002 } else if (Name == "access") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002003 if (FTy->getNumParams() != 2 ||
2004 !isa<PointerType>(FTy->getParamType(0)))
2005 continue;
2006 setDoesNotThrow(F);
2007 setDoesNotCapture(F, 1);
2008 }
2009 break;
2010 case 'f':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002011 if (Name == "fopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002012 if (FTy->getNumParams() != 2 ||
2013 !isa<PointerType>(FTy->getReturnType()) ||
2014 !isa<PointerType>(FTy->getParamType(0)) ||
2015 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002016 continue;
2017 setDoesNotThrow(F);
2018 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002019 setDoesNotCapture(F, 1);
2020 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002021 } else if (Name == "fdopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002022 if (FTy->getNumParams() != 2 ||
2023 !isa<PointerType>(FTy->getReturnType()) ||
2024 !isa<PointerType>(FTy->getParamType(1)))
2025 continue;
2026 setDoesNotThrow(F);
2027 setDoesNotAlias(F, 0);
2028 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002029 } else if (Name == "feof" ||
2030 Name == "free" ||
2031 Name == "fseek" ||
2032 Name == "ftell" ||
2033 Name == "fgetc" ||
2034 Name == "fseeko" ||
2035 Name == "ftello" ||
2036 Name == "fileno" ||
2037 Name == "fflush" ||
2038 Name == "fclose" ||
2039 Name == "fsetpos" ||
2040 Name == "flockfile" ||
2041 Name == "funlockfile" ||
2042 Name == "ftrylockfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002043 if (FTy->getNumParams() == 0 ||
2044 !isa<PointerType>(FTy->getParamType(0)))
2045 continue;
2046 setDoesNotThrow(F);
2047 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002048 } else if (Name == "ferror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002049 if (FTy->getNumParams() != 1 ||
2050 !isa<PointerType>(FTy->getParamType(0)))
2051 continue;
2052 setDoesNotThrow(F);
2053 setDoesNotCapture(F, 1);
2054 setOnlyReadsMemory(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002055 } else if (Name == "fputc" ||
2056 Name == "fstat" ||
2057 Name == "frexp" ||
2058 Name == "frexpf" ||
2059 Name == "frexpl" ||
2060 Name == "fstatvfs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002061 if (FTy->getNumParams() != 2 ||
2062 !isa<PointerType>(FTy->getParamType(1)))
2063 continue;
2064 setDoesNotThrow(F);
2065 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002066 } else if (Name == "fgets") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002067 if (FTy->getNumParams() != 3 ||
2068 !isa<PointerType>(FTy->getParamType(0)) ||
2069 !isa<PointerType>(FTy->getParamType(2)))
2070 continue;
2071 setDoesNotThrow(F);
2072 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002073 } else if (Name == "fread" ||
2074 Name == "fwrite") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002075 if (FTy->getNumParams() != 4 ||
2076 !isa<PointerType>(FTy->getParamType(0)) ||
2077 !isa<PointerType>(FTy->getParamType(3)))
2078 continue;
2079 setDoesNotThrow(F);
2080 setDoesNotCapture(F, 1);
2081 setDoesNotCapture(F, 4);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002082 } else if (Name == "fputs" ||
2083 Name == "fscanf" ||
2084 Name == "fprintf" ||
2085 Name == "fgetpos") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002086 if (FTy->getNumParams() < 2 ||
2087 !isa<PointerType>(FTy->getParamType(0)) ||
2088 !isa<PointerType>(FTy->getParamType(1)))
2089 continue;
2090 setDoesNotThrow(F);
2091 setDoesNotCapture(F, 1);
2092 setDoesNotCapture(F, 2);
2093 }
2094 break;
2095 case 'g':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002096 if (Name == "getc" ||
2097 Name == "getlogin_r" ||
2098 Name == "getc_unlocked") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002099 if (FTy->getNumParams() == 0 ||
2100 !isa<PointerType>(FTy->getParamType(0)))
2101 continue;
2102 setDoesNotThrow(F);
2103 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002104 } else if (Name == "getenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002105 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002106 !isa<PointerType>(FTy->getParamType(0)))
2107 continue;
2108 setDoesNotThrow(F);
2109 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002110 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002111 } else if (Name == "gets" ||
2112 Name == "getchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002113 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002114 } else if (Name == "getitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002115 if (FTy->getNumParams() != 2 ||
2116 !isa<PointerType>(FTy->getParamType(1)))
2117 continue;
2118 setDoesNotThrow(F);
2119 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002120 } else if (Name == "getpwnam") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002121 if (FTy->getNumParams() != 1 ||
2122 !isa<PointerType>(FTy->getParamType(0)))
2123 continue;
2124 setDoesNotThrow(F);
2125 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002126 }
2127 break;
2128 case 'u':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002129 if (Name == "ungetc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002130 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002131 !isa<PointerType>(FTy->getParamType(1)))
2132 continue;
2133 setDoesNotThrow(F);
2134 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002135 } else if (Name == "uname" ||
2136 Name == "unlink" ||
2137 Name == "unsetenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002138 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002139 !isa<PointerType>(FTy->getParamType(0)))
2140 continue;
2141 setDoesNotThrow(F);
2142 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002143 } else if (Name == "utime" ||
2144 Name == "utimes") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002145 if (FTy->getNumParams() != 2 ||
2146 !isa<PointerType>(FTy->getParamType(0)) ||
2147 !isa<PointerType>(FTy->getParamType(1)))
2148 continue;
2149 setDoesNotThrow(F);
2150 setDoesNotCapture(F, 1);
2151 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002152 }
2153 break;
2154 case 'p':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002155 if (Name == "putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002156 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002157 !isa<PointerType>(FTy->getParamType(1)))
2158 continue;
2159 setDoesNotThrow(F);
2160 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002161 } else if (Name == "puts" ||
2162 Name == "printf" ||
2163 Name == "perror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002164 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002165 !isa<PointerType>(FTy->getParamType(0)))
2166 continue;
2167 setDoesNotThrow(F);
2168 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002169 } else if (Name == "pread" ||
2170 Name == "pwrite") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002171 if (FTy->getNumParams() != 4 ||
2172 !isa<PointerType>(FTy->getParamType(1)))
2173 continue;
2174 // May throw; these are valid pthread cancellation points.
2175 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002176 } else if (Name == "putchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002177 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002178 } else if (Name == "popen") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002179 if (FTy->getNumParams() != 2 ||
2180 !isa<PointerType>(FTy->getReturnType()) ||
2181 !isa<PointerType>(FTy->getParamType(0)) ||
2182 !isa<PointerType>(FTy->getParamType(1)))
2183 continue;
2184 setDoesNotThrow(F);
2185 setDoesNotAlias(F, 0);
2186 setDoesNotCapture(F, 1);
2187 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002188 } else if (Name == "pclose") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002189 if (FTy->getNumParams() != 1 ||
2190 !isa<PointerType>(FTy->getParamType(0)))
2191 continue;
2192 setDoesNotThrow(F);
2193 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002194 }
2195 break;
2196 case 'v':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002197 if (Name == "vscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002198 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002199 !isa<PointerType>(FTy->getParamType(1)))
2200 continue;
2201 setDoesNotThrow(F);
2202 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002203 } else if (Name == "vsscanf" ||
2204 Name == "vfscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002205 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002206 !isa<PointerType>(FTy->getParamType(1)) ||
2207 !isa<PointerType>(FTy->getParamType(2)))
2208 continue;
2209 setDoesNotThrow(F);
2210 setDoesNotCapture(F, 1);
2211 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002212 } else if (Name == "valloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002213 if (!isa<PointerType>(FTy->getReturnType()))
2214 continue;
2215 setDoesNotThrow(F);
2216 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002217 } else if (Name == "vprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002218 if (FTy->getNumParams() != 2 ||
2219 !isa<PointerType>(FTy->getParamType(0)))
2220 continue;
2221 setDoesNotThrow(F);
2222 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002223 } else if (Name == "vfprintf" ||
2224 Name == "vsprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002225 if (FTy->getNumParams() != 3 ||
2226 !isa<PointerType>(FTy->getParamType(0)) ||
2227 !isa<PointerType>(FTy->getParamType(1)))
2228 continue;
2229 setDoesNotThrow(F);
2230 setDoesNotCapture(F, 1);
2231 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002232 } else if (Name == "vsnprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002233 if (FTy->getNumParams() != 4 ||
2234 !isa<PointerType>(FTy->getParamType(0)) ||
2235 !isa<PointerType>(FTy->getParamType(2)))
2236 continue;
2237 setDoesNotThrow(F);
2238 setDoesNotCapture(F, 1);
2239 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002240 }
2241 break;
2242 case 'o':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002243 if (Name == "open") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002244 if (FTy->getNumParams() < 2 ||
2245 !isa<PointerType>(FTy->getParamType(0)))
2246 continue;
2247 // May throw; "open" is a valid pthread cancellation point.
2248 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002249 } else if (Name == "opendir") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002250 if (FTy->getNumParams() != 1 ||
2251 !isa<PointerType>(FTy->getReturnType()) ||
2252 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002253 continue;
2254 setDoesNotThrow(F);
2255 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002256 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002257 }
2258 break;
2259 case 't':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002260 if (Name == "tmpfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002261 if (!isa<PointerType>(FTy->getReturnType()))
2262 continue;
2263 setDoesNotThrow(F);
2264 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002265 } else if (Name == "times") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002266 if (FTy->getNumParams() != 1 ||
2267 !isa<PointerType>(FTy->getParamType(0)))
2268 continue;
2269 setDoesNotThrow(F);
2270 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002271 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002272 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002273 case 'h':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002274 if (Name == "htonl" ||
2275 Name == "htons") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002276 setDoesNotThrow(F);
2277 setDoesNotAccessMemory(F);
2278 }
2279 break;
2280 case 'n':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002281 if (Name == "ntohl" ||
2282 Name == "ntohs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002283 setDoesNotThrow(F);
2284 setDoesNotAccessMemory(F);
2285 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002286 break;
2287 case 'l':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002288 if (Name == "lstat") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002289 if (FTy->getNumParams() != 2 ||
2290 !isa<PointerType>(FTy->getParamType(0)) ||
2291 !isa<PointerType>(FTy->getParamType(1)))
2292 continue;
2293 setDoesNotThrow(F);
2294 setDoesNotCapture(F, 1);
2295 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002296 } else if (Name == "lchown") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002297 if (FTy->getNumParams() != 3 ||
2298 !isa<PointerType>(FTy->getParamType(0)))
2299 continue;
2300 setDoesNotThrow(F);
2301 setDoesNotCapture(F, 1);
2302 }
2303 break;
2304 case 'q':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002305 if (Name == "qsort") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002306 if (FTy->getNumParams() != 4 ||
2307 !isa<PointerType>(FTy->getParamType(3)))
2308 continue;
2309 // May throw; places call through function pointer.
2310 setDoesNotCapture(F, 4);
2311 }
2312 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002313 case '_':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002314 if (Name == "__strdup" ||
2315 Name == "__strndup") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002316 if (FTy->getNumParams() < 1 ||
2317 !isa<PointerType>(FTy->getReturnType()) ||
2318 !isa<PointerType>(FTy->getParamType(0)))
2319 continue;
2320 setDoesNotThrow(F);
2321 setDoesNotAlias(F, 0);
2322 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002323 } else if (Name == "__strtok_r") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002324 if (FTy->getNumParams() != 3 ||
2325 !isa<PointerType>(FTy->getParamType(1)))
2326 continue;
2327 setDoesNotThrow(F);
2328 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002329 } else if (Name == "_IO_getc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002330 if (FTy->getNumParams() != 1 ||
2331 !isa<PointerType>(FTy->getParamType(0)))
2332 continue;
2333 setDoesNotThrow(F);
2334 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002335 } else if (Name == "_IO_putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002336 if (FTy->getNumParams() != 2 ||
2337 !isa<PointerType>(FTy->getParamType(1)))
2338 continue;
2339 setDoesNotThrow(F);
2340 setDoesNotCapture(F, 2);
2341 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002342 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002343 case 1:
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002344 if (Name == "\1__isoc99_scanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002345 if (FTy->getNumParams() < 1 ||
2346 !isa<PointerType>(FTy->getParamType(0)))
2347 continue;
2348 setDoesNotThrow(F);
2349 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002350 } else if (Name == "\1stat64" ||
2351 Name == "\1lstat64" ||
2352 Name == "\1statvfs64" ||
2353 Name == "\1__isoc99_sscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002354 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002355 !isa<PointerType>(FTy->getParamType(0)) ||
2356 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002357 continue;
2358 setDoesNotThrow(F);
2359 setDoesNotCapture(F, 1);
2360 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002361 } else if (Name == "\1fopen64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002362 if (FTy->getNumParams() != 2 ||
2363 !isa<PointerType>(FTy->getReturnType()) ||
2364 !isa<PointerType>(FTy->getParamType(0)) ||
2365 !isa<PointerType>(FTy->getParamType(1)))
2366 continue;
2367 setDoesNotThrow(F);
2368 setDoesNotAlias(F, 0);
2369 setDoesNotCapture(F, 1);
2370 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002371 } else if (Name == "\1fseeko64" ||
2372 Name == "\1ftello64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002373 if (FTy->getNumParams() == 0 ||
2374 !isa<PointerType>(FTy->getParamType(0)))
2375 continue;
2376 setDoesNotThrow(F);
2377 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002378 } else if (Name == "\1tmpfile64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002379 if (!isa<PointerType>(FTy->getReturnType()))
2380 continue;
2381 setDoesNotThrow(F);
2382 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002383 } else if (Name == "\1fstat64" ||
2384 Name == "\1fstatvfs64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002385 if (FTy->getNumParams() != 2 ||
2386 !isa<PointerType>(FTy->getParamType(1)))
2387 continue;
2388 setDoesNotThrow(F);
2389 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002390 } else if (Name == "\1open64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002391 if (FTy->getNumParams() < 2 ||
2392 !isa<PointerType>(FTy->getParamType(0)))
2393 continue;
2394 // May throw; "open" is a valid pthread cancellation point.
2395 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002396 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002397 break;
2398 }
2399 }
2400 return Modified;
2401}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002402
2403// TODO:
2404// Additional cases that we need to add to this file:
2405//
2406// cbrt:
2407// * cbrt(expN(X)) -> expN(x/3)
2408// * cbrt(sqrt(x)) -> pow(x,1/6)
2409// * cbrt(sqrt(x)) -> pow(x,1/9)
2410//
2411// cos, cosf, cosl:
2412// * cos(-x) -> cos(x)
2413//
2414// exp, expf, expl:
2415// * exp(log(x)) -> x
2416//
2417// log, logf, logl:
2418// * log(exp(x)) -> x
2419// * log(x**y) -> y*log(x)
2420// * log(exp(y)) -> y*log(e)
2421// * log(exp2(y)) -> y*log(2)
2422// * log(exp10(y)) -> y*log(10)
2423// * log(sqrt(x)) -> 0.5*log(x)
2424// * log(pow(x,y)) -> y*log(x)
2425//
2426// lround, lroundf, lroundl:
2427// * lround(cnst) -> cnst'
2428//
2429// memcmp:
2430// * memcmp(x,y,l) -> cnst
2431// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2432//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002433// pow, powf, powl:
2434// * pow(exp(x),y) -> exp(x*y)
2435// * pow(sqrt(x),y) -> pow(x,y*0.5)
2436// * pow(pow(x,y),z)-> pow(x,y*z)
2437//
2438// puts:
2439// * puts("") -> putchar("\n")
2440//
2441// round, roundf, roundl:
2442// * round(cnst) -> cnst'
2443//
2444// signbit:
2445// * signbit(cnst) -> cnst'
2446// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2447//
2448// sqrt, sqrtf, sqrtl:
2449// * sqrt(expN(x)) -> expN(x*0.5)
2450// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2451// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2452//
2453// stpcpy:
2454// * stpcpy(str, "literal") ->
2455// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2456// strrchr:
2457// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2458// (if c is a constant integer and s is a constant string)
2459// * strrchr(s1,0) -> strchr(s1,0)
2460//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002461// strpbrk:
2462// * strpbrk(s,a) -> offset_in_for(s,a)
2463// (if s and a are both constant strings)
2464// * strpbrk(s,"") -> 0
2465// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2466//
2467// strspn, strcspn:
2468// * strspn(s,a) -> const_int (if both args are constant)
2469// * strspn("",a) -> 0
2470// * strspn(s,"") -> 0
2471// * strcspn(s,a) -> const_int (if both args are constant)
2472// * strcspn("",a) -> 0
2473// * strcspn(s,"") -> strlen(a)
2474//
2475// strstr:
2476// * strstr(x,x) -> x
2477// * strstr(s1,s2) -> offset_of_s2_in(s1)
2478// (if s1 and s2 are constant strings)
2479//
2480// tan, tanf, tanl:
2481// * tan(atan(x)) -> x
2482//
2483// trunc, truncf, truncl:
2484// * trunc(cnst) -> cnst'
2485//
2486//