blob: 32a547398dec04541fc0fe46dc10819655d1785f [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"
Daniel Dunbar473955f2009-07-29 22:00:43 +000032#include "llvm/ADT/STLExtras.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 {
Chris Lattner3e8b6632009-09-02 06:11:42 +000048class LibCallOptimization {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000049protected:
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
Dan Gohmanf14d9192009-08-18 00:48:13 +000065 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000066 Caller = CI->getParent()->getParent();
Dan Gohmanf14d9192009-08-18 00:48:13 +000067 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
Owen Anderson1d0be152009-08-13 21:58:54 +0000128 B.CreateBitCast(V, PointerType::getUnqual(Type::getInt8Ty(*Context)), "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),
Owen Anderson1d0be152009-08-13 21:58:54 +0000141 TD->getIntPtrType(*Context),
142 PointerType::getUnqual(Type::getInt8Ty(*Context)),
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 Anderson1d0be152009-08-13 21:58:54 +0000161 ConstantInt::get(Type::getInt32Ty(*Context), 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 Anderson1d0be152009-08-13 21:58:54 +0000173 PointerType::getUnqual(Type::getInt8Ty(*Context)),
174 PointerType::getUnqual(Type::getInt8Ty(*Context)),
175 Type::getInt32Ty(*Context), TD->getIntPtrType(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000176 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),
Owen Anderson1d0be152009-08-13 21:58:54 +0000196 Type::getInt32Ty(*Context),
197 PointerType::getUnqual(Type::getInt8Ty(*Context)),
198 PointerType::getUnqual(Type::getInt8Ty(*Context)),
199 TD->getIntPtrType(*Context), 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 Anderson1d0be152009-08-13 21:58:54 +0000217 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 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];
Owen Anderson1d0be152009-08-13 21:58:54 +0000228 if (Op->getType() != Type::getDoubleTy(*Context)) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000229 // 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);
Owen Anderson1d0be152009-08-13 21:58:54 +0000233 if (Op->getType() == Type::getFloatTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000234 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();
Owen Anderson1d0be152009-08-13 21:58:54 +0000256 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
257 Type::getInt32Ty(*Context), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000258 CallInst *CI = B.CreateCall(PutChar,
Owen Anderson1d0be152009-08-13 21:58:54 +0000259 B.CreateIntCast(Char, Type::getInt32Ty(*Context), "chari"),
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000260 "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),
Owen Anderson1d0be152009-08-13 21:58:54 +0000275 Type::getInt32Ty(*Context),
276 PointerType::getUnqual(Type::getInt8Ty(*Context)),
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()))
Owen Anderson1d0be152009-08-13 21:58:54 +0000293 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::getInt32Ty(*Context),
294 Type::getInt32Ty(*Context), File->getType(), NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000295 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000296 F = M->getOrInsertFunction("fputc", Type::getInt32Ty(*Context), Type::getInt32Ty(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000297 File->getType(), NULL);
Owen Anderson1d0be152009-08-13 21:58:54 +0000298 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), "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()))
Owen Anderson1d0be152009-08-13 21:58:54 +0000315 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::getInt32Ty(*Context),
316 PointerType::getUnqual(Type::getInt8Ty(*Context)),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000317 File->getType(), NULL);
318 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000319 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
320 PointerType::getUnqual(Type::getInt8Ty(*Context)),
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),
Owen Anderson1d0be152009-08-13 21:58:54 +0000340 TD->getIntPtrType(*Context),
341 PointerType::getUnqual(Type::getInt8Ty(*Context)),
342 TD->getIntPtrType(*Context), TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000343 File->getType(), NULL);
344 else
Owen Anderson1d0be152009-08-13 21:58:54 +0000345 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
346 PointerType::getUnqual(Type::getInt8Ty(*Context)),
347 TD->getIntPtrType(*Context), TD->getIntPtrType(*Context),
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000348 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000349 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
Owen Anderson1d0be152009-08-13 21:58:54 +0000350 ConstantInt::get(TD->getIntPtrType(*Context), 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));
Dan Gohman107f41f2009-08-19 00:11:12 +0000440 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
441 GV->mayBeOverridden())
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000442 return 0;
443 Constant *GlobalInit = GV->getInitializer();
444
445 // Handle the ConstantAggregateZero case, which is a degenerate case. The
446 // initializer is constant zero so the length of the string must be zero.
447 if (isa<ConstantAggregateZero>(GlobalInit))
448 return 1; // Len = 0 offset by 1.
449
450 // Must be a Constant Array
451 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Owen Anderson1d0be152009-08-13 21:58:54 +0000452 if (!Array ||
453 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000454 return false;
455
456 // Get the number of elements in the array
457 uint64_t NumElts = Array->getType()->getNumElements();
458
459 // Traverse the constant array from StartIdx (derived above) which is
460 // the place the GEP refers to in the array.
461 for (unsigned i = StartIdx; i != NumElts; ++i) {
462 Constant *Elt = Array->getOperand(i);
463 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
464 if (!CI) // This array isn't suitable, non-int initializer.
465 return 0;
466 if (CI->isZero())
467 return i-StartIdx+1; // We found end of string, success!
468 }
469
470 return 0; // The array isn't null terminated, conservatively return 'unknown'.
471}
472
473/// GetStringLength - If we can compute the length of the string pointed to by
474/// the specified pointer, return 'len+1'. If we can't, return 0.
475static uint64_t GetStringLength(Value *V) {
476 if (!isa<PointerType>(V->getType())) return 0;
477
478 SmallPtrSet<PHINode*, 32> PHIs;
479 uint64_t Len = GetStringLengthH(V, PHIs);
480 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
481 // an empty string as a length.
482 return Len == ~0ULL ? 1 : Len;
483}
484
485/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
486/// value is equal or not-equal to zero.
487static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
488 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
489 UI != E; ++UI) {
490 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
491 if (IC->isEquality())
492 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
493 if (C->isNullValue())
494 continue;
495 // Unknown instruction.
496 return false;
497 }
498 return true;
499}
500
501//===----------------------------------------------------------------------===//
502// Miscellaneous LibCall Optimizations
503//===----------------------------------------------------------------------===//
504
Bill Wendlingac178222008-05-05 21:37:59 +0000505namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000506//===---------------------------------------===//
507// 'exit' Optimizations
508
509/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
Chris Lattner3e8b6632009-09-02 06:11:42 +0000510struct ExitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000511 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000512 // Verify we have a reasonable prototype for exit.
513 if (Callee->arg_size() == 0 || !CI->use_empty())
514 return 0;
515
516 // Verify the caller is main, and that the result type of main matches the
517 // argument type of exit.
Daniel Dunbar03d76512009-07-25 23:55:21 +0000518 if (Caller->getName() != "main" || !Caller->hasExternalLinkage() ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000519 Caller->getReturnType() != CI->getOperand(1)->getType())
520 return 0;
521
522 TerminatorInst *OldTI = CI->getParent()->getTerminator();
Daniel Dunbar473955f2009-07-29 22:00:43 +0000523
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000524 // Drop all successor phi node entries.
525 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
526 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
Nick Lewycky0efa9212009-07-29 05:17:50 +0000527
Daniel Dunbar473955f2009-07-29 22:00:43 +0000528 // Remove all instructions after the exit.
529 BasicBlock::iterator Dead = CI, E = OldTI; ++Dead;
530 while (Dead != E) {
531 BasicBlock::iterator Next = next(Dead);
Owen Anderson1d0be152009-08-13 21:58:54 +0000532 if (Dead->getType() != Type::getVoidTy(*Context))
Daniel Dunbar473955f2009-07-29 22:00:43 +0000533 Dead->replaceAllUsesWith(UndefValue::get(Dead->getType()));
534 Dead->eraseFromParent();
535 Dead = Next;
536 }
537
538 // Insert a return instruction.
539 OldTI->eraseFromParent();
540 B.SetInsertPoint(B.GetInsertBlock());
Nick Lewycky0efa9212009-07-29 05:17:50 +0000541 B.CreateRet(CI->getOperand(1));
542
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000543 return CI;
544 }
545};
546
547//===----------------------------------------------------------------------===//
548// String and Memory LibCall Optimizations
549//===----------------------------------------------------------------------===//
550
551//===---------------------------------------===//
552// 'strcat' Optimizations
553
Chris Lattner3e8b6632009-09-02 06:11:42 +0000554struct StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000555 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000556 // Verify the "strcat" function prototype.
557 const FunctionType *FT = Callee->getFunctionType();
558 if (FT->getNumParams() != 2 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000559 FT->getReturnType() != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000560 FT->getParamType(0) != FT->getReturnType() ||
561 FT->getParamType(1) != FT->getReturnType())
562 return 0;
563
564 // Extract some information from the instruction
565 Value *Dst = CI->getOperand(1);
566 Value *Src = CI->getOperand(2);
567
568 // See if we can get the length of the input string.
569 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000570 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000571 --Len; // Unbias length.
572
573 // Handle the simple, do-nothing case: strcat(x, "") -> x
574 if (Len == 0)
575 return Dst;
Dan Gohmanf14d9192009-08-18 00:48:13 +0000576
577 // These optimizations require TargetData.
578 if (!TD) return 0;
579
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000580 EmitStrLenMemCpy(Src, Dst, Len, B);
581 return Dst;
582 }
583
584 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000585 // We need to find the end of the destination string. That's where the
586 // memory is to be moved to. We just generate a call to strlen.
587 Value *DstLen = EmitStrLen(Dst, B);
588
589 // Now that we have the destination's length, we must index into the
590 // destination's pointer to get the actual memcpy destination (end of
591 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000592 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000593
594 // We have enough information to now generate the memcpy call to do the
595 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000596 EmitMemCpy(CpyDst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000597 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000598 }
599};
600
601//===---------------------------------------===//
602// 'strncat' Optimizations
603
Chris Lattner3e8b6632009-09-02 06:11:42 +0000604struct StrNCatOpt : public StrCatOpt {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000605 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
606 // Verify the "strncat" function prototype.
607 const FunctionType *FT = Callee->getFunctionType();
608 if (FT->getNumParams() != 3 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000609 FT->getReturnType() != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000610 FT->getParamType(0) != FT->getReturnType() ||
611 FT->getParamType(1) != FT->getReturnType() ||
612 !isa<IntegerType>(FT->getParamType(2)))
613 return 0;
614
615 // Extract some information from the instruction
616 Value *Dst = CI->getOperand(1);
617 Value *Src = CI->getOperand(2);
618 uint64_t Len;
619
620 // We don't do anything if length is not constant
621 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
622 Len = LengthArg->getZExtValue();
623 else
624 return 0;
625
626 // See if we can get the length of the input string.
627 uint64_t SrcLen = GetStringLength(Src);
628 if (SrcLen == 0) return 0;
629 --SrcLen; // Unbias length.
630
631 // Handle the simple, do-nothing cases:
632 // strncat(x, "", c) -> x
633 // strncat(x, c, 0) -> x
634 if (SrcLen == 0 || Len == 0) return Dst;
635
Dan Gohmanf14d9192009-08-18 00:48:13 +0000636 // These optimizations require TargetData.
637 if (!TD) return 0;
638
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000639 // We don't optimize this case
640 if (Len < SrcLen) return 0;
641
642 // strncat(x, s, c) -> strcat(x, s)
643 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000644 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000645 return Dst;
646 }
647};
648
649//===---------------------------------------===//
650// 'strchr' Optimizations
651
Chris Lattner3e8b6632009-09-02 06:11:42 +0000652struct StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000653 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000654 // Verify the "strchr" function prototype.
655 const FunctionType *FT = Callee->getFunctionType();
656 if (FT->getNumParams() != 2 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000657 FT->getReturnType() != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000658 FT->getParamType(0) != FT->getReturnType())
659 return 0;
660
661 Value *SrcStr = CI->getOperand(1);
662
663 // If the second operand is non-constant, see if we can compute the length
664 // of the input string and turn this into memchr.
665 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
666 if (CharC == 0) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000667 // These optimizations require TargetData.
668 if (!TD) return 0;
669
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000670 uint64_t Len = GetStringLength(SrcStr);
Owen Anderson1d0be152009-08-13 21:58:54 +0000671 if (Len == 0 || FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs i32.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000672 return 0;
673
674 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
Owen Anderson1d0be152009-08-13 21:58:54 +0000675 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000676 }
677
678 // Otherwise, the character is a constant, see if the first argument is
679 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000680 std::string Str;
681 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000682 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000683
684 // strchr can find the nul character.
685 Str += '\0';
686 char CharValue = CharC->getSExtValue();
687
688 // Compute the offset.
689 uint64_t i = 0;
690 while (1) {
691 if (i == Str.size()) // Didn't find the char. strchr returns null.
Owen Andersona7235ea2009-07-31 20:28:14 +0000692 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000693 // Did we find our match?
694 if (Str[i] == CharValue)
695 break;
696 ++i;
697 }
698
699 // strchr(s+n,c) -> gep(s+n+i,c)
Owen Anderson1d0be152009-08-13 21:58:54 +0000700 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000701 return B.CreateGEP(SrcStr, Idx, "strchr");
702 }
703};
704
705//===---------------------------------------===//
706// 'strcmp' Optimizations
707
Chris Lattner3e8b6632009-09-02 06:11:42 +0000708struct StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000709 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000710 // Verify the "strcmp" function prototype.
711 const FunctionType *FT = Callee->getFunctionType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000712 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000713 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000714 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000715 return 0;
716
717 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
718 if (Str1P == Str2P) // strcmp(x,x) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000719 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000720
Bill Wendling0582ae92009-03-13 04:39:26 +0000721 std::string Str1, Str2;
722 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
723 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
724
725 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000726 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
727
Bill Wendling0582ae92009-03-13 04:39:26 +0000728 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000729 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
730
731 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000732 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000733 return ConstantInt::get(CI->getType(),
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000734 strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000735
736 // strcmp(P, "x") -> memcmp(P, "x", 2)
737 uint64_t Len1 = GetStringLength(Str1P);
738 uint64_t Len2 = GetStringLength(Str2P);
Chris Lattner849832c2009-06-19 04:17:36 +0000739 if (Len1 && Len2) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000740 // These optimizations require TargetData.
741 if (!TD) return 0;
742
Nick Lewycky13a09e22008-12-21 00:19:21 +0000743 return EmitMemCmp(Str1P, Str2P,
Owen Anderson1d0be152009-08-13 21:58:54 +0000744 ConstantInt::get(TD->getIntPtrType(*Context),
Chris Lattner849832c2009-06-19 04:17:36 +0000745 std::min(Len1, Len2)), B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000746 }
747
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000748 return 0;
749 }
750};
751
752//===---------------------------------------===//
753// 'strncmp' Optimizations
754
Chris Lattner3e8b6632009-09-02 06:11:42 +0000755struct StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000756 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000757 // Verify the "strncmp" function prototype.
758 const FunctionType *FT = Callee->getFunctionType();
Owen Anderson1d0be152009-08-13 21:58:54 +0000759 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000760 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000761 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000762 !isa<IntegerType>(FT->getParamType(2)))
763 return 0;
764
765 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
766 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000767 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000768
769 // Get the length argument if it is constant.
770 uint64_t Length;
771 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
772 Length = LengthArg->getZExtValue();
773 else
774 return 0;
775
776 if (Length == 0) // strncmp(x,y,0) -> 0
Owen Andersoneed707b2009-07-24 23:12:02 +0000777 return ConstantInt::get(CI->getType(), 0);
Bill Wendling0582ae92009-03-13 04:39:26 +0000778
779 std::string Str1, Str2;
780 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
781 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
782
783 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000784 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
785
Bill Wendling0582ae92009-03-13 04:39:26 +0000786 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000787 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
788
789 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000790 if (HasStr1 && HasStr2)
Owen Andersoneed707b2009-07-24 23:12:02 +0000791 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000792 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000793 return 0;
794 }
795};
796
797
798//===---------------------------------------===//
799// 'strcpy' Optimizations
800
Chris Lattner3e8b6632009-09-02 06:11:42 +0000801struct StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000802 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000803 // Verify the "strcpy" function prototype.
804 const FunctionType *FT = Callee->getFunctionType();
805 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
806 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000807 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000808 return 0;
809
810 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
811 if (Dst == Src) // strcpy(x,x) -> x
812 return Src;
813
Dan Gohmanf14d9192009-08-18 00:48:13 +0000814 // These optimizations require TargetData.
815 if (!TD) return 0;
816
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000817 // See if we can get the length of the input string.
818 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000819 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000820
821 // We have enough information to now generate the memcpy call to do the
822 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000823 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000824 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000825 return Dst;
826 }
827};
828
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000829//===---------------------------------------===//
830// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000831
Chris Lattner3e8b6632009-09-02 06:11:42 +0000832struct StrNCpyOpt : public LibCallOptimization {
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000833 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
834 const FunctionType *FT = Callee->getFunctionType();
835 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
836 FT->getParamType(0) != FT->getParamType(1) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000837 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000838 !isa<IntegerType>(FT->getParamType(2)))
839 return 0;
840
841 Value *Dst = CI->getOperand(1);
842 Value *Src = CI->getOperand(2);
843 Value *LenOp = CI->getOperand(3);
844
845 // See if we can get the length of the input string.
846 uint64_t SrcLen = GetStringLength(Src);
847 if (SrcLen == 0) return 0;
848 --SrcLen;
849
850 if (SrcLen == 0) {
851 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
Owen Anderson1d0be152009-08-13 21:58:54 +0000852 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000853 return Dst;
854 }
855
856 uint64_t Len;
857 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
858 Len = LengthArg->getZExtValue();
859 else
860 return 0;
861
862 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
863
Dan Gohmanf14d9192009-08-18 00:48:13 +0000864 // These optimizations require TargetData.
865 if (!TD) return 0;
866
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000867 // Let strncpy handle the zero padding
868 if (Len > SrcLen+1) return 0;
869
870 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
Owen Andersonfa5cbd62009-07-03 19:42:02 +0000871 EmitMemCpy(Dst, Src,
Owen Anderson1d0be152009-08-13 21:58:54 +0000872 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000873
874 return Dst;
875 }
876};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000877
878//===---------------------------------------===//
879// 'strlen' Optimizations
880
Chris Lattner3e8b6632009-09-02 06:11:42 +0000881struct StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000882 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000883 const FunctionType *FT = Callee->getFunctionType();
884 if (FT->getNumParams() != 1 ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000885 FT->getParamType(0) != PointerType::getUnqual(Type::getInt8Ty(*Context)) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000886 !isa<IntegerType>(FT->getReturnType()))
887 return 0;
888
889 Value *Src = CI->getOperand(1);
890
891 // Constant folding: strlen("xyz") -> 3
892 if (uint64_t Len = GetStringLength(Src))
Owen Andersoneed707b2009-07-24 23:12:02 +0000893 return ConstantInt::get(CI->getType(), Len-1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000894
895 // Handle strlen(p) != 0.
896 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
897
898 // strlen(x) != 0 --> *x != 0
899 // strlen(x) == 0 --> *x == 0
900 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
901 }
902};
903
904//===---------------------------------------===//
Nick Lewycky4c498412009-02-13 15:31:46 +0000905// 'strto*' Optimizations
906
Chris Lattner3e8b6632009-09-02 06:11:42 +0000907struct StrToOpt : public LibCallOptimization {
Nick Lewycky4c498412009-02-13 15:31:46 +0000908 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
909 const FunctionType *FT = Callee->getFunctionType();
910 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
911 !isa<PointerType>(FT->getParamType(0)) ||
912 !isa<PointerType>(FT->getParamType(1)))
913 return 0;
914
915 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000916 if (isa<ConstantPointerNull>(EndPtr)) {
917 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000918 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000919 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000920
921 return 0;
922 }
923};
924
925
926//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000927// 'memcmp' Optimizations
928
Chris Lattner3e8b6632009-09-02 06:11:42 +0000929struct MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000930 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000931 const FunctionType *FT = Callee->getFunctionType();
932 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
933 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000934 FT->getReturnType() != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000935 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000936
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000937 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000938
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000939 if (LHS == RHS) // memcmp(s,s,x) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000940 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000941
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000942 // Make sure we have a constant length.
943 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000944 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000945 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000946
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000947 if (Len == 0) // memcmp(s1,s2,0) -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +0000948 return Constant::getNullValue(CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000949
950 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
951 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
952 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +0000953 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000954 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000955
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000956 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
957 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
958 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Owen Andersondebcb012009-07-29 22:17:13 +0000959 const Type *PTy = PointerType::getUnqual(Len == 2 ?
Owen Anderson1d0be152009-08-13 21:58:54 +0000960 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000961 LHS = B.CreateBitCast(LHS, PTy, "tmp");
962 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000963 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
964 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
965 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
966 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
967 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000968
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000969 return 0;
970 }
971};
972
973//===---------------------------------------===//
974// 'memcpy' Optimizations
975
Chris Lattner3e8b6632009-09-02 06:11:42 +0000976struct MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000977 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000978 // These optimizations require TargetData.
979 if (!TD) return 0;
980
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000981 const FunctionType *FT = Callee->getFunctionType();
982 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
983 !isa<PointerType>(FT->getParamType(0)) ||
984 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000985 FT->getParamType(2) != TD->getIntPtrType(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000986 return 0;
987
988 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
989 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
990 return CI->getOperand(1);
991 }
992};
993
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000994//===---------------------------------------===//
995// 'memmove' Optimizations
996
Chris Lattner3e8b6632009-09-02 06:11:42 +0000997struct MemMoveOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000998 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +0000999 // These optimizations require TargetData.
1000 if (!TD) return 0;
1001
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001002 const FunctionType *FT = Callee->getFunctionType();
1003 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1004 !isa<PointerType>(FT->getParamType(0)) ||
1005 !isa<PointerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001006 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001007 return 0;
1008
1009 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1010 Module *M = Caller->getParent();
1011 Intrinsic::ID IID = Intrinsic::memmove;
1012 const Type *Tys[1];
Owen Anderson1d0be152009-08-13 21:58:54 +00001013 Tys[0] = TD->getIntPtrType(*Context);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001014 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
1015 Value *Dst = CastToCStr(CI->getOperand(1), B);
1016 Value *Src = CastToCStr(CI->getOperand(2), B);
1017 Value *Size = CI->getOperand(3);
Owen Anderson1d0be152009-08-13 21:58:54 +00001018 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001019 B.CreateCall4(MemMove, Dst, Src, Size, Align);
1020 return CI->getOperand(1);
1021 }
1022};
1023
1024//===---------------------------------------===//
1025// 'memset' Optimizations
1026
Chris Lattner3e8b6632009-09-02 06:11:42 +00001027struct MemSetOpt : public LibCallOptimization {
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001028 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001029 // These optimizations require TargetData.
1030 if (!TD) return 0;
1031
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001032 const FunctionType *FT = Callee->getFunctionType();
1033 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1034 !isa<PointerType>(FT->getParamType(0)) ||
Eli Friedman62bb4132009-07-18 08:34:51 +00001035 !isa<IntegerType>(FT->getParamType(1)) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001036 FT->getParamType(2) != TD->getIntPtrType(*Context))
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001037 return 0;
1038
1039 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Owen Anderson1d0be152009-08-13 21:58:54 +00001040 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context), false);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001041 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001042 return CI->getOperand(1);
1043 }
1044};
1045
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001046//===----------------------------------------------------------------------===//
1047// Math Library Optimizations
1048//===----------------------------------------------------------------------===//
1049
1050//===---------------------------------------===//
1051// 'pow*' Optimizations
1052
Chris Lattner3e8b6632009-09-02 06:11:42 +00001053struct PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001054 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001055 const FunctionType *FT = Callee->getFunctionType();
1056 // Just make sure this has 2 arguments of the same FP type, which match the
1057 // result type.
1058 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1059 FT->getParamType(0) != FT->getParamType(1) ||
1060 !FT->getParamType(0)->isFloatingPoint())
1061 return 0;
1062
1063 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1064 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1065 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1066 return Op1C;
1067 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1068 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1069 }
1070
1071 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1072 if (Op2C == 0) return 0;
1073
1074 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001075 return ConstantFP::get(CI->getType(), 1.0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001076
1077 if (Op2C->isExactlyValue(0.5)) {
1078 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1079 // 'unsafe' math optimizations are allowed.
1080 // x pow(x, 0.5) sqrt(x)
1081 // ---------------------------------------------
1082 // -0.0 +0.0 -0.0
1083 // -inf +inf NaN
1084#if 0
1085 // pow(x, 0.5) -> sqrt(x)
1086 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1087#endif
1088 }
1089
1090 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1091 return Op1;
1092 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001093 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001094 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001095 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001096 Op1, "powrecip");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001097 return 0;
1098 }
1099};
1100
1101//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001102// 'exp2' Optimizations
1103
Chris Lattner3e8b6632009-09-02 06:11:42 +00001104struct Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001105 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001106 const FunctionType *FT = Callee->getFunctionType();
1107 // Just make sure this has 1 argument of FP type, which matches the
1108 // result type.
1109 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1110 !FT->getParamType(0)->isFloatingPoint())
1111 return 0;
1112
1113 Value *Op = CI->getOperand(1);
1114 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1115 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1116 Value *LdExpArg = 0;
1117 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1118 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
Owen Anderson1d0be152009-08-13 21:58:54 +00001119 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001120 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1121 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +00001122 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::getInt32Ty(*Context), "tmp");
Chris Lattnere818f772008-05-02 18:43:35 +00001123 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001124
Chris Lattnere818f772008-05-02 18:43:35 +00001125 if (LdExpArg) {
1126 const char *Name;
Owen Anderson1d0be152009-08-13 21:58:54 +00001127 if (Op->getType() == Type::getFloatTy(*Context))
Chris Lattnere818f772008-05-02 18:43:35 +00001128 Name = "ldexpf";
Owen Anderson1d0be152009-08-13 21:58:54 +00001129 else if (Op->getType() == Type::getDoubleTy(*Context))
Chris Lattnere818f772008-05-02 18:43:35 +00001130 Name = "ldexp";
1131 else
1132 Name = "ldexpl";
1133
Owen Anderson6f83c9c2009-07-27 20:59:43 +00001134 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
Owen Anderson1d0be152009-08-13 21:58:54 +00001135 if (Op->getType() != Type::getFloatTy(*Context))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001136 One = ConstantExpr::getFPExtend(One, Op->getType());
Chris Lattnere818f772008-05-02 18:43:35 +00001137
1138 Module *M = Caller->getParent();
1139 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Owen Anderson1d0be152009-08-13 21:58:54 +00001140 Op->getType(), Type::getInt32Ty(*Context),NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001141 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1142 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1143 CI->setCallingConv(F->getCallingConv());
1144
1145 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001146 }
1147 return 0;
1148 }
1149};
Chris Lattnere818f772008-05-02 18:43:35 +00001150
1151//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001152// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1153
Chris Lattner3e8b6632009-09-02 06:11:42 +00001154struct UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001155 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001156 const FunctionType *FT = Callee->getFunctionType();
Owen Anderson1d0be152009-08-13 21:58:54 +00001157 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::getDoubleTy(*Context) ||
1158 FT->getParamType(0) != Type::getDoubleTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001159 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001160
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001161 // If this is something like 'floor((double)floatval)', convert to floorf.
1162 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
Owen Anderson1d0be152009-08-13 21:58:54 +00001163 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::getFloatTy(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001164 return 0;
1165
1166 // floor((double)floatval) -> (double)floorf(floatval)
1167 Value *V = Cast->getOperand(0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001168 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B);
Owen Anderson1d0be152009-08-13 21:58:54 +00001169 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001170 }
1171};
1172
1173//===----------------------------------------------------------------------===//
1174// Integer Optimizations
1175//===----------------------------------------------------------------------===//
1176
1177//===---------------------------------------===//
1178// 'ffs*' Optimizations
1179
Chris Lattner3e8b6632009-09-02 06:11:42 +00001180struct FFSOpt : 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 // Just make sure this has 2 arguments of the same FP type, which match the
1184 // result type.
Owen Anderson1d0be152009-08-13 21:58:54 +00001185 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::getInt32Ty(*Context) ||
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001186 !isa<IntegerType>(FT->getParamType(0)))
1187 return 0;
1188
1189 Value *Op = CI->getOperand(1);
1190
1191 // Constant fold.
1192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1193 if (CI->getValue() == 0) // ffs(0) -> 0.
Owen Andersona7235ea2009-07-31 20:28:14 +00001194 return Constant::getNullValue(CI->getType());
Owen Anderson1d0be152009-08-13 21:58:54 +00001195 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001196 CI->getValue().countTrailingZeros()+1);
1197 }
1198
1199 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1200 const Type *ArgType = Op->getType();
1201 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1202 Intrinsic::cttz, &ArgType, 1);
1203 Value *V = B.CreateCall(F, Op, "cttz");
Owen Andersoneed707b2009-07-24 23:12:02 +00001204 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001205 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001206
Owen Andersona7235ea2009-07-31 20:28:14 +00001207 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001208 return B.CreateSelect(Cond, V, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001209 }
1210};
1211
1212//===---------------------------------------===//
1213// 'isdigit' Optimizations
1214
Chris Lattner3e8b6632009-09-02 06:11:42 +00001215struct IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001216 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001217 const FunctionType *FT = Callee->getFunctionType();
1218 // We require integer(i32)
1219 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001220 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001221 return 0;
1222
1223 // isdigit(c) -> (c-'0') <u 10
1224 Value *Op = CI->getOperand(1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001225 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001226 "isdigittmp");
Owen Anderson1d0be152009-08-13 21:58:54 +00001227 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001228 "isdigit");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001229 return B.CreateZExt(Op, CI->getType());
1230 }
1231};
1232
1233//===---------------------------------------===//
1234// 'isascii' Optimizations
1235
Chris Lattner3e8b6632009-09-02 06:11:42 +00001236struct IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001237 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001238 const FunctionType *FT = Callee->getFunctionType();
1239 // We require integer(i32)
1240 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001241 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001242 return 0;
1243
1244 // isascii(c) -> c <u 128
1245 Value *Op = CI->getOperand(1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001246 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001247 "isascii");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001248 return B.CreateZExt(Op, CI->getType());
1249 }
1250};
Chris Lattner313f0e62008-06-09 08:26:51 +00001251
1252//===---------------------------------------===//
1253// 'abs', 'labs', 'llabs' Optimizations
1254
Chris Lattner3e8b6632009-09-02 06:11:42 +00001255struct AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001256 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001257 const FunctionType *FT = Callee->getFunctionType();
1258 // We require integer(integer) where the types agree.
1259 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1260 FT->getParamType(0) != FT->getReturnType())
1261 return 0;
1262
1263 // abs(x) -> x >s -1 ? x : -x
1264 Value *Op = CI->getOperand(1);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001265 Value *Pos = B.CreateICmpSGT(Op,
Owen Andersona7235ea2009-07-31 20:28:14 +00001266 Constant::getAllOnesValue(Op->getType()),
Chris Lattner313f0e62008-06-09 08:26:51 +00001267 "ispos");
1268 Value *Neg = B.CreateNeg(Op, "neg");
1269 return B.CreateSelect(Pos, Op, Neg);
1270 }
1271};
1272
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001273
1274//===---------------------------------------===//
1275// 'toascii' Optimizations
1276
Chris Lattner3e8b6632009-09-02 06:11:42 +00001277struct ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001278 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001279 const FunctionType *FT = Callee->getFunctionType();
1280 // We require i32(i32)
1281 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001282 FT->getParamType(0) != Type::getInt32Ty(*Context))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001283 return 0;
1284
1285 // isascii(c) -> c & 0x7f
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001286 return B.CreateAnd(CI->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001287 ConstantInt::get(CI->getType(),0x7F));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001288 }
1289};
1290
1291//===----------------------------------------------------------------------===//
1292// Formatting and IO Optimizations
1293//===----------------------------------------------------------------------===//
1294
1295//===---------------------------------------===//
1296// 'printf' Optimizations
1297
Chris Lattner3e8b6632009-09-02 06:11:42 +00001298struct PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001299 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001300 // Require one fixed pointer argument and an integer/void result.
1301 const FunctionType *FT = Callee->getFunctionType();
1302 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1303 !(isa<IntegerType>(FT->getReturnType()) ||
Owen Anderson1d0be152009-08-13 21:58:54 +00001304 FT->getReturnType() == Type::getVoidTy(*Context)))
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001305 return 0;
1306
1307 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001308 std::string FormatStr;
1309 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1310 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001311
1312 // Empty format string -> noop.
1313 if (FormatStr.empty()) // Tolerate printf's declared void.
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001314 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001315 ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001316
1317 // printf("x") -> putchar('x'), even for '%'.
1318 if (FormatStr.size() == 1) {
Owen Anderson1d0be152009-08-13 21:58:54 +00001319 EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context), FormatStr[0]), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001320 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001321 ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001322 }
1323
1324 // printf("foo\n") --> puts("foo")
1325 if (FormatStr[FormatStr.size()-1] == '\n' &&
1326 FormatStr.find('%') == std::string::npos) { // no format characters.
1327 // Create a string literal with no \n on it. We expect the constant merge
1328 // pass to be run after this pass, to merge duplicate strings.
1329 FormatStr.erase(FormatStr.end()-1);
Owen Anderson1d0be152009-08-13 21:58:54 +00001330 Constant *C = ConstantArray::get(*Context, FormatStr, true);
Owen Andersone9b11b42009-07-08 19:03:57 +00001331 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1332 GlobalVariable::InternalLinkage, C, "str");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001333 EmitPutS(C, B);
1334 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001335 ConstantInt::get(CI->getType(), FormatStr.size()+1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001336 }
1337
1338 // Optimize specific format strings.
1339 // printf("%c", chr) --> putchar(*(i8*)dst)
1340 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1341 isa<IntegerType>(CI->getOperand(2)->getType())) {
1342 EmitPutChar(CI->getOperand(2), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001343 return CI->use_empty() ? (Value*)CI :
Owen Andersoneed707b2009-07-24 23:12:02 +00001344 ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001345 }
1346
1347 // printf("%s\n", str) --> puts(str)
1348 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1349 isa<PointerType>(CI->getOperand(2)->getType()) &&
1350 CI->use_empty()) {
1351 EmitPutS(CI->getOperand(2), B);
1352 return CI;
1353 }
1354 return 0;
1355 }
1356};
1357
1358//===---------------------------------------===//
1359// 'sprintf' Optimizations
1360
Chris Lattner3e8b6632009-09-02 06:11:42 +00001361struct SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001362 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001363 // Require two fixed pointer arguments and an integer result.
1364 const FunctionType *FT = Callee->getFunctionType();
1365 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1366 !isa<PointerType>(FT->getParamType(1)) ||
1367 !isa<IntegerType>(FT->getReturnType()))
1368 return 0;
1369
1370 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001371 std::string FormatStr;
1372 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1373 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001374
1375 // If we just have a format string (nothing else crazy) transform it.
1376 if (CI->getNumOperands() == 3) {
1377 // Make sure there's no % in the constant array. We could try to handle
1378 // %% -> % in the future if we cared.
1379 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1380 if (FormatStr[i] == '%')
1381 return 0; // we found a format specifier, bail out.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001382
1383 // These optimizations require TargetData.
1384 if (!TD) return 0;
1385
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001386 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1387 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
Owen Anderson1d0be152009-08-13 21:58:54 +00001388 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001389 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001390 }
1391
1392 // The remaining optimizations require the format string to be "%s" or "%c"
1393 // and have an extra operand.
1394 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1395 return 0;
1396
1397 // Decode the second character of the format string.
1398 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001399 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001400 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00001401 Value *V = B.CreateTrunc(CI->getOperand(3), Type::getInt8Ty(*Context), "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001402 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1403 B.CreateStore(V, Ptr);
Owen Anderson1d0be152009-08-13 21:58:54 +00001404 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1), "nul");
1405 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001406
Owen Andersoneed707b2009-07-24 23:12:02 +00001407 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001408 }
1409
1410 if (FormatStr[1] == 's') {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001411 // These optimizations require TargetData.
1412 if (!TD) return 0;
1413
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001414 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1415 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1416
1417 Value *Len = EmitStrLen(CI->getOperand(3), B);
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001418 Value *IncLen = B.CreateAdd(Len,
Owen Andersoneed707b2009-07-24 23:12:02 +00001419 ConstantInt::get(Len->getType(), 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001420 "leninc");
1421 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1422
1423 // The sprintf result is the unincremented number of bytes in the string.
1424 return B.CreateIntCast(Len, CI->getType(), false);
1425 }
1426 return 0;
1427 }
1428};
1429
1430//===---------------------------------------===//
1431// 'fwrite' Optimizations
1432
Chris Lattner3e8b6632009-09-02 06:11:42 +00001433struct FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001434 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001435 // Require a pointer, an integer, an integer, a pointer, returning integer.
1436 const FunctionType *FT = Callee->getFunctionType();
1437 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1438 !isa<IntegerType>(FT->getParamType(1)) ||
1439 !isa<IntegerType>(FT->getParamType(2)) ||
1440 !isa<PointerType>(FT->getParamType(3)) ||
1441 !isa<IntegerType>(FT->getReturnType()))
1442 return 0;
1443
1444 // Get the element size and count.
1445 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1446 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1447 if (!SizeC || !CountC) return 0;
1448 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1449
1450 // If this is writing zero records, remove the call (it's a noop).
1451 if (Bytes == 0)
Owen Andersoneed707b2009-07-24 23:12:02 +00001452 return ConstantInt::get(CI->getType(), 0);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001453
1454 // If this is writing one byte, turn it into fputc.
1455 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1456 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1457 EmitFPutC(Char, CI->getOperand(4), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001458 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001459 }
1460
1461 return 0;
1462 }
1463};
1464
1465//===---------------------------------------===//
1466// 'fputs' Optimizations
1467
Chris Lattner3e8b6632009-09-02 06:11:42 +00001468struct FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Dan Gohmanf14d9192009-08-18 00:48:13 +00001470 // These optimizations require TargetData.
1471 if (!TD) return 0;
1472
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001473 // Require two pointers. Also, we can't optimize if return value is used.
1474 const FunctionType *FT = Callee->getFunctionType();
1475 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1476 !isa<PointerType>(FT->getParamType(1)) ||
1477 !CI->use_empty())
1478 return 0;
1479
1480 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1481 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001482 if (!Len) return 0;
Owen Andersonfa5cbd62009-07-03 19:42:02 +00001483 EmitFWrite(CI->getOperand(1),
Owen Anderson1d0be152009-08-13 21:58:54 +00001484 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001485 CI->getOperand(2), B);
1486 return CI; // Known to have no uses (see above).
1487 }
1488};
1489
1490//===---------------------------------------===//
1491// 'fprintf' Optimizations
1492
Chris Lattner3e8b6632009-09-02 06:11:42 +00001493struct FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001494 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001495 // Require two fixed paramters as pointers and integer result.
1496 const FunctionType *FT = Callee->getFunctionType();
1497 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1498 !isa<PointerType>(FT->getParamType(1)) ||
1499 !isa<IntegerType>(FT->getReturnType()))
1500 return 0;
1501
1502 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001503 std::string FormatStr;
1504 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1505 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001506
1507 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1508 if (CI->getNumOperands() == 3) {
1509 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1510 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001511 return 0; // We found a format specifier.
Dan Gohmanf14d9192009-08-18 00:48:13 +00001512
1513 // These optimizations require TargetData.
1514 if (!TD) return 0;
1515
Owen Anderson1d0be152009-08-13 21:58:54 +00001516 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001517 FormatStr.size()),
1518 CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001519 return ConstantInt::get(CI->getType(), FormatStr.size());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001520 }
1521
1522 // The remaining optimizations require the format string to be "%s" or "%c"
1523 // and have an extra operand.
1524 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1525 return 0;
1526
1527 // Decode the second character of the format string.
1528 if (FormatStr[1] == 'c') {
1529 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1530 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1531 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
Owen Andersoneed707b2009-07-24 23:12:02 +00001532 return ConstantInt::get(CI->getType(), 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001533 }
1534
1535 if (FormatStr[1] == 's') {
1536 // fprintf(F, "%s", str) -> fputs(str, F)
1537 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1538 return 0;
1539 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1540 return CI;
1541 }
1542 return 0;
1543 }
1544};
1545
Bill Wendlingac178222008-05-05 21:37:59 +00001546} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001547
1548//===----------------------------------------------------------------------===//
1549// SimplifyLibCalls Pass Implementation
1550//===----------------------------------------------------------------------===//
1551
1552namespace {
1553 /// This pass optimizes well known library functions from libc and libm.
1554 ///
Chris Lattner3e8b6632009-09-02 06:11:42 +00001555 class SimplifyLibCalls : public FunctionPass {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001556 StringMap<LibCallOptimization*> Optimizations;
1557 // Miscellaneous LibCall Optimizations
1558 ExitOpt Exit;
1559 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001560 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1561 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1562 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1563 MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001564 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001565 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001566 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001567 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1568 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001569 // Formatting and IO Optimizations
1570 SPrintFOpt SPrintF; PrintFOpt PrintF;
1571 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001572
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001573 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001574 public:
1575 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001576 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001577
1578 void InitOptimizations();
1579 bool runOnFunction(Function &F);
1580
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001581 void setDoesNotAccessMemory(Function &F);
1582 void setOnlyReadsMemory(Function &F);
1583 void setDoesNotThrow(Function &F);
1584 void setDoesNotCapture(Function &F, unsigned n);
1585 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001586 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001587
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001588 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001589 }
1590 };
1591 char SimplifyLibCalls::ID = 0;
1592} // end anonymous namespace.
1593
1594static RegisterPass<SimplifyLibCalls>
1595X("simplify-libcalls", "Simplify well-known library calls");
1596
1597// Public interface to the Simplify LibCalls pass.
1598FunctionPass *llvm::createSimplifyLibCallsPass() {
1599 return new SimplifyLibCalls();
1600}
1601
1602/// Optimizations - Populate the Optimizations map with all the optimizations
1603/// we know.
1604void SimplifyLibCalls::InitOptimizations() {
1605 // Miscellaneous LibCall Optimizations
1606 Optimizations["exit"] = &Exit;
1607
1608 // String and Memory LibCall Optimizations
1609 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001610 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001611 Optimizations["strchr"] = &StrChr;
1612 Optimizations["strcmp"] = &StrCmp;
1613 Optimizations["strncmp"] = &StrNCmp;
1614 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001615 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001616 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001617 Optimizations["strtol"] = &StrTo;
1618 Optimizations["strtod"] = &StrTo;
1619 Optimizations["strtof"] = &StrTo;
1620 Optimizations["strtoul"] = &StrTo;
1621 Optimizations["strtoll"] = &StrTo;
1622 Optimizations["strtold"] = &StrTo;
1623 Optimizations["strtoull"] = &StrTo;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001624 Optimizations["memcmp"] = &MemCmp;
1625 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001626 Optimizations["memmove"] = &MemMove;
1627 Optimizations["memset"] = &MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001628
1629 // Math Library Optimizations
1630 Optimizations["powf"] = &Pow;
1631 Optimizations["pow"] = &Pow;
1632 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001633 Optimizations["llvm.pow.f32"] = &Pow;
1634 Optimizations["llvm.pow.f64"] = &Pow;
1635 Optimizations["llvm.pow.f80"] = &Pow;
1636 Optimizations["llvm.pow.f128"] = &Pow;
1637 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001638 Optimizations["exp2l"] = &Exp2;
1639 Optimizations["exp2"] = &Exp2;
1640 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001641 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1642 Optimizations["llvm.exp2.f128"] = &Exp2;
1643 Optimizations["llvm.exp2.f80"] = &Exp2;
1644 Optimizations["llvm.exp2.f64"] = &Exp2;
1645 Optimizations["llvm.exp2.f32"] = &Exp2;
Chris Lattnere818f772008-05-02 18:43:35 +00001646
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001647#ifdef HAVE_FLOORF
1648 Optimizations["floor"] = &UnaryDoubleFP;
1649#endif
1650#ifdef HAVE_CEILF
1651 Optimizations["ceil"] = &UnaryDoubleFP;
1652#endif
1653#ifdef HAVE_ROUNDF
1654 Optimizations["round"] = &UnaryDoubleFP;
1655#endif
1656#ifdef HAVE_RINTF
1657 Optimizations["rint"] = &UnaryDoubleFP;
1658#endif
1659#ifdef HAVE_NEARBYINTF
1660 Optimizations["nearbyint"] = &UnaryDoubleFP;
1661#endif
1662
1663 // Integer Optimizations
1664 Optimizations["ffs"] = &FFS;
1665 Optimizations["ffsl"] = &FFS;
1666 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001667 Optimizations["abs"] = &Abs;
1668 Optimizations["labs"] = &Abs;
1669 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001670 Optimizations["isdigit"] = &IsDigit;
1671 Optimizations["isascii"] = &IsAscii;
1672 Optimizations["toascii"] = &ToAscii;
1673
1674 // Formatting and IO Optimizations
1675 Optimizations["sprintf"] = &SPrintF;
1676 Optimizations["printf"] = &PrintF;
1677 Optimizations["fwrite"] = &FWrite;
1678 Optimizations["fputs"] = &FPuts;
1679 Optimizations["fprintf"] = &FPrintF;
1680}
1681
1682
1683/// runOnFunction - Top level algorithm.
1684///
1685bool SimplifyLibCalls::runOnFunction(Function &F) {
1686 if (Optimizations.empty())
1687 InitOptimizations();
1688
Dan Gohmanf14d9192009-08-18 00:48:13 +00001689 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001690
Owen Andersone922c022009-07-22 00:24:57 +00001691 IRBuilder<> Builder(F.getContext());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001692
1693 bool Changed = false;
1694 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1695 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1696 // Ignore non-calls.
1697 CallInst *CI = dyn_cast<CallInst>(I++);
1698 if (!CI) continue;
1699
1700 // Ignore indirect calls and calls to non-external functions.
1701 Function *Callee = CI->getCalledFunction();
1702 if (Callee == 0 || !Callee->isDeclaration() ||
1703 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1704 continue;
1705
1706 // Ignore unknown calls.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001707 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1708 if (!LCO) continue;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001709
1710 // Set the builder to the instruction after the call.
1711 Builder.SetInsertPoint(BB, I);
1712
1713 // Try to optimize this call.
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001714 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001715 if (Result == 0) continue;
1716
Daniel Dunbarf0443c12009-07-26 08:34:35 +00001717 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1718 errs() << " into: " << *Result << "\n");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001719
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001720 // Something changed!
1721 Changed = true;
1722 ++NumSimplified;
1723
1724 // Inspect the instruction after the call (which was potentially just
1725 // added) next.
1726 I = CI; ++I;
1727
1728 if (CI != Result && !CI->use_empty()) {
1729 CI->replaceAllUsesWith(Result);
1730 if (!Result->hasName())
1731 Result->takeName(CI);
1732 }
1733 CI->eraseFromParent();
1734 }
1735 }
1736 return Changed;
1737}
1738
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001739// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001740
1741void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1742 if (!F.doesNotAccessMemory()) {
1743 F.setDoesNotAccessMemory();
1744 ++NumAnnotated;
1745 Modified = true;
1746 }
1747}
1748void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1749 if (!F.onlyReadsMemory()) {
1750 F.setOnlyReadsMemory();
1751 ++NumAnnotated;
1752 Modified = true;
1753 }
1754}
1755void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1756 if (!F.doesNotThrow()) {
1757 F.setDoesNotThrow();
1758 ++NumAnnotated;
1759 Modified = true;
1760 }
1761}
1762void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1763 if (!F.doesNotCapture(n)) {
1764 F.setDoesNotCapture(n);
1765 ++NumAnnotated;
1766 Modified = true;
1767 }
1768}
1769void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1770 if (!F.doesNotAlias(n)) {
1771 F.setDoesNotAlias(n);
1772 ++NumAnnotated;
1773 Modified = true;
1774 }
1775}
1776
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001777/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001778///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001779bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001780 Modified = false;
1781 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1782 Function &F = *I;
1783 if (!F.isDeclaration())
1784 continue;
1785
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001786 if (!F.hasName())
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001787 continue;
1788
1789 const FunctionType *FTy = F.getFunctionType();
1790
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001791 StringRef Name = F.getName();
1792 switch (Name[0]) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001793 case 's':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001794 if (Name == "strlen") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001795 if (FTy->getNumParams() != 1 ||
1796 !isa<PointerType>(FTy->getParamType(0)))
1797 continue;
1798 setOnlyReadsMemory(F);
1799 setDoesNotThrow(F);
1800 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001801 } else if (Name == "strcpy" ||
1802 Name == "stpcpy" ||
1803 Name == "strcat" ||
1804 Name == "strtol" ||
1805 Name == "strtod" ||
1806 Name == "strtof" ||
1807 Name == "strtoul" ||
1808 Name == "strtoll" ||
1809 Name == "strtold" ||
1810 Name == "strncat" ||
1811 Name == "strncpy" ||
1812 Name == "strtoull") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001813 if (FTy->getNumParams() < 2 ||
1814 !isa<PointerType>(FTy->getParamType(1)))
1815 continue;
1816 setDoesNotThrow(F);
1817 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001818 } else if (Name == "strxfrm") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001819 if (FTy->getNumParams() != 3 ||
1820 !isa<PointerType>(FTy->getParamType(0)) ||
1821 !isa<PointerType>(FTy->getParamType(1)))
1822 continue;
1823 setDoesNotThrow(F);
1824 setDoesNotCapture(F, 1);
1825 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001826 } else if (Name == "strcmp" ||
1827 Name == "strspn" ||
1828 Name == "strncmp" ||
1829 Name ==" strcspn" ||
1830 Name == "strcoll" ||
1831 Name == "strcasecmp" ||
1832 Name == "strncasecmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001833 if (FTy->getNumParams() < 2 ||
1834 !isa<PointerType>(FTy->getParamType(0)) ||
1835 !isa<PointerType>(FTy->getParamType(1)))
1836 continue;
1837 setOnlyReadsMemory(F);
1838 setDoesNotThrow(F);
1839 setDoesNotCapture(F, 1);
1840 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001841 } else if (Name == "strstr" ||
1842 Name == "strpbrk") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001843 if (FTy->getNumParams() != 2 ||
1844 !isa<PointerType>(FTy->getParamType(1)))
1845 continue;
1846 setOnlyReadsMemory(F);
1847 setDoesNotThrow(F);
1848 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001849 } else if (Name == "strtok" ||
1850 Name == "strtok_r") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001851 if (FTy->getNumParams() < 2 ||
1852 !isa<PointerType>(FTy->getParamType(1)))
1853 continue;
1854 setDoesNotThrow(F);
1855 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001856 } else if (Name == "scanf" ||
1857 Name == "setbuf" ||
1858 Name == "setvbuf") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001859 if (FTy->getNumParams() < 1 ||
1860 !isa<PointerType>(FTy->getParamType(0)))
1861 continue;
1862 setDoesNotThrow(F);
1863 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001864 } else if (Name == "strdup" ||
1865 Name == "strndup") {
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001866 if (FTy->getNumParams() < 1 ||
1867 !isa<PointerType>(FTy->getReturnType()) ||
1868 !isa<PointerType>(FTy->getParamType(0)))
1869 continue;
1870 setDoesNotThrow(F);
1871 setDoesNotAlias(F, 0);
1872 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001873 } else if (Name == "stat" ||
1874 Name == "sscanf" ||
1875 Name == "sprintf" ||
1876 Name == "statvfs") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001877 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001878 !isa<PointerType>(FTy->getParamType(0)) ||
1879 !isa<PointerType>(FTy->getParamType(1)))
1880 continue;
1881 setDoesNotThrow(F);
1882 setDoesNotCapture(F, 1);
1883 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001884 } else if (Name == "snprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001885 if (FTy->getNumParams() != 3 ||
1886 !isa<PointerType>(FTy->getParamType(0)) ||
1887 !isa<PointerType>(FTy->getParamType(2)))
1888 continue;
1889 setDoesNotThrow(F);
1890 setDoesNotCapture(F, 1);
1891 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001892 } else if (Name == "setitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001893 if (FTy->getNumParams() != 3 ||
1894 !isa<PointerType>(FTy->getParamType(1)) ||
1895 !isa<PointerType>(FTy->getParamType(2)))
1896 continue;
1897 setDoesNotThrow(F);
1898 setDoesNotCapture(F, 2);
1899 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001900 } else if (Name == "system") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001901 if (FTy->getNumParams() != 1 ||
1902 !isa<PointerType>(FTy->getParamType(0)))
1903 continue;
1904 // May throw; "system" is a valid pthread cancellation point.
1905 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001906 }
1907 break;
1908 case 'm':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001909 if (Name == "memcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001910 if (FTy->getNumParams() != 3 ||
1911 !isa<PointerType>(FTy->getParamType(0)) ||
1912 !isa<PointerType>(FTy->getParamType(1)))
1913 continue;
1914 setOnlyReadsMemory(F);
1915 setDoesNotThrow(F);
1916 setDoesNotCapture(F, 1);
1917 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001918 } else if (Name == "memchr" ||
1919 Name == "memrchr") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001920 if (FTy->getNumParams() != 3)
1921 continue;
1922 setOnlyReadsMemory(F);
1923 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001924 } else if (Name == "modf" ||
1925 Name == "modff" ||
1926 Name == "modfl" ||
1927 Name == "memcpy" ||
1928 Name == "memccpy" ||
1929 Name == "memmove") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001930 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001931 !isa<PointerType>(FTy->getParamType(1)))
1932 continue;
1933 setDoesNotThrow(F);
1934 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001935 } else if (Name == "memalign") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001936 if (!isa<PointerType>(FTy->getReturnType()))
1937 continue;
1938 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001939 } else if (Name == "mkdir" ||
1940 Name == "mktime") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001941 if (FTy->getNumParams() == 0 ||
1942 !isa<PointerType>(FTy->getParamType(0)))
1943 continue;
1944 setDoesNotThrow(F);
1945 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001946 }
1947 break;
1948 case 'r':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001949 if (Name == "realloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001950 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001951 !isa<PointerType>(FTy->getParamType(0)) ||
1952 !isa<PointerType>(FTy->getReturnType()))
1953 continue;
1954 setDoesNotThrow(F);
1955 setDoesNotAlias(F, 0);
1956 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001957 } else if (Name == "read") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001958 if (FTy->getNumParams() != 3 ||
1959 !isa<PointerType>(FTy->getParamType(1)))
1960 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001961 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001962 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001963 } else if (Name == "rmdir" ||
1964 Name == "rewind" ||
1965 Name == "remove" ||
1966 Name == "realpath") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001967 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001968 !isa<PointerType>(FTy->getParamType(0)))
1969 continue;
1970 setDoesNotThrow(F);
1971 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001972 } else if (Name == "rename" ||
1973 Name == "readlink") {
Nick Lewycky225f7472009-02-15 22:47:25 +00001974 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001975 !isa<PointerType>(FTy->getParamType(0)) ||
1976 !isa<PointerType>(FTy->getParamType(1)))
1977 continue;
1978 setDoesNotThrow(F);
1979 setDoesNotCapture(F, 1);
1980 setDoesNotCapture(F, 2);
1981 }
1982 break;
1983 case 'w':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001984 if (Name == "write") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001985 if (FTy->getNumParams() != 3 ||
1986 !isa<PointerType>(FTy->getParamType(1)))
1987 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001988 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001989 setDoesNotCapture(F, 2);
1990 }
1991 break;
1992 case 'b':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00001993 if (Name == "bcopy") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001994 if (FTy->getNumParams() != 3 ||
1995 !isa<PointerType>(FTy->getParamType(0)) ||
1996 !isa<PointerType>(FTy->getParamType(1)))
1997 continue;
1998 setDoesNotThrow(F);
1999 setDoesNotCapture(F, 1);
2000 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002001 } else if (Name == "bcmp") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002002 if (FTy->getNumParams() != 3 ||
2003 !isa<PointerType>(FTy->getParamType(0)) ||
2004 !isa<PointerType>(FTy->getParamType(1)))
2005 continue;
2006 setDoesNotThrow(F);
2007 setOnlyReadsMemory(F);
2008 setDoesNotCapture(F, 1);
2009 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002010 } else if (Name == "bzero") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002011 if (FTy->getNumParams() != 2 ||
2012 !isa<PointerType>(FTy->getParamType(0)))
2013 continue;
2014 setDoesNotThrow(F);
2015 setDoesNotCapture(F, 1);
2016 }
2017 break;
2018 case 'c':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002019 if (Name == "calloc") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002020 if (FTy->getNumParams() != 2 ||
2021 !isa<PointerType>(FTy->getReturnType()))
2022 continue;
2023 setDoesNotThrow(F);
2024 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002025 } else if (Name == "chmod" ||
2026 Name == "chown" ||
2027 Name == "ctermid" ||
2028 Name == "clearerr" ||
2029 Name == "closedir") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002030 if (FTy->getNumParams() == 0 ||
2031 !isa<PointerType>(FTy->getParamType(0)))
2032 continue;
2033 setDoesNotThrow(F);
2034 setDoesNotCapture(F, 1);
2035 }
2036 break;
2037 case 'a':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002038 if (Name == "atoi" ||
2039 Name == "atol" ||
2040 Name == "atof" ||
2041 Name == "atoll") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002042 if (FTy->getNumParams() != 1 ||
2043 !isa<PointerType>(FTy->getParamType(0)))
2044 continue;
2045 setDoesNotThrow(F);
2046 setOnlyReadsMemory(F);
2047 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002048 } else if (Name == "access") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002049 if (FTy->getNumParams() != 2 ||
2050 !isa<PointerType>(FTy->getParamType(0)))
2051 continue;
2052 setDoesNotThrow(F);
2053 setDoesNotCapture(F, 1);
2054 }
2055 break;
2056 case 'f':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002057 if (Name == "fopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002058 if (FTy->getNumParams() != 2 ||
2059 !isa<PointerType>(FTy->getReturnType()) ||
2060 !isa<PointerType>(FTy->getParamType(0)) ||
2061 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002062 continue;
2063 setDoesNotThrow(F);
2064 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002065 setDoesNotCapture(F, 1);
2066 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002067 } else if (Name == "fdopen") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002068 if (FTy->getNumParams() != 2 ||
2069 !isa<PointerType>(FTy->getReturnType()) ||
2070 !isa<PointerType>(FTy->getParamType(1)))
2071 continue;
2072 setDoesNotThrow(F);
2073 setDoesNotAlias(F, 0);
2074 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002075 } else if (Name == "feof" ||
2076 Name == "free" ||
2077 Name == "fseek" ||
2078 Name == "ftell" ||
2079 Name == "fgetc" ||
2080 Name == "fseeko" ||
2081 Name == "ftello" ||
2082 Name == "fileno" ||
2083 Name == "fflush" ||
2084 Name == "fclose" ||
2085 Name == "fsetpos" ||
2086 Name == "flockfile" ||
2087 Name == "funlockfile" ||
2088 Name == "ftrylockfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002089 if (FTy->getNumParams() == 0 ||
2090 !isa<PointerType>(FTy->getParamType(0)))
2091 continue;
2092 setDoesNotThrow(F);
2093 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002094 } else if (Name == "ferror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002095 if (FTy->getNumParams() != 1 ||
2096 !isa<PointerType>(FTy->getParamType(0)))
2097 continue;
2098 setDoesNotThrow(F);
2099 setDoesNotCapture(F, 1);
2100 setOnlyReadsMemory(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002101 } else if (Name == "fputc" ||
2102 Name == "fstat" ||
2103 Name == "frexp" ||
2104 Name == "frexpf" ||
2105 Name == "frexpl" ||
2106 Name == "fstatvfs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002107 if (FTy->getNumParams() != 2 ||
2108 !isa<PointerType>(FTy->getParamType(1)))
2109 continue;
2110 setDoesNotThrow(F);
2111 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002112 } else if (Name == "fgets") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002113 if (FTy->getNumParams() != 3 ||
2114 !isa<PointerType>(FTy->getParamType(0)) ||
2115 !isa<PointerType>(FTy->getParamType(2)))
2116 continue;
2117 setDoesNotThrow(F);
2118 setDoesNotCapture(F, 3);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002119 } else if (Name == "fread" ||
2120 Name == "fwrite") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002121 if (FTy->getNumParams() != 4 ||
2122 !isa<PointerType>(FTy->getParamType(0)) ||
2123 !isa<PointerType>(FTy->getParamType(3)))
2124 continue;
2125 setDoesNotThrow(F);
2126 setDoesNotCapture(F, 1);
2127 setDoesNotCapture(F, 4);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002128 } else if (Name == "fputs" ||
2129 Name == "fscanf" ||
2130 Name == "fprintf" ||
2131 Name == "fgetpos") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002132 if (FTy->getNumParams() < 2 ||
2133 !isa<PointerType>(FTy->getParamType(0)) ||
2134 !isa<PointerType>(FTy->getParamType(1)))
2135 continue;
2136 setDoesNotThrow(F);
2137 setDoesNotCapture(F, 1);
2138 setDoesNotCapture(F, 2);
2139 }
2140 break;
2141 case 'g':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002142 if (Name == "getc" ||
2143 Name == "getlogin_r" ||
2144 Name == "getc_unlocked") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002145 if (FTy->getNumParams() == 0 ||
2146 !isa<PointerType>(FTy->getParamType(0)))
2147 continue;
2148 setDoesNotThrow(F);
2149 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002150 } else if (Name == "getenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002151 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002152 !isa<PointerType>(FTy->getParamType(0)))
2153 continue;
2154 setDoesNotThrow(F);
2155 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002156 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002157 } else if (Name == "gets" ||
2158 Name == "getchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002159 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002160 } else if (Name == "getitimer") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002161 if (FTy->getNumParams() != 2 ||
2162 !isa<PointerType>(FTy->getParamType(1)))
2163 continue;
2164 setDoesNotThrow(F);
2165 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002166 } else if (Name == "getpwnam") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002167 if (FTy->getNumParams() != 1 ||
2168 !isa<PointerType>(FTy->getParamType(0)))
2169 continue;
2170 setDoesNotThrow(F);
2171 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002172 }
2173 break;
2174 case 'u':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002175 if (Name == "ungetc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002176 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002177 !isa<PointerType>(FTy->getParamType(1)))
2178 continue;
2179 setDoesNotThrow(F);
2180 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002181 } else if (Name == "uname" ||
2182 Name == "unlink" ||
2183 Name == "unsetenv") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002184 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002185 !isa<PointerType>(FTy->getParamType(0)))
2186 continue;
2187 setDoesNotThrow(F);
2188 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002189 } else if (Name == "utime" ||
2190 Name == "utimes") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002191 if (FTy->getNumParams() != 2 ||
2192 !isa<PointerType>(FTy->getParamType(0)) ||
2193 !isa<PointerType>(FTy->getParamType(1)))
2194 continue;
2195 setDoesNotThrow(F);
2196 setDoesNotCapture(F, 1);
2197 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002198 }
2199 break;
2200 case 'p':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002201 if (Name == "putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002202 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002203 !isa<PointerType>(FTy->getParamType(1)))
2204 continue;
2205 setDoesNotThrow(F);
2206 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002207 } else if (Name == "puts" ||
2208 Name == "printf" ||
2209 Name == "perror") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002210 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002211 !isa<PointerType>(FTy->getParamType(0)))
2212 continue;
2213 setDoesNotThrow(F);
2214 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002215 } else if (Name == "pread" ||
2216 Name == "pwrite") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002217 if (FTy->getNumParams() != 4 ||
2218 !isa<PointerType>(FTy->getParamType(1)))
2219 continue;
2220 // May throw; these are valid pthread cancellation points.
2221 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002222 } else if (Name == "putchar") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002223 setDoesNotThrow(F);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002224 } else if (Name == "popen") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002225 if (FTy->getNumParams() != 2 ||
2226 !isa<PointerType>(FTy->getReturnType()) ||
2227 !isa<PointerType>(FTy->getParamType(0)) ||
2228 !isa<PointerType>(FTy->getParamType(1)))
2229 continue;
2230 setDoesNotThrow(F);
2231 setDoesNotAlias(F, 0);
2232 setDoesNotCapture(F, 1);
2233 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002234 } else if (Name == "pclose") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002235 if (FTy->getNumParams() != 1 ||
2236 !isa<PointerType>(FTy->getParamType(0)))
2237 continue;
2238 setDoesNotThrow(F);
2239 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002240 }
2241 break;
2242 case 'v':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002243 if (Name == "vscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002244 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002245 !isa<PointerType>(FTy->getParamType(1)))
2246 continue;
2247 setDoesNotThrow(F);
2248 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002249 } else if (Name == "vsscanf" ||
2250 Name == "vfscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002251 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002252 !isa<PointerType>(FTy->getParamType(1)) ||
2253 !isa<PointerType>(FTy->getParamType(2)))
2254 continue;
2255 setDoesNotThrow(F);
2256 setDoesNotCapture(F, 1);
2257 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002258 } else if (Name == "valloc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002259 if (!isa<PointerType>(FTy->getReturnType()))
2260 continue;
2261 setDoesNotThrow(F);
2262 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002263 } else if (Name == "vprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002264 if (FTy->getNumParams() != 2 ||
2265 !isa<PointerType>(FTy->getParamType(0)))
2266 continue;
2267 setDoesNotThrow(F);
2268 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002269 } else if (Name == "vfprintf" ||
2270 Name == "vsprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002271 if (FTy->getNumParams() != 3 ||
2272 !isa<PointerType>(FTy->getParamType(0)) ||
2273 !isa<PointerType>(FTy->getParamType(1)))
2274 continue;
2275 setDoesNotThrow(F);
2276 setDoesNotCapture(F, 1);
2277 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002278 } else if (Name == "vsnprintf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002279 if (FTy->getNumParams() != 4 ||
2280 !isa<PointerType>(FTy->getParamType(0)) ||
2281 !isa<PointerType>(FTy->getParamType(2)))
2282 continue;
2283 setDoesNotThrow(F);
2284 setDoesNotCapture(F, 1);
2285 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002286 }
2287 break;
2288 case 'o':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002289 if (Name == "open") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002290 if (FTy->getNumParams() < 2 ||
2291 !isa<PointerType>(FTy->getParamType(0)))
2292 continue;
2293 // May throw; "open" is a valid pthread cancellation point.
2294 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002295 } else if (Name == "opendir") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002296 if (FTy->getNumParams() != 1 ||
2297 !isa<PointerType>(FTy->getReturnType()) ||
2298 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002299 continue;
2300 setDoesNotThrow(F);
2301 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002302 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002303 }
2304 break;
2305 case 't':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002306 if (Name == "tmpfile") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002307 if (!isa<PointerType>(FTy->getReturnType()))
2308 continue;
2309 setDoesNotThrow(F);
2310 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002311 } else if (Name == "times") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002312 if (FTy->getNumParams() != 1 ||
2313 !isa<PointerType>(FTy->getParamType(0)))
2314 continue;
2315 setDoesNotThrow(F);
2316 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002317 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002318 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002319 case 'h':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002320 if (Name == "htonl" ||
2321 Name == "htons") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002322 setDoesNotThrow(F);
2323 setDoesNotAccessMemory(F);
2324 }
2325 break;
2326 case 'n':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002327 if (Name == "ntohl" ||
2328 Name == "ntohs") {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002329 setDoesNotThrow(F);
2330 setDoesNotAccessMemory(F);
2331 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002332 break;
2333 case 'l':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002334 if (Name == "lstat") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002335 if (FTy->getNumParams() != 2 ||
2336 !isa<PointerType>(FTy->getParamType(0)) ||
2337 !isa<PointerType>(FTy->getParamType(1)))
2338 continue;
2339 setDoesNotThrow(F);
2340 setDoesNotCapture(F, 1);
2341 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002342 } else if (Name == "lchown") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002343 if (FTy->getNumParams() != 3 ||
2344 !isa<PointerType>(FTy->getParamType(0)))
2345 continue;
2346 setDoesNotThrow(F);
2347 setDoesNotCapture(F, 1);
2348 }
2349 break;
2350 case 'q':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002351 if (Name == "qsort") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002352 if (FTy->getNumParams() != 4 ||
2353 !isa<PointerType>(FTy->getParamType(3)))
2354 continue;
2355 // May throw; places call through function pointer.
2356 setDoesNotCapture(F, 4);
2357 }
2358 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002359 case '_':
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002360 if (Name == "__strdup" ||
2361 Name == "__strndup") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002362 if (FTy->getNumParams() < 1 ||
2363 !isa<PointerType>(FTy->getReturnType()) ||
2364 !isa<PointerType>(FTy->getParamType(0)))
2365 continue;
2366 setDoesNotThrow(F);
2367 setDoesNotAlias(F, 0);
2368 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002369 } else if (Name == "__strtok_r") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002370 if (FTy->getNumParams() != 3 ||
2371 !isa<PointerType>(FTy->getParamType(1)))
2372 continue;
2373 setDoesNotThrow(F);
2374 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002375 } else if (Name == "_IO_getc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002376 if (FTy->getNumParams() != 1 ||
2377 !isa<PointerType>(FTy->getParamType(0)))
2378 continue;
2379 setDoesNotThrow(F);
2380 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002381 } else if (Name == "_IO_putc") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002382 if (FTy->getNumParams() != 2 ||
2383 !isa<PointerType>(FTy->getParamType(1)))
2384 continue;
2385 setDoesNotThrow(F);
2386 setDoesNotCapture(F, 2);
2387 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002388 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002389 case 1:
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002390 if (Name == "\1__isoc99_scanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002391 if (FTy->getNumParams() < 1 ||
2392 !isa<PointerType>(FTy->getParamType(0)))
2393 continue;
2394 setDoesNotThrow(F);
2395 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002396 } else if (Name == "\1stat64" ||
2397 Name == "\1lstat64" ||
2398 Name == "\1statvfs64" ||
2399 Name == "\1__isoc99_sscanf") {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002400 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002401 !isa<PointerType>(FTy->getParamType(0)) ||
2402 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002403 continue;
2404 setDoesNotThrow(F);
2405 setDoesNotCapture(F, 1);
2406 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002407 } else if (Name == "\1fopen64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002408 if (FTy->getNumParams() != 2 ||
2409 !isa<PointerType>(FTy->getReturnType()) ||
2410 !isa<PointerType>(FTy->getParamType(0)) ||
2411 !isa<PointerType>(FTy->getParamType(1)))
2412 continue;
2413 setDoesNotThrow(F);
2414 setDoesNotAlias(F, 0);
2415 setDoesNotCapture(F, 1);
2416 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002417 } else if (Name == "\1fseeko64" ||
2418 Name == "\1ftello64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002419 if (FTy->getNumParams() == 0 ||
2420 !isa<PointerType>(FTy->getParamType(0)))
2421 continue;
2422 setDoesNotThrow(F);
2423 setDoesNotCapture(F, 1);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002424 } else if (Name == "\1tmpfile64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002425 if (!isa<PointerType>(FTy->getReturnType()))
2426 continue;
2427 setDoesNotThrow(F);
2428 setDoesNotAlias(F, 0);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002429 } else if (Name == "\1fstat64" ||
2430 Name == "\1fstatvfs64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002431 if (FTy->getNumParams() != 2 ||
2432 !isa<PointerType>(FTy->getParamType(1)))
2433 continue;
2434 setDoesNotThrow(F);
2435 setDoesNotCapture(F, 2);
Daniel Dunbar93b67e42009-07-26 07:49:05 +00002436 } else if (Name == "\1open64") {
Nick Lewycky225f7472009-02-15 22:47:25 +00002437 if (FTy->getNumParams() < 2 ||
2438 !isa<PointerType>(FTy->getParamType(0)))
2439 continue;
2440 // May throw; "open" is a valid pthread cancellation point.
2441 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002442 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002443 break;
2444 }
2445 }
2446 return Modified;
2447}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002448
2449// TODO:
2450// Additional cases that we need to add to this file:
2451//
2452// cbrt:
2453// * cbrt(expN(X)) -> expN(x/3)
2454// * cbrt(sqrt(x)) -> pow(x,1/6)
2455// * cbrt(sqrt(x)) -> pow(x,1/9)
2456//
2457// cos, cosf, cosl:
2458// * cos(-x) -> cos(x)
2459//
2460// exp, expf, expl:
2461// * exp(log(x)) -> x
2462//
2463// log, logf, logl:
2464// * log(exp(x)) -> x
2465// * log(x**y) -> y*log(x)
2466// * log(exp(y)) -> y*log(e)
2467// * log(exp2(y)) -> y*log(2)
2468// * log(exp10(y)) -> y*log(10)
2469// * log(sqrt(x)) -> 0.5*log(x)
2470// * log(pow(x,y)) -> y*log(x)
2471//
2472// lround, lroundf, lroundl:
2473// * lround(cnst) -> cnst'
2474//
2475// memcmp:
2476// * memcmp(x,y,l) -> cnst
2477// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2478//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002479// pow, powf, powl:
2480// * pow(exp(x),y) -> exp(x*y)
2481// * pow(sqrt(x),y) -> pow(x,y*0.5)
2482// * pow(pow(x,y),z)-> pow(x,y*z)
2483//
2484// puts:
2485// * puts("") -> putchar("\n")
2486//
2487// round, roundf, roundl:
2488// * round(cnst) -> cnst'
2489//
2490// signbit:
2491// * signbit(cnst) -> cnst'
2492// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2493//
2494// sqrt, sqrtf, sqrtl:
2495// * sqrt(expN(x)) -> expN(x*0.5)
2496// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2497// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2498//
2499// stpcpy:
2500// * stpcpy(str, "literal") ->
2501// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2502// strrchr:
2503// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2504// (if c is a constant integer and s is a constant string)
2505// * strrchr(s1,0) -> strchr(s1,0)
2506//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002507// strpbrk:
2508// * strpbrk(s,a) -> offset_in_for(s,a)
2509// (if s and a are both constant strings)
2510// * strpbrk(s,"") -> 0
2511// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2512//
2513// strspn, strcspn:
2514// * strspn(s,a) -> const_int (if both args are constant)
2515// * strspn("",a) -> 0
2516// * strspn(s,"") -> 0
2517// * strcspn(s,a) -> const_int (if both args are constant)
2518// * strcspn("",a) -> 0
2519// * strcspn(s,"") -> strlen(a)
2520//
2521// strstr:
2522// * strstr(x,x) -> x
2523// * strstr(s1,s2) -> offset_of_s2_in(s1)
2524// (if s1 and s2 are constant strings)
2525//
2526// tan, tanf, tanl:
2527// * tan(atan(x)) -> x
2528//
2529// trunc, truncf, truncl:
2530// * trunc(cnst) -> cnst'
2531//
2532//