blob: 7d0c35e54091a2dea3508379dbc3fb38ab5043ff [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"
23#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000026#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/Support/Compiler.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000032#include "llvm/Support/Debug.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000033#include "llvm/Config/config.h"
34using namespace llvm;
35
36STATISTIC(NumSimplified, "Number of library calls simplified");
Nick Lewycky0f8df9a2009-01-04 20:27:34 +000037STATISTIC(NumAnnotated, "Number of attributes added to library functions");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000038
39//===----------------------------------------------------------------------===//
40// Optimizer Base Class
41//===----------------------------------------------------------------------===//
42
43/// This class is the abstract base class for the set of optimizations that
44/// corresponds to one library call.
45namespace {
46class VISIBILITY_HIDDEN LibCallOptimization {
47protected:
48 Function *Caller;
49 const TargetData *TD;
50public:
51 LibCallOptimization() { }
52 virtual ~LibCallOptimization() {}
53
54 /// CallOptimizer - This pure virtual method is implemented by base classes to
55 /// do various optimizations. If this returns null then no transformation was
56 /// performed. If it returns CI, then it transformed the call and CI is to be
57 /// deleted. If it returns something else, replace CI with the new value and
58 /// delete CI.
Eric Christopher7a61d702008-08-08 19:39:37 +000059 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
60 =0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000061
Eric Christopher7a61d702008-08-08 19:39:37 +000062 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000063 Caller = CI->getParent()->getParent();
64 this->TD = &TD;
65 return CallOptimizer(CI->getCalledFunction(), CI, B);
66 }
67
68 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +000069 Value *CastToCStr(Value *V, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000070
71 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
72 /// specified pointer. Ptr is required to be some pointer type, and the
73 /// return value has 'intptr_t' type.
Eric Christopher7a61d702008-08-08 19:39:37 +000074 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000075
76 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
77 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
78 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +000079 unsigned Align, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000080
81 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
82 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
Eric Christopher7a61d702008-08-08 19:39:37 +000083 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +000084
85 /// EmitMemCmp - Emit a call to the memcmp function.
86 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
87
Chris Lattnerf5b6bc72009-04-12 05:06:39 +000088 /// EmitMemSet - Emit a call to the memset function
89 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
90
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000091 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
92 /// 'floor'). This function is known to take a single of type matching 'Op'
93 /// and returns one value with the same type. If 'Op' is a long double, 'l'
94 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
Eric Christopher7a61d702008-08-08 19:39:37 +000095 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000096
97 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
98 /// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +000099 void EmitPutChar(Value *Char, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000100
101 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
102 /// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000103 void EmitPutS(Value *Str, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000104
105 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
106 /// an i32, and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000107 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000108
109 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
110 /// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000111 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000112
113 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
114 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000115 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
Nick Lewycky13a09e22008-12-21 00:19:21 +0000116
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000117};
118} // End anonymous namespace.
119
120/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +0000121Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000122 return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
123}
124
125/// EmitStrLen - Emit a call to the strlen function to the builder, for the
126/// specified pointer. This always returns an integer value of size intptr_t.
Eric Christopher7a61d702008-08-08 19:39:37 +0000127Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000128 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000129 AttributeWithIndex AWI[2];
130 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
131 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
132 Attribute::NoUnwind);
133
134 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
135 TD->getIntPtrType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000136 PointerType::getUnqual(Type::Int8Ty),
137 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000138 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
139 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
140 CI->setCallingConv(F->getCallingConv());
141
142 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000143}
144
145/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
146/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
147Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +0000148 unsigned Align, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000149 Module *M = Caller->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +0000150 Intrinsic::ID IID = Intrinsic::memcpy;
151 const Type *Tys[1];
152 Tys[0] = Len->getType();
153 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000154 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
155 ConstantInt::get(Type::Int32Ty, Align));
156}
157
158/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
159/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
160Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
Eric Christopher7a61d702008-08-08 19:39:37 +0000161 Value *Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000162 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000163 AttributeWithIndex AWI;
164 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
165
166 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000167 PointerType::getUnqual(Type::Int8Ty),
168 PointerType::getUnqual(Type::Int8Ty),
169 Type::Int32Ty, TD->getIntPtrType(),
170 NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000171 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
172
173 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
174 CI->setCallingConv(F->getCallingConv());
175
176 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000177}
178
Nick Lewycky13a09e22008-12-21 00:19:21 +0000179/// EmitMemCmp - Emit a call to the memcmp function.
180Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
181 Value *Len, IRBuilder<> &B) {
182 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000183 AttributeWithIndex AWI[3];
184 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
185 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
186 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
187 Attribute::NoUnwind);
188
189 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
Nick Lewycky13a09e22008-12-21 00:19:21 +0000190 Type::Int32Ty,
191 PointerType::getUnqual(Type::Int8Ty),
192 PointerType::getUnqual(Type::Int8Ty),
193 TD->getIntPtrType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000194 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
195 Len, "memcmp");
196
197 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
198 CI->setCallingConv(F->getCallingConv());
199
200 return CI;
Nick Lewycky13a09e22008-12-21 00:19:21 +0000201}
202
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000203/// EmitMemSet - Emit a call to the memset function
204Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
205 Value *Len, IRBuilder<> &B) {
206 Module *M = Caller->getParent();
207 Intrinsic::ID IID = Intrinsic::memset;
208 const Type *Tys[1];
209 Tys[0] = Len->getType();
210 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
211 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
212 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
213}
214
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000215/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
216/// 'floor'). This function is known to take a single of type matching 'Op' and
217/// returns one value with the same type. If 'Op' is a long double, 'l' is
218/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
219Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
Eric Christopher7a61d702008-08-08 19:39:37 +0000220 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000221 char NameBuffer[20];
222 if (Op->getType() != Type::DoubleTy) {
223 // If we need to add a suffix, copy into NameBuffer.
224 unsigned NameLen = strlen(Name);
225 assert(NameLen < sizeof(NameBuffer)-2);
226 memcpy(NameBuffer, Name, NameLen);
227 if (Op->getType() == Type::FloatTy)
228 NameBuffer[NameLen] = 'f'; // floorf
229 else
230 NameBuffer[NameLen] = 'l'; // floorl
231 NameBuffer[NameLen+1] = 0;
232 Name = NameBuffer;
233 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000234
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000235 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000236 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000237 Op->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000238 CallInst *CI = B.CreateCall(Callee, Op, Name);
239
240 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
241 CI->setCallingConv(F->getCallingConv());
242
243 return CI;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000244}
245
246/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
247/// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000248void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000249 Module *M = Caller->getParent();
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000250 Value *PutChar = M->getOrInsertFunction("putchar", Type::Int32Ty,
251 Type::Int32Ty, NULL);
252 CallInst *CI = B.CreateCall(PutChar,
253 B.CreateIntCast(Char, Type::Int32Ty, "chari"),
254 "putchar");
255
256 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
257 CI->setCallingConv(F->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000258}
259
260/// EmitPutS - Emit a call to the puts function. This assumes that Str is
261/// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000262void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000263 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000264 AttributeWithIndex AWI[2];
265 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
266 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
267
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000268 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
269 Type::Int32Ty,
270 PointerType::getUnqual(Type::Int8Ty),
271 NULL);
272 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
273 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
274 CI->setCallingConv(F->getCallingConv());
275
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000276}
277
278/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
279/// an integer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000280void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000281 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000282 AttributeWithIndex AWI[2];
283 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
284 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
285 Constant *F;
286 if (isa<PointerType>(File->getType()))
287 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
288 Type::Int32Ty, File->getType(), NULL);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000289 else
290 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
291 File->getType(), NULL);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000292 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000293 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
294
295 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
296 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000297}
298
299/// EmitFPutS - Emit a call to the puts function. Str is required to be a
300/// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000301void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000302 Module *M = Caller->getParent();
Nick Lewycky225f7472009-02-15 22:47:25 +0000303 AttributeWithIndex AWI[3];
304 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
305 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
306 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000307 Constant *F;
308 if (isa<PointerType>(File->getType()))
Nick Lewycky225f7472009-02-15 22:47:25 +0000309 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3), Type::Int32Ty,
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000310 PointerType::getUnqual(Type::Int8Ty),
311 File->getType(), NULL);
312 else
313 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
314 PointerType::getUnqual(Type::Int8Ty),
315 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000316 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
317
318 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
319 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000320}
321
322/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
323/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
324void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
Eric Christopher7a61d702008-08-08 19:39:37 +0000325 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000326 Module *M = Caller->getParent();
Nick Lewycky6cd0c042009-01-05 00:07:50 +0000327 AttributeWithIndex AWI[3];
328 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
329 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
330 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
331 Constant *F;
332 if (isa<PointerType>(File->getType()))
333 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
334 TD->getIntPtrType(),
335 PointerType::getUnqual(Type::Int8Ty),
336 TD->getIntPtrType(), TD->getIntPtrType(),
337 File->getType(), NULL);
338 else
339 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
340 PointerType::getUnqual(Type::Int8Ty),
341 TD->getIntPtrType(), TD->getIntPtrType(),
342 File->getType(), NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +0000343 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
344 ConstantInt::get(TD->getIntPtrType(), 1), File);
345
346 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
347 CI->setCallingConv(Fn->getCallingConv());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000348}
349
350//===----------------------------------------------------------------------===//
351// Helper Functions
352//===----------------------------------------------------------------------===//
353
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000354/// GetStringLengthH - If we can compute the length of the string pointed to by
355/// the specified pointer, return 'len+1'. If we can't, return 0.
356static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
357 // Look through noop bitcast instructions.
358 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
359 return GetStringLengthH(BCI->getOperand(0), PHIs);
360
361 // If this is a PHI node, there are two cases: either we have already seen it
362 // or we haven't.
363 if (PHINode *PN = dyn_cast<PHINode>(V)) {
364 if (!PHIs.insert(PN))
365 return ~0ULL; // already in the set.
366
367 // If it was new, see if all the input strings are the same length.
368 uint64_t LenSoFar = ~0ULL;
369 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
370 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
371 if (Len == 0) return 0; // Unknown length -> unknown.
372
373 if (Len == ~0ULL) continue;
374
375 if (Len != LenSoFar && LenSoFar != ~0ULL)
376 return 0; // Disagree -> unknown.
377 LenSoFar = Len;
378 }
379
380 // Success, all agree.
381 return LenSoFar;
382 }
383
384 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
385 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
386 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
387 if (Len1 == 0) return 0;
388 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
389 if (Len2 == 0) return 0;
390 if (Len1 == ~0ULL) return Len2;
391 if (Len2 == ~0ULL) return Len1;
392 if (Len1 != Len2) return 0;
393 return Len1;
394 }
395
396 // If the value is not a GEP instruction nor a constant expression with a
397 // GEP instruction, then return unknown.
398 User *GEP = 0;
399 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
400 GEP = GEPI;
401 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
402 if (CE->getOpcode() != Instruction::GetElementPtr)
403 return 0;
404 GEP = CE;
405 } else {
406 return 0;
407 }
408
409 // Make sure the GEP has exactly three arguments.
410 if (GEP->getNumOperands() != 3)
411 return 0;
412
413 // Check to make sure that the first operand of the GEP is an integer and
414 // has value 0 so that we are sure we're indexing into the initializer.
415 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
416 if (!Idx->isZero())
417 return 0;
418 } else
419 return 0;
420
421 // If the second index isn't a ConstantInt, then this is a variable index
422 // into the array. If this occurs, we can't say anything meaningful about
423 // the string.
424 uint64_t StartIdx = 0;
425 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
426 StartIdx = CI->getZExtValue();
427 else
428 return 0;
429
430 // The GEP instruction, constant or instruction, must reference a global
431 // variable that is a constant and is initialized. The referenced constant
432 // initializer is the array that we'll use for optimization.
433 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
434 if (!GV || !GV->isConstant() || !GV->hasInitializer())
435 return 0;
436 Constant *GlobalInit = GV->getInitializer();
437
438 // Handle the ConstantAggregateZero case, which is a degenerate case. The
439 // initializer is constant zero so the length of the string must be zero.
440 if (isa<ConstantAggregateZero>(GlobalInit))
441 return 1; // Len = 0 offset by 1.
442
443 // Must be a Constant Array
444 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
445 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
446 return false;
447
448 // Get the number of elements in the array
449 uint64_t NumElts = Array->getType()->getNumElements();
450
451 // Traverse the constant array from StartIdx (derived above) which is
452 // the place the GEP refers to in the array.
453 for (unsigned i = StartIdx; i != NumElts; ++i) {
454 Constant *Elt = Array->getOperand(i);
455 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
456 if (!CI) // This array isn't suitable, non-int initializer.
457 return 0;
458 if (CI->isZero())
459 return i-StartIdx+1; // We found end of string, success!
460 }
461
462 return 0; // The array isn't null terminated, conservatively return 'unknown'.
463}
464
465/// GetStringLength - If we can compute the length of the string pointed to by
466/// the specified pointer, return 'len+1'. If we can't, return 0.
467static uint64_t GetStringLength(Value *V) {
468 if (!isa<PointerType>(V->getType())) return 0;
469
470 SmallPtrSet<PHINode*, 32> PHIs;
471 uint64_t Len = GetStringLengthH(V, PHIs);
472 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
473 // an empty string as a length.
474 return Len == ~0ULL ? 1 : Len;
475}
476
477/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
478/// value is equal or not-equal to zero.
479static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
480 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
481 UI != E; ++UI) {
482 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
483 if (IC->isEquality())
484 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
485 if (C->isNullValue())
486 continue;
487 // Unknown instruction.
488 return false;
489 }
490 return true;
491}
492
493//===----------------------------------------------------------------------===//
494// Miscellaneous LibCall Optimizations
495//===----------------------------------------------------------------------===//
496
Bill Wendlingac178222008-05-05 21:37:59 +0000497namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000498//===---------------------------------------===//
499// 'exit' Optimizations
500
501/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
502struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000503 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000504 // Verify we have a reasonable prototype for exit.
505 if (Callee->arg_size() == 0 || !CI->use_empty())
506 return 0;
507
508 // Verify the caller is main, and that the result type of main matches the
509 // argument type of exit.
510 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
511 Caller->getReturnType() != CI->getOperand(1)->getType())
512 return 0;
513
514 TerminatorInst *OldTI = CI->getParent()->getTerminator();
515
516 // Create the return after the call.
517 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
518
519 // Drop all successor phi node entries.
520 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
521 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
522
523 // Erase all instructions from after our return instruction until the end of
524 // the block.
525 BasicBlock::iterator FirstDead = RI; ++FirstDead;
526 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
527 return CI;
528 }
529};
530
531//===----------------------------------------------------------------------===//
532// String and Memory LibCall Optimizations
533//===----------------------------------------------------------------------===//
534
535//===---------------------------------------===//
536// 'strcat' Optimizations
537
538struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000539 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000540 // Verify the "strcat" function prototype.
541 const FunctionType *FT = Callee->getFunctionType();
542 if (FT->getNumParams() != 2 ||
543 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
544 FT->getParamType(0) != FT->getReturnType() ||
545 FT->getParamType(1) != FT->getReturnType())
546 return 0;
547
548 // Extract some information from the instruction
549 Value *Dst = CI->getOperand(1);
550 Value *Src = CI->getOperand(2);
551
552 // See if we can get the length of the input string.
553 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000554 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000555 --Len; // Unbias length.
556
557 // Handle the simple, do-nothing case: strcat(x, "") -> x
558 if (Len == 0)
559 return Dst;
560
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000561 EmitStrLenMemCpy(Src, Dst, Len, B);
562 return Dst;
563 }
564
565 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000566 // We need to find the end of the destination string. That's where the
567 // memory is to be moved to. We just generate a call to strlen.
568 Value *DstLen = EmitStrLen(Dst, B);
569
570 // Now that we have the destination's length, we must index into the
571 // destination's pointer to get the actual memcpy destination (end of
572 // the string .. we're concatenating).
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000573 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000574
575 // We have enough information to now generate the memcpy call to do the
576 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
Ed Schoutenb5e0a962009-04-06 13:06:48 +0000577 EmitMemCpy(CpyDst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000578 }
579};
580
581//===---------------------------------------===//
582// 'strncat' Optimizations
583
584struct VISIBILITY_HIDDEN StrNCatOpt : public StrCatOpt {
585 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
586 // Verify the "strncat" function prototype.
587 const FunctionType *FT = Callee->getFunctionType();
588 if (FT->getNumParams() != 3 ||
589 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
590 FT->getParamType(0) != FT->getReturnType() ||
591 FT->getParamType(1) != FT->getReturnType() ||
592 !isa<IntegerType>(FT->getParamType(2)))
593 return 0;
594
595 // Extract some information from the instruction
596 Value *Dst = CI->getOperand(1);
597 Value *Src = CI->getOperand(2);
598 uint64_t Len;
599
600 // We don't do anything if length is not constant
601 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
602 Len = LengthArg->getZExtValue();
603 else
604 return 0;
605
606 // See if we can get the length of the input string.
607 uint64_t SrcLen = GetStringLength(Src);
608 if (SrcLen == 0) return 0;
609 --SrcLen; // Unbias length.
610
611 // Handle the simple, do-nothing cases:
612 // strncat(x, "", c) -> x
613 // strncat(x, c, 0) -> x
614 if (SrcLen == 0 || Len == 0) return Dst;
615
616 // We don't optimize this case
617 if (Len < SrcLen) return 0;
618
619 // strncat(x, s, c) -> strcat(x, s)
620 // s is constant so the strcat can be optimized further
Chris Lattner5db4cdf2009-04-12 18:22:33 +0000621 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000622 return Dst;
623 }
624};
625
626//===---------------------------------------===//
627// 'strchr' Optimizations
628
629struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000630 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000631 // Verify the "strchr" function prototype.
632 const FunctionType *FT = Callee->getFunctionType();
633 if (FT->getNumParams() != 2 ||
634 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
635 FT->getParamType(0) != FT->getReturnType())
636 return 0;
637
638 Value *SrcStr = CI->getOperand(1);
639
640 // If the second operand is non-constant, see if we can compute the length
641 // of the input string and turn this into memchr.
642 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
643 if (CharC == 0) {
644 uint64_t Len = GetStringLength(SrcStr);
645 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
646 return 0;
647
648 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
649 ConstantInt::get(TD->getIntPtrType(), Len), B);
650 }
651
652 // Otherwise, the character is a constant, see if the first argument is
653 // a string literal. If so, we can constant fold.
Bill Wendling0582ae92009-03-13 04:39:26 +0000654 std::string Str;
655 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000656 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000657
658 // strchr can find the nul character.
659 Str += '\0';
660 char CharValue = CharC->getSExtValue();
661
662 // Compute the offset.
663 uint64_t i = 0;
664 while (1) {
665 if (i == Str.size()) // Didn't find the char. strchr returns null.
666 return Constant::getNullValue(CI->getType());
667 // Did we find our match?
668 if (Str[i] == CharValue)
669 break;
670 ++i;
671 }
672
673 // strchr(s+n,c) -> gep(s+n+i,c)
674 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
675 return B.CreateGEP(SrcStr, Idx, "strchr");
676 }
677};
678
679//===---------------------------------------===//
680// 'strcmp' Optimizations
681
682struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000683 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000684 // Verify the "strcmp" function prototype.
685 const FunctionType *FT = Callee->getFunctionType();
686 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
687 FT->getParamType(0) != FT->getParamType(1) ||
688 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
689 return 0;
690
691 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
692 if (Str1P == Str2P) // strcmp(x,x) -> 0
693 return ConstantInt::get(CI->getType(), 0);
694
Bill Wendling0582ae92009-03-13 04:39:26 +0000695 std::string Str1, Str2;
696 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
697 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
698
699 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000700 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
701
Bill Wendling0582ae92009-03-13 04:39:26 +0000702 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000703 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
704
705 // strcmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000706 if (HasStr1 && HasStr2)
707 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
Nick Lewycky13a09e22008-12-21 00:19:21 +0000708
709 // strcmp(P, "x") -> memcmp(P, "x", 2)
710 uint64_t Len1 = GetStringLength(Str1P);
711 uint64_t Len2 = GetStringLength(Str2P);
712 if (Len1 || Len2) {
713 // Choose the smallest Len excluding 0 which means 'unknown'.
714 if (!Len1 || (Len2 && Len2 < Len1))
715 Len1 = Len2;
716 return EmitMemCmp(Str1P, Str2P,
717 ConstantInt::get(TD->getIntPtrType(), Len1), B);
718 }
719
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000720 return 0;
721 }
722};
723
724//===---------------------------------------===//
725// 'strncmp' Optimizations
726
727struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000728 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000729 // Verify the "strncmp" function prototype.
730 const FunctionType *FT = Callee->getFunctionType();
731 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
732 FT->getParamType(0) != FT->getParamType(1) ||
733 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
734 !isa<IntegerType>(FT->getParamType(2)))
735 return 0;
736
737 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
738 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
739 return ConstantInt::get(CI->getType(), 0);
740
741 // Get the length argument if it is constant.
742 uint64_t Length;
743 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
744 Length = LengthArg->getZExtValue();
745 else
746 return 0;
747
748 if (Length == 0) // strncmp(x,y,0) -> 0
749 return ConstantInt::get(CI->getType(), 0);
Bill Wendling0582ae92009-03-13 04:39:26 +0000750
751 std::string Str1, Str2;
752 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
753 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
754
755 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000756 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
757
Bill Wendling0582ae92009-03-13 04:39:26 +0000758 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000759 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
760
761 // strncmp(x, y) -> cnst (if both x and y are constant strings)
Bill Wendling0582ae92009-03-13 04:39:26 +0000762 if (HasStr1 && HasStr2)
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000763 return ConstantInt::get(CI->getType(),
Bill Wendling0582ae92009-03-13 04:39:26 +0000764 strncmp(Str1.c_str(), Str2.c_str(), Length));
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000765 return 0;
766 }
767};
768
769
770//===---------------------------------------===//
771// 'strcpy' Optimizations
772
773struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000774 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000775 // Verify the "strcpy" function prototype.
776 const FunctionType *FT = Callee->getFunctionType();
777 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
778 FT->getParamType(0) != FT->getParamType(1) ||
779 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
780 return 0;
781
782 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
783 if (Dst == Src) // strcpy(x,x) -> x
784 return Src;
785
786 // See if we can get the length of the input string.
787 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000788 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000789
790 // We have enough information to now generate the memcpy call to do the
791 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
792 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
793 return Dst;
794 }
795};
796
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000797//===---------------------------------------===//
798// 'strncpy' Optimizations
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000799
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000800struct VISIBILITY_HIDDEN StrNCpyOpt : public LibCallOptimization {
801 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
802 const FunctionType *FT = Callee->getFunctionType();
803 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
804 FT->getParamType(0) != FT->getParamType(1) ||
805 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
806 !isa<IntegerType>(FT->getParamType(2)))
807 return 0;
808
809 Value *Dst = CI->getOperand(1);
810 Value *Src = CI->getOperand(2);
811 Value *LenOp = CI->getOperand(3);
812
813 // See if we can get the length of the input string.
814 uint64_t SrcLen = GetStringLength(Src);
815 if (SrcLen == 0) return 0;
816 --SrcLen;
817
818 if (SrcLen == 0) {
819 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
820 EmitMemSet(Dst, ConstantInt::get(Type::Int8Ty, '\0'), LenOp, B);
821 return Dst;
822 }
823
824 uint64_t Len;
825 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
826 Len = LengthArg->getZExtValue();
827 else
828 return 0;
829
830 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
831
832 // Let strncpy handle the zero padding
833 if (Len > SrcLen+1) return 0;
834
835 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
836 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
837
838 return Dst;
839 }
840};
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000841
842//===---------------------------------------===//
843// 'strlen' Optimizations
844
845struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000846 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000847 const FunctionType *FT = Callee->getFunctionType();
848 if (FT->getNumParams() != 1 ||
849 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
850 !isa<IntegerType>(FT->getReturnType()))
851 return 0;
852
853 Value *Src = CI->getOperand(1);
854
855 // Constant folding: strlen("xyz") -> 3
856 if (uint64_t Len = GetStringLength(Src))
857 return ConstantInt::get(CI->getType(), Len-1);
858
859 // Handle strlen(p) != 0.
860 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
861
862 // strlen(x) != 0 --> *x != 0
863 // strlen(x) == 0 --> *x == 0
864 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
865 }
866};
867
868//===---------------------------------------===//
Nick Lewycky4c498412009-02-13 15:31:46 +0000869// 'strto*' Optimizations
870
871struct VISIBILITY_HIDDEN StrToOpt : public LibCallOptimization {
872 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
873 const FunctionType *FT = Callee->getFunctionType();
874 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
875 !isa<PointerType>(FT->getParamType(0)) ||
876 !isa<PointerType>(FT->getParamType(1)))
877 return 0;
878
879 Value *EndPtr = CI->getOperand(2);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000880 if (isa<ConstantPointerNull>(EndPtr)) {
881 CI->setOnlyReadsMemory();
Nick Lewycky4c498412009-02-13 15:31:46 +0000882 CI->addAttribute(1, Attribute::NoCapture);
Nick Lewycky02b6a6a2009-02-13 17:08:33 +0000883 }
Nick Lewycky4c498412009-02-13 15:31:46 +0000884
885 return 0;
886 }
887};
888
889
890//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000891// 'memcmp' Optimizations
892
893struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000894 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000895 const FunctionType *FT = Callee->getFunctionType();
896 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
897 !isa<PointerType>(FT->getParamType(1)) ||
898 FT->getReturnType() != Type::Int32Ty)
899 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000900
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000901 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000902
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000903 if (LHS == RHS) // memcmp(s,s,x) -> 0
904 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000905
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000906 // Make sure we have a constant length.
907 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000908 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000909 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000910
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000911 if (Len == 0) // memcmp(s1,s2,0) -> 0
912 return Constant::getNullValue(CI->getType());
913
914 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
915 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
916 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
Chris Lattner0e98e4d2009-05-30 18:43:04 +0000917 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000918 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000919
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000920 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
921 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
922 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000923 const Type *PTy = PointerType::getUnqual(Len == 2 ?
924 Type::Int16Ty : Type::Int32Ty);
925 LHS = B.CreateBitCast(LHS, PTy, "tmp");
926 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000927 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
928 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
929 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
930 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
931 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000932
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000933 return 0;
934 }
935};
936
937//===---------------------------------------===//
938// 'memcpy' Optimizations
939
940struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000941 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000942 const FunctionType *FT = Callee->getFunctionType();
943 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
944 !isa<PointerType>(FT->getParamType(0)) ||
945 !isa<PointerType>(FT->getParamType(1)) ||
946 FT->getParamType(2) != TD->getIntPtrType())
947 return 0;
948
949 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
950 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
951 return CI->getOperand(1);
952 }
953};
954
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000955//===---------------------------------------===//
956// 'memmove' Optimizations
957
958struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
959 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
960 const FunctionType *FT = Callee->getFunctionType();
961 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
962 !isa<PointerType>(FT->getParamType(0)) ||
963 !isa<PointerType>(FT->getParamType(1)) ||
964 FT->getParamType(2) != TD->getIntPtrType())
965 return 0;
966
967 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
968 Module *M = Caller->getParent();
969 Intrinsic::ID IID = Intrinsic::memmove;
970 const Type *Tys[1];
971 Tys[0] = TD->getIntPtrType();
972 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
973 Value *Dst = CastToCStr(CI->getOperand(1), B);
974 Value *Src = CastToCStr(CI->getOperand(2), B);
975 Value *Size = CI->getOperand(3);
976 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
977 B.CreateCall4(MemMove, Dst, Src, Size, Align);
978 return CI->getOperand(1);
979 }
980};
981
982//===---------------------------------------===//
983// 'memset' Optimizations
984
985struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
986 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
987 const FunctionType *FT = Callee->getFunctionType();
988 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
989 !isa<PointerType>(FT->getParamType(0)) ||
990 FT->getParamType(1) != TD->getIntPtrType() ||
991 FT->getParamType(2) != TD->getIntPtrType())
992 return 0;
993
994 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000995 Value *Val = B.CreateTrunc(CI->getOperand(2), Type::Int8Ty);
Chris Lattnerf5b6bc72009-04-12 05:06:39 +0000996 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
Eli Friedmand83ae7d2008-11-30 08:32:11 +0000997 return CI->getOperand(1);
998 }
999};
1000
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001001//===----------------------------------------------------------------------===//
1002// Math Library Optimizations
1003//===----------------------------------------------------------------------===//
1004
1005//===---------------------------------------===//
1006// 'pow*' Optimizations
1007
1008struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001009 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001010 const FunctionType *FT = Callee->getFunctionType();
1011 // Just make sure this has 2 arguments of the same FP type, which match the
1012 // result type.
1013 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1014 FT->getParamType(0) != FT->getParamType(1) ||
1015 !FT->getParamType(0)->isFloatingPoint())
1016 return 0;
1017
1018 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1019 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1020 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1021 return Op1C;
1022 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1023 return EmitUnaryFloatFnCall(Op2, "exp2", B);
1024 }
1025
1026 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1027 if (Op2C == 0) return 0;
1028
1029 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1030 return ConstantFP::get(CI->getType(), 1.0);
1031
1032 if (Op2C->isExactlyValue(0.5)) {
1033 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
1034 // 'unsafe' math optimizations are allowed.
1035 // x pow(x, 0.5) sqrt(x)
1036 // ---------------------------------------------
1037 // -0.0 +0.0 -0.0
1038 // -inf +inf NaN
1039#if 0
1040 // pow(x, 0.5) -> sqrt(x)
1041 return B.CreateCall(get_sqrt(), Op1, "sqrt");
1042#endif
1043 }
1044
1045 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1046 return Op1;
1047 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001048 return B.CreateFMul(Op1, Op1, "pow2");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001049 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1050 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
1051 return 0;
1052 }
1053};
1054
1055//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +00001056// 'exp2' Optimizations
1057
1058struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001059 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +00001060 const FunctionType *FT = Callee->getFunctionType();
1061 // Just make sure this has 1 argument of FP type, which matches the
1062 // result type.
1063 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1064 !FT->getParamType(0)->isFloatingPoint())
1065 return 0;
1066
1067 Value *Op = CI->getOperand(1);
1068 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1069 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1070 Value *LdExpArg = 0;
1071 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1072 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1073 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1074 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1075 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1076 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
1077 }
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001078
Chris Lattnere818f772008-05-02 18:43:35 +00001079 if (LdExpArg) {
1080 const char *Name;
1081 if (Op->getType() == Type::FloatTy)
1082 Name = "ldexpf";
1083 else if (Op->getType() == Type::DoubleTy)
1084 Name = "ldexp";
1085 else
1086 Name = "ldexpl";
1087
1088 Constant *One = ConstantFP::get(APFloat(1.0f));
1089 if (Op->getType() != Type::FloatTy)
1090 One = ConstantExpr::getFPExtend(One, Op->getType());
1091
1092 Module *M = Caller->getParent();
1093 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1094 Op->getType(), Type::Int32Ty,NULL);
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001095 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1096 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1097 CI->setCallingConv(F->getCallingConv());
1098
1099 return CI;
Chris Lattnere818f772008-05-02 18:43:35 +00001100 }
1101 return 0;
1102 }
1103};
Chris Lattnere818f772008-05-02 18:43:35 +00001104
1105//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001106// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1107
1108struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001109 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001110 const FunctionType *FT = Callee->getFunctionType();
1111 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
1112 FT->getParamType(0) != Type::DoubleTy)
1113 return 0;
Anton Korobeynikov9547cdf2009-06-18 20:05:31 +00001114
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001115 // If this is something like 'floor((double)floatval)', convert to floorf.
1116 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1117 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
1118 return 0;
1119
1120 // floor((double)floatval) -> (double)floorf(floatval)
1121 Value *V = Cast->getOperand(0);
1122 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
1123 return B.CreateFPExt(V, Type::DoubleTy);
1124 }
1125};
1126
1127//===----------------------------------------------------------------------===//
1128// Integer Optimizations
1129//===----------------------------------------------------------------------===//
1130
1131//===---------------------------------------===//
1132// 'ffs*' Optimizations
1133
1134struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001135 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001136 const FunctionType *FT = Callee->getFunctionType();
1137 // Just make sure this has 2 arguments of the same FP type, which match the
1138 // result type.
1139 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
1140 !isa<IntegerType>(FT->getParamType(0)))
1141 return 0;
1142
1143 Value *Op = CI->getOperand(1);
1144
1145 // Constant fold.
1146 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1147 if (CI->getValue() == 0) // ffs(0) -> 0.
1148 return Constant::getNullValue(CI->getType());
1149 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
1150 CI->getValue().countTrailingZeros()+1);
1151 }
1152
1153 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1154 const Type *ArgType = Op->getType();
1155 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1156 Intrinsic::cttz, &ArgType, 1);
1157 Value *V = B.CreateCall(F, Op, "cttz");
Chris Lattnerbcc2e7d2009-05-13 06:26:11 +00001158 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001159 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1160
1161 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1162 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
1163 }
1164};
1165
1166//===---------------------------------------===//
1167// 'isdigit' Optimizations
1168
1169struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001170 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001171 const FunctionType *FT = Callee->getFunctionType();
1172 // We require integer(i32)
1173 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1174 FT->getParamType(0) != Type::Int32Ty)
1175 return 0;
1176
1177 // isdigit(c) -> (c-'0') <u 10
1178 Value *Op = CI->getOperand(1);
1179 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
1180 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
1181 return B.CreateZExt(Op, CI->getType());
1182 }
1183};
1184
1185//===---------------------------------------===//
1186// 'isascii' Optimizations
1187
1188struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001189 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001190 const FunctionType *FT = Callee->getFunctionType();
1191 // We require integer(i32)
1192 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1193 FT->getParamType(0) != Type::Int32Ty)
1194 return 0;
1195
1196 // isascii(c) -> c <u 128
1197 Value *Op = CI->getOperand(1);
1198 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
1199 return B.CreateZExt(Op, CI->getType());
1200 }
1201};
Chris Lattner313f0e62008-06-09 08:26:51 +00001202
1203//===---------------------------------------===//
1204// 'abs', 'labs', 'llabs' Optimizations
1205
1206struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001207 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +00001208 const FunctionType *FT = Callee->getFunctionType();
1209 // We require integer(integer) where the types agree.
1210 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1211 FT->getParamType(0) != FT->getReturnType())
1212 return 0;
1213
1214 // abs(x) -> x >s -1 ? x : -x
1215 Value *Op = CI->getOperand(1);
1216 Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
1217 "ispos");
1218 Value *Neg = B.CreateNeg(Op, "neg");
1219 return B.CreateSelect(Pos, Op, Neg);
1220 }
1221};
1222
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001223
1224//===---------------------------------------===//
1225// 'toascii' Optimizations
1226
1227struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001228 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001229 const FunctionType *FT = Callee->getFunctionType();
1230 // We require i32(i32)
1231 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1232 FT->getParamType(0) != Type::Int32Ty)
1233 return 0;
1234
1235 // isascii(c) -> c & 0x7f
1236 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
1237 }
1238};
1239
1240//===----------------------------------------------------------------------===//
1241// Formatting and IO Optimizations
1242//===----------------------------------------------------------------------===//
1243
1244//===---------------------------------------===//
1245// 'printf' Optimizations
1246
1247struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001248 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001249 // Require one fixed pointer argument and an integer/void result.
1250 const FunctionType *FT = Callee->getFunctionType();
1251 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1252 !(isa<IntegerType>(FT->getReturnType()) ||
1253 FT->getReturnType() == Type::VoidTy))
1254 return 0;
1255
1256 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001257 std::string FormatStr;
1258 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1259 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001260
1261 // Empty format string -> noop.
1262 if (FormatStr.empty()) // Tolerate printf's declared void.
1263 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
1264
1265 // printf("x") -> putchar('x'), even for '%'.
1266 if (FormatStr.size() == 1) {
1267 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1268 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1269 }
1270
1271 // printf("foo\n") --> puts("foo")
1272 if (FormatStr[FormatStr.size()-1] == '\n' &&
1273 FormatStr.find('%') == std::string::npos) { // no format characters.
1274 // Create a string literal with no \n on it. We expect the constant merge
1275 // pass to be run after this pass, to merge duplicate strings.
1276 FormatStr.erase(FormatStr.end()-1);
1277 Constant *C = ConstantArray::get(FormatStr, true);
1278 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
1279 C, "str", Callee->getParent());
1280 EmitPutS(C, B);
1281 return CI->use_empty() ? (Value*)CI :
1282 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1283 }
1284
1285 // Optimize specific format strings.
1286 // printf("%c", chr) --> putchar(*(i8*)dst)
1287 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1288 isa<IntegerType>(CI->getOperand(2)->getType())) {
1289 EmitPutChar(CI->getOperand(2), B);
1290 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1291 }
1292
1293 // printf("%s\n", str) --> puts(str)
1294 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1295 isa<PointerType>(CI->getOperand(2)->getType()) &&
1296 CI->use_empty()) {
1297 EmitPutS(CI->getOperand(2), B);
1298 return CI;
1299 }
1300 return 0;
1301 }
1302};
1303
1304//===---------------------------------------===//
1305// 'sprintf' Optimizations
1306
1307struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001308 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001309 // Require two fixed pointer arguments and an integer result.
1310 const FunctionType *FT = Callee->getFunctionType();
1311 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1312 !isa<PointerType>(FT->getParamType(1)) ||
1313 !isa<IntegerType>(FT->getReturnType()))
1314 return 0;
1315
1316 // Check for a fixed format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001317 std::string FormatStr;
1318 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1319 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001320
1321 // If we just have a format string (nothing else crazy) transform it.
1322 if (CI->getNumOperands() == 3) {
1323 // Make sure there's no % in the constant array. We could try to handle
1324 // %% -> % in the future if we cared.
1325 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1326 if (FormatStr[i] == '%')
1327 return 0; // we found a format specifier, bail out.
1328
1329 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1330 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1331 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1332 return ConstantInt::get(CI->getType(), FormatStr.size());
1333 }
1334
1335 // The remaining optimizations require the format string to be "%s" or "%c"
1336 // and have an extra operand.
1337 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1338 return 0;
1339
1340 // Decode the second character of the format string.
1341 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001342 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001343 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1344 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001345 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1346 B.CreateStore(V, Ptr);
1347 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1348 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1349
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001350 return ConstantInt::get(CI->getType(), 1);
1351 }
1352
1353 if (FormatStr[1] == 's') {
1354 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1355 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1356
1357 Value *Len = EmitStrLen(CI->getOperand(3), B);
1358 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1359 "leninc");
1360 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1361
1362 // The sprintf result is the unincremented number of bytes in the string.
1363 return B.CreateIntCast(Len, CI->getType(), false);
1364 }
1365 return 0;
1366 }
1367};
1368
1369//===---------------------------------------===//
1370// 'fwrite' Optimizations
1371
1372struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001373 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001374 // Require a pointer, an integer, an integer, a pointer, returning integer.
1375 const FunctionType *FT = Callee->getFunctionType();
1376 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1377 !isa<IntegerType>(FT->getParamType(1)) ||
1378 !isa<IntegerType>(FT->getParamType(2)) ||
1379 !isa<PointerType>(FT->getParamType(3)) ||
1380 !isa<IntegerType>(FT->getReturnType()))
1381 return 0;
1382
1383 // Get the element size and count.
1384 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1385 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1386 if (!SizeC || !CountC) return 0;
1387 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1388
1389 // If this is writing zero records, remove the call (it's a noop).
1390 if (Bytes == 0)
1391 return ConstantInt::get(CI->getType(), 0);
1392
1393 // If this is writing one byte, turn it into fputc.
1394 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1395 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1396 EmitFPutC(Char, CI->getOperand(4), B);
1397 return ConstantInt::get(CI->getType(), 1);
1398 }
1399
1400 return 0;
1401 }
1402};
1403
1404//===---------------------------------------===//
1405// 'fputs' Optimizations
1406
1407struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001408 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001409 // Require two pointers. Also, we can't optimize if return value is used.
1410 const FunctionType *FT = Callee->getFunctionType();
1411 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1412 !isa<PointerType>(FT->getParamType(1)) ||
1413 !CI->use_empty())
1414 return 0;
1415
1416 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1417 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001418 if (!Len) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001419 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1420 CI->getOperand(2), B);
1421 return CI; // Known to have no uses (see above).
1422 }
1423};
1424
1425//===---------------------------------------===//
1426// 'fprintf' Optimizations
1427
1428struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001429 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001430 // Require two fixed paramters as pointers and integer result.
1431 const FunctionType *FT = Callee->getFunctionType();
1432 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1433 !isa<PointerType>(FT->getParamType(1)) ||
1434 !isa<IntegerType>(FT->getReturnType()))
1435 return 0;
1436
1437 // All the optimizations depend on the format string.
Bill Wendling0582ae92009-03-13 04:39:26 +00001438 std::string FormatStr;
1439 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1440 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001441
1442 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1443 if (CI->getNumOperands() == 3) {
1444 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1445 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001446 return 0; // We found a format specifier.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001447
1448 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1449 FormatStr.size()),
1450 CI->getOperand(1), B);
1451 return ConstantInt::get(CI->getType(), FormatStr.size());
1452 }
1453
1454 // The remaining optimizations require the format string to be "%s" or "%c"
1455 // and have an extra operand.
1456 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1457 return 0;
1458
1459 // Decode the second character of the format string.
1460 if (FormatStr[1] == 'c') {
1461 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1462 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1463 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1464 return ConstantInt::get(CI->getType(), 1);
1465 }
1466
1467 if (FormatStr[1] == 's') {
1468 // fprintf(F, "%s", str) -> fputs(str, F)
1469 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1470 return 0;
1471 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1472 return CI;
1473 }
1474 return 0;
1475 }
1476};
1477
Bill Wendlingac178222008-05-05 21:37:59 +00001478} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001479
1480//===----------------------------------------------------------------------===//
1481// SimplifyLibCalls Pass Implementation
1482//===----------------------------------------------------------------------===//
1483
1484namespace {
1485 /// This pass optimizes well known library functions from libc and libm.
1486 ///
1487 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1488 StringMap<LibCallOptimization*> Optimizations;
1489 // Miscellaneous LibCall Optimizations
1490 ExitOpt Exit;
1491 // String and Memory LibCall Optimizations
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001492 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1493 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1494 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1495 MemSetOpt MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001496 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001497 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001498 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001499 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1500 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001501 // Formatting and IO Optimizations
1502 SPrintFOpt SPrintF; PrintFOpt PrintF;
1503 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001504
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001505 bool Modified; // This is only used by doInitialization.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001506 public:
1507 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001508 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001509
1510 void InitOptimizations();
1511 bool runOnFunction(Function &F);
1512
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001513 void setDoesNotAccessMemory(Function &F);
1514 void setOnlyReadsMemory(Function &F);
1515 void setDoesNotThrow(Function &F);
1516 void setDoesNotCapture(Function &F, unsigned n);
1517 void setDoesNotAlias(Function &F, unsigned n);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001518 bool doInitialization(Module &M);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001519
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001520 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1521 AU.addRequired<TargetData>();
1522 }
1523 };
1524 char SimplifyLibCalls::ID = 0;
1525} // end anonymous namespace.
1526
1527static RegisterPass<SimplifyLibCalls>
1528X("simplify-libcalls", "Simplify well-known library calls");
1529
1530// Public interface to the Simplify LibCalls pass.
1531FunctionPass *llvm::createSimplifyLibCallsPass() {
1532 return new SimplifyLibCalls();
1533}
1534
1535/// Optimizations - Populate the Optimizations map with all the optimizations
1536/// we know.
1537void SimplifyLibCalls::InitOptimizations() {
1538 // Miscellaneous LibCall Optimizations
1539 Optimizations["exit"] = &Exit;
1540
1541 // String and Memory LibCall Optimizations
1542 Optimizations["strcat"] = &StrCat;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001543 Optimizations["strncat"] = &StrNCat;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001544 Optimizations["strchr"] = &StrChr;
1545 Optimizations["strcmp"] = &StrCmp;
1546 Optimizations["strncmp"] = &StrNCmp;
1547 Optimizations["strcpy"] = &StrCpy;
Chris Lattnerf5b6bc72009-04-12 05:06:39 +00001548 Optimizations["strncpy"] = &StrNCpy;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001549 Optimizations["strlen"] = &StrLen;
Nick Lewycky4c498412009-02-13 15:31:46 +00001550 Optimizations["strtol"] = &StrTo;
1551 Optimizations["strtod"] = &StrTo;
1552 Optimizations["strtof"] = &StrTo;
1553 Optimizations["strtoul"] = &StrTo;
1554 Optimizations["strtoll"] = &StrTo;
1555 Optimizations["strtold"] = &StrTo;
1556 Optimizations["strtoull"] = &StrTo;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001557 Optimizations["memcmp"] = &MemCmp;
1558 Optimizations["memcpy"] = &MemCpy;
Eli Friedmand83ae7d2008-11-30 08:32:11 +00001559 Optimizations["memmove"] = &MemMove;
1560 Optimizations["memset"] = &MemSet;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001561
1562 // Math Library Optimizations
1563 Optimizations["powf"] = &Pow;
1564 Optimizations["pow"] = &Pow;
1565 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001566 Optimizations["llvm.pow.f32"] = &Pow;
1567 Optimizations["llvm.pow.f64"] = &Pow;
1568 Optimizations["llvm.pow.f80"] = &Pow;
1569 Optimizations["llvm.pow.f128"] = &Pow;
1570 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001571 Optimizations["exp2l"] = &Exp2;
1572 Optimizations["exp2"] = &Exp2;
1573 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001574 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1575 Optimizations["llvm.exp2.f128"] = &Exp2;
1576 Optimizations["llvm.exp2.f80"] = &Exp2;
1577 Optimizations["llvm.exp2.f64"] = &Exp2;
1578 Optimizations["llvm.exp2.f32"] = &Exp2;
Chris Lattnere818f772008-05-02 18:43:35 +00001579
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001580#ifdef HAVE_FLOORF
1581 Optimizations["floor"] = &UnaryDoubleFP;
1582#endif
1583#ifdef HAVE_CEILF
1584 Optimizations["ceil"] = &UnaryDoubleFP;
1585#endif
1586#ifdef HAVE_ROUNDF
1587 Optimizations["round"] = &UnaryDoubleFP;
1588#endif
1589#ifdef HAVE_RINTF
1590 Optimizations["rint"] = &UnaryDoubleFP;
1591#endif
1592#ifdef HAVE_NEARBYINTF
1593 Optimizations["nearbyint"] = &UnaryDoubleFP;
1594#endif
1595
1596 // Integer Optimizations
1597 Optimizations["ffs"] = &FFS;
1598 Optimizations["ffsl"] = &FFS;
1599 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001600 Optimizations["abs"] = &Abs;
1601 Optimizations["labs"] = &Abs;
1602 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001603 Optimizations["isdigit"] = &IsDigit;
1604 Optimizations["isascii"] = &IsAscii;
1605 Optimizations["toascii"] = &ToAscii;
1606
1607 // Formatting and IO Optimizations
1608 Optimizations["sprintf"] = &SPrintF;
1609 Optimizations["printf"] = &PrintF;
1610 Optimizations["fwrite"] = &FWrite;
1611 Optimizations["fputs"] = &FPuts;
1612 Optimizations["fprintf"] = &FPrintF;
1613}
1614
1615
1616/// runOnFunction - Top level algorithm.
1617///
1618bool SimplifyLibCalls::runOnFunction(Function &F) {
1619 if (Optimizations.empty())
1620 InitOptimizations();
1621
1622 const TargetData &TD = getAnalysis<TargetData>();
1623
Eric Christopher7a61d702008-08-08 19:39:37 +00001624 IRBuilder<> Builder;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001625
1626 bool Changed = false;
1627 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1628 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1629 // Ignore non-calls.
1630 CallInst *CI = dyn_cast<CallInst>(I++);
1631 if (!CI) continue;
1632
1633 // Ignore indirect calls and calls to non-external functions.
1634 Function *Callee = CI->getCalledFunction();
1635 if (Callee == 0 || !Callee->isDeclaration() ||
1636 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1637 continue;
1638
1639 // Ignore unknown calls.
1640 const char *CalleeName = Callee->getNameStart();
1641 StringMap<LibCallOptimization*>::iterator OMI =
1642 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1643 if (OMI == Optimizations.end()) continue;
1644
1645 // Set the builder to the instruction after the call.
1646 Builder.SetInsertPoint(BB, I);
1647
1648 // Try to optimize this call.
1649 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1650 if (Result == 0) continue;
1651
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001652 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1653 DOUT << " into: " << *Result << "\n");
1654
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001655 // Something changed!
1656 Changed = true;
1657 ++NumSimplified;
1658
1659 // Inspect the instruction after the call (which was potentially just
1660 // added) next.
1661 I = CI; ++I;
1662
1663 if (CI != Result && !CI->use_empty()) {
1664 CI->replaceAllUsesWith(Result);
1665 if (!Result->hasName())
1666 Result->takeName(CI);
1667 }
1668 CI->eraseFromParent();
1669 }
1670 }
1671 return Changed;
1672}
1673
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001674// Utility methods for doInitialization.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001675
1676void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1677 if (!F.doesNotAccessMemory()) {
1678 F.setDoesNotAccessMemory();
1679 ++NumAnnotated;
1680 Modified = true;
1681 }
1682}
1683void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1684 if (!F.onlyReadsMemory()) {
1685 F.setOnlyReadsMemory();
1686 ++NumAnnotated;
1687 Modified = true;
1688 }
1689}
1690void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1691 if (!F.doesNotThrow()) {
1692 F.setDoesNotThrow();
1693 ++NumAnnotated;
1694 Modified = true;
1695 }
1696}
1697void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1698 if (!F.doesNotCapture(n)) {
1699 F.setDoesNotCapture(n);
1700 ++NumAnnotated;
1701 Modified = true;
1702 }
1703}
1704void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1705 if (!F.doesNotAlias(n)) {
1706 F.setDoesNotAlias(n);
1707 ++NumAnnotated;
1708 Modified = true;
1709 }
1710}
1711
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001712/// doInitialization - Add attributes to well-known functions.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001713///
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001714bool SimplifyLibCalls::doInitialization(Module &M) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001715 Modified = false;
1716 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1717 Function &F = *I;
1718 if (!F.isDeclaration())
1719 continue;
1720
1721 unsigned NameLen = F.getNameLen();
1722 if (!NameLen)
1723 continue;
1724
1725 const FunctionType *FTy = F.getFunctionType();
1726
1727 const char *NameStr = F.getNameStart();
1728 switch (NameStr[0]) {
1729 case 's':
1730 if (NameLen == 6 && !strcmp(NameStr, "strlen")) {
1731 if (FTy->getNumParams() != 1 ||
1732 !isa<PointerType>(FTy->getParamType(0)))
1733 continue;
1734 setOnlyReadsMemory(F);
1735 setDoesNotThrow(F);
1736 setDoesNotCapture(F, 1);
1737 } else if ((NameLen == 6 && !strcmp(NameStr, "strcpy")) ||
1738 (NameLen == 6 && !strcmp(NameStr, "stpcpy")) ||
1739 (NameLen == 6 && !strcmp(NameStr, "strcat")) ||
Nick Lewycky4c498412009-02-13 15:31:46 +00001740 (NameLen == 6 && !strcmp(NameStr, "strtol")) ||
1741 (NameLen == 6 && !strcmp(NameStr, "strtod")) ||
1742 (NameLen == 6 && !strcmp(NameStr, "strtof")) ||
1743 (NameLen == 7 && !strcmp(NameStr, "strtoul")) ||
1744 (NameLen == 7 && !strcmp(NameStr, "strtoll")) ||
1745 (NameLen == 7 && !strcmp(NameStr, "strtold")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001746 (NameLen == 7 && !strcmp(NameStr, "strncat")) ||
Nick Lewycky4c498412009-02-13 15:31:46 +00001747 (NameLen == 7 && !strcmp(NameStr, "strncpy")) ||
1748 (NameLen == 8 && !strcmp(NameStr, "strtoull"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001749 if (FTy->getNumParams() < 2 ||
1750 !isa<PointerType>(FTy->getParamType(1)))
1751 continue;
1752 setDoesNotThrow(F);
1753 setDoesNotCapture(F, 2);
1754 } else if (NameLen == 7 && !strcmp(NameStr, "strxfrm")) {
1755 if (FTy->getNumParams() != 3 ||
1756 !isa<PointerType>(FTy->getParamType(0)) ||
1757 !isa<PointerType>(FTy->getParamType(1)))
1758 continue;
1759 setDoesNotThrow(F);
1760 setDoesNotCapture(F, 1);
1761 setDoesNotCapture(F, 2);
1762 } else if ((NameLen == 6 && !strcmp(NameStr, "strcmp")) ||
1763 (NameLen == 6 && !strcmp(NameStr, "strspn")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001764 (NameLen == 7 && !strcmp(NameStr, "strncmp")) ||
1765 (NameLen == 7 && !strcmp(NameStr, "strcspn")) ||
1766 (NameLen == 7 && !strcmp(NameStr, "strcoll")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001767 (NameLen == 10 && !strcmp(NameStr, "strcasecmp")) ||
1768 (NameLen == 11 && !strcmp(NameStr, "strncasecmp"))) {
1769 if (FTy->getNumParams() < 2 ||
1770 !isa<PointerType>(FTy->getParamType(0)) ||
1771 !isa<PointerType>(FTy->getParamType(1)))
1772 continue;
1773 setOnlyReadsMemory(F);
1774 setDoesNotThrow(F);
1775 setDoesNotCapture(F, 1);
1776 setDoesNotCapture(F, 2);
1777 } else if ((NameLen == 6 && !strcmp(NameStr, "strstr")) ||
1778 (NameLen == 7 && !strcmp(NameStr, "strpbrk"))) {
1779 if (FTy->getNumParams() != 2 ||
1780 !isa<PointerType>(FTy->getParamType(1)))
1781 continue;
1782 setOnlyReadsMemory(F);
1783 setDoesNotThrow(F);
1784 setDoesNotCapture(F, 2);
1785 } else if ((NameLen == 6 && !strcmp(NameStr, "strtok")) ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001786 (NameLen == 8 && !strcmp(NameStr, "strtok_r"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001787 if (FTy->getNumParams() < 2 ||
1788 !isa<PointerType>(FTy->getParamType(1)))
1789 continue;
1790 setDoesNotThrow(F);
1791 setDoesNotCapture(F, 2);
1792 } else if ((NameLen == 5 && !strcmp(NameStr, "scanf")) ||
1793 (NameLen == 6 && !strcmp(NameStr, "setbuf")) ||
1794 (NameLen == 7 && !strcmp(NameStr, "setvbuf"))) {
1795 if (FTy->getNumParams() < 1 ||
1796 !isa<PointerType>(FTy->getParamType(0)))
1797 continue;
1798 setDoesNotThrow(F);
1799 setDoesNotCapture(F, 1);
Nick Lewycky6cd0c042009-01-05 00:07:50 +00001800 } else if ((NameLen == 6 && !strcmp(NameStr, "strdup")) ||
1801 (NameLen == 7 && !strcmp(NameStr, "strndup"))) {
1802 if (FTy->getNumParams() < 1 ||
1803 !isa<PointerType>(FTy->getReturnType()) ||
1804 !isa<PointerType>(FTy->getParamType(0)))
1805 continue;
1806 setDoesNotThrow(F);
1807 setDoesNotAlias(F, 0);
1808 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00001809 } else if ((NameLen == 4 && !strcmp(NameStr, "stat")) ||
1810 (NameLen == 6 && !strcmp(NameStr, "sscanf")) ||
1811 (NameLen == 7 && !strcmp(NameStr, "sprintf")) ||
1812 (NameLen == 7 && !strcmp(NameStr, "statvfs"))) {
1813 if (FTy->getNumParams() < 2 ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001814 !isa<PointerType>(FTy->getParamType(0)) ||
1815 !isa<PointerType>(FTy->getParamType(1)))
1816 continue;
1817 setDoesNotThrow(F);
1818 setDoesNotCapture(F, 1);
1819 setDoesNotCapture(F, 2);
1820 } else if (NameLen == 8 && !strcmp(NameStr, "snprintf")) {
1821 if (FTy->getNumParams() != 3 ||
1822 !isa<PointerType>(FTy->getParamType(0)) ||
1823 !isa<PointerType>(FTy->getParamType(2)))
1824 continue;
1825 setDoesNotThrow(F);
1826 setDoesNotCapture(F, 1);
1827 setDoesNotCapture(F, 3);
Nick Lewycky225f7472009-02-15 22:47:25 +00001828 } else if (NameLen == 9 && !strcmp(NameStr, "setitimer")) {
1829 if (FTy->getNumParams() != 3 ||
1830 !isa<PointerType>(FTy->getParamType(1)) ||
1831 !isa<PointerType>(FTy->getParamType(2)))
1832 continue;
1833 setDoesNotThrow(F);
1834 setDoesNotCapture(F, 2);
1835 setDoesNotCapture(F, 3);
1836 } else if (NameLen == 6 && !strcmp(NameStr, "system")) {
1837 if (FTy->getNumParams() != 1 ||
1838 !isa<PointerType>(FTy->getParamType(0)))
1839 continue;
1840 // May throw; "system" is a valid pthread cancellation point.
1841 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001842 }
1843 break;
1844 case 'm':
1845 if (NameLen == 6 && !strcmp(NameStr, "memcmp")) {
1846 if (FTy->getNumParams() != 3 ||
1847 !isa<PointerType>(FTy->getParamType(0)) ||
1848 !isa<PointerType>(FTy->getParamType(1)))
1849 continue;
1850 setOnlyReadsMemory(F);
1851 setDoesNotThrow(F);
1852 setDoesNotCapture(F, 1);
1853 setDoesNotCapture(F, 2);
1854 } else if ((NameLen == 6 && !strcmp(NameStr, "memchr")) ||
1855 (NameLen == 7 && !strcmp(NameStr, "memrchr"))) {
1856 if (FTy->getNumParams() != 3)
1857 continue;
1858 setOnlyReadsMemory(F);
1859 setDoesNotThrow(F);
Nick Lewycky225f7472009-02-15 22:47:25 +00001860 } else if ((NameLen == 4 && !strcmp(NameStr, "modf")) ||
1861 (NameLen == 5 && !strcmp(NameStr, "modff")) ||
1862 (NameLen == 5 && !strcmp(NameStr, "modfl")) ||
1863 (NameLen == 6 && !strcmp(NameStr, "memcpy")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001864 (NameLen == 7 && !strcmp(NameStr, "memccpy")) ||
1865 (NameLen == 7 && !strcmp(NameStr, "memmove"))) {
Nick Lewycky225f7472009-02-15 22:47:25 +00001866 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001867 !isa<PointerType>(FTy->getParamType(1)))
1868 continue;
1869 setDoesNotThrow(F);
1870 setDoesNotCapture(F, 2);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001871 } else if (NameLen == 8 && !strcmp(NameStr, "memalign")) {
1872 if (!isa<PointerType>(FTy->getReturnType()))
1873 continue;
1874 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00001875 } else if ((NameLen == 5 && !strcmp(NameStr, "mkdir")) ||
1876 (NameLen == 6 && !strcmp(NameStr, "mktime"))) {
1877 if (FTy->getNumParams() == 0 ||
1878 !isa<PointerType>(FTy->getParamType(0)))
1879 continue;
1880 setDoesNotThrow(F);
1881 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001882 }
1883 break;
1884 case 'r':
1885 if (NameLen == 7 && !strcmp(NameStr, "realloc")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001886 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001887 !isa<PointerType>(FTy->getParamType(0)) ||
1888 !isa<PointerType>(FTy->getReturnType()))
1889 continue;
1890 setDoesNotThrow(F);
1891 setDoesNotAlias(F, 0);
1892 setDoesNotCapture(F, 1);
1893 } else if (NameLen == 4 && !strcmp(NameStr, "read")) {
1894 if (FTy->getNumParams() != 3 ||
1895 !isa<PointerType>(FTy->getParamType(1)))
1896 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001897 // May throw; "read" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001898 setDoesNotCapture(F, 2);
1899 } else if ((NameLen == 5 && !strcmp(NameStr, "rmdir")) ||
1900 (NameLen == 6 && !strcmp(NameStr, "rewind")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00001901 (NameLen == 6 && !strcmp(NameStr, "remove")) ||
1902 (NameLen == 8 && !strcmp(NameStr, "realpath"))) {
1903 if (FTy->getNumParams() < 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001904 !isa<PointerType>(FTy->getParamType(0)))
1905 continue;
1906 setDoesNotThrow(F);
1907 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00001908 } else if ((NameLen == 6 && !strcmp(NameStr, "rename")) ||
1909 (NameLen == 8 && !strcmp(NameStr, "readlink"))) {
1910 if (FTy->getNumParams() < 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001911 !isa<PointerType>(FTy->getParamType(0)) ||
1912 !isa<PointerType>(FTy->getParamType(1)))
1913 continue;
1914 setDoesNotThrow(F);
1915 setDoesNotCapture(F, 1);
1916 setDoesNotCapture(F, 2);
1917 }
1918 break;
1919 case 'w':
1920 if (NameLen == 5 && !strcmp(NameStr, "write")) {
1921 if (FTy->getNumParams() != 3 ||
1922 !isa<PointerType>(FTy->getParamType(1)))
1923 continue;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001924 // May throw; "write" is a valid pthread cancellation point.
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001925 setDoesNotCapture(F, 2);
1926 }
1927 break;
1928 case 'b':
1929 if (NameLen == 5 && !strcmp(NameStr, "bcopy")) {
1930 if (FTy->getNumParams() != 3 ||
1931 !isa<PointerType>(FTy->getParamType(0)) ||
1932 !isa<PointerType>(FTy->getParamType(1)))
1933 continue;
1934 setDoesNotThrow(F);
1935 setDoesNotCapture(F, 1);
1936 setDoesNotCapture(F, 2);
1937 } else if (NameLen == 4 && !strcmp(NameStr, "bcmp")) {
1938 if (FTy->getNumParams() != 3 ||
1939 !isa<PointerType>(FTy->getParamType(0)) ||
1940 !isa<PointerType>(FTy->getParamType(1)))
1941 continue;
1942 setDoesNotThrow(F);
1943 setOnlyReadsMemory(F);
1944 setDoesNotCapture(F, 1);
1945 setDoesNotCapture(F, 2);
1946 } else if (NameLen == 5 && !strcmp(NameStr, "bzero")) {
1947 if (FTy->getNumParams() != 2 ||
1948 !isa<PointerType>(FTy->getParamType(0)))
1949 continue;
1950 setDoesNotThrow(F);
1951 setDoesNotCapture(F, 1);
1952 }
1953 break;
1954 case 'c':
1955 if (NameLen == 6 && !strcmp(NameStr, "calloc")) {
1956 if (FTy->getNumParams() != 2 ||
1957 !isa<PointerType>(FTy->getReturnType()))
1958 continue;
1959 setDoesNotThrow(F);
1960 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00001961 } else if ((NameLen == 5 && !strcmp(NameStr, "chmod")) ||
1962 (NameLen == 5 && !strcmp(NameStr, "chown")) ||
1963 (NameLen == 7 && !strcmp(NameStr, "ctermid")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001964 (NameLen == 8 && !strcmp(NameStr, "clearerr")) ||
1965 (NameLen == 8 && !strcmp(NameStr, "closedir"))) {
1966 if (FTy->getNumParams() == 0 ||
1967 !isa<PointerType>(FTy->getParamType(0)))
1968 continue;
1969 setDoesNotThrow(F);
1970 setDoesNotCapture(F, 1);
1971 }
1972 break;
1973 case 'a':
1974 if ((NameLen == 4 && !strcmp(NameStr, "atoi")) ||
1975 (NameLen == 4 && !strcmp(NameStr, "atol")) ||
1976 (NameLen == 4 && !strcmp(NameStr, "atof")) ||
1977 (NameLen == 5 && !strcmp(NameStr, "atoll"))) {
1978 if (FTy->getNumParams() != 1 ||
1979 !isa<PointerType>(FTy->getParamType(0)))
1980 continue;
1981 setDoesNotThrow(F);
1982 setOnlyReadsMemory(F);
1983 setDoesNotCapture(F, 1);
1984 } else if (NameLen == 6 && !strcmp(NameStr, "access")) {
1985 if (FTy->getNumParams() != 2 ||
1986 !isa<PointerType>(FTy->getParamType(0)))
1987 continue;
1988 setDoesNotThrow(F);
1989 setDoesNotCapture(F, 1);
1990 }
1991 break;
1992 case 'f':
Nick Lewycky0b6679d2009-01-18 04:34:36 +00001993 if (NameLen == 5 && !strcmp(NameStr, "fopen")) {
1994 if (FTy->getNumParams() != 2 ||
1995 !isa<PointerType>(FTy->getReturnType()) ||
1996 !isa<PointerType>(FTy->getParamType(0)) ||
1997 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00001998 continue;
1999 setDoesNotThrow(F);
2000 setDoesNotAlias(F, 0);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002001 setDoesNotCapture(F, 1);
2002 setDoesNotCapture(F, 2);
2003 } else if (NameLen == 6 && !strcmp(NameStr, "fdopen")) {
2004 if (FTy->getNumParams() != 2 ||
2005 !isa<PointerType>(FTy->getReturnType()) ||
2006 !isa<PointerType>(FTy->getParamType(1)))
2007 continue;
2008 setDoesNotThrow(F);
2009 setDoesNotAlias(F, 0);
2010 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002011 } else if ((NameLen == 4 && !strcmp(NameStr, "feof")) ||
2012 (NameLen == 4 && !strcmp(NameStr, "free")) ||
2013 (NameLen == 5 && !strcmp(NameStr, "fseek")) ||
2014 (NameLen == 5 && !strcmp(NameStr, "ftell")) ||
2015 (NameLen == 5 && !strcmp(NameStr, "fgetc")) ||
2016 (NameLen == 6 && !strcmp(NameStr, "fseeko")) ||
2017 (NameLen == 6 && !strcmp(NameStr, "ftello")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002018 (NameLen == 6 && !strcmp(NameStr, "fileno")) ||
2019 (NameLen == 6 && !strcmp(NameStr, "fflush")) ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002020 (NameLen == 6 && !strcmp(NameStr, "fclose")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002021 (NameLen == 7 && !strcmp(NameStr, "fsetpos")) ||
2022 (NameLen == 9 && !strcmp(NameStr, "flockfile")) ||
2023 (NameLen == 11 && !strcmp(NameStr, "funlockfile")) ||
2024 (NameLen == 12 && !strcmp(NameStr, "ftrylockfile"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002025 if (FTy->getNumParams() == 0 ||
2026 !isa<PointerType>(FTy->getParamType(0)))
2027 continue;
2028 setDoesNotThrow(F);
2029 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002030 } else if (NameLen == 6 && !strcmp(NameStr, "ferror")) {
2031 if (FTy->getNumParams() != 1 ||
2032 !isa<PointerType>(FTy->getParamType(0)))
2033 continue;
2034 setDoesNotThrow(F);
2035 setDoesNotCapture(F, 1);
2036 setOnlyReadsMemory(F);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002037 } else if ((NameLen == 5 && !strcmp(NameStr, "fputc")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002038 (NameLen == 5 && !strcmp(NameStr, "fstat")) ||
2039 (NameLen == 5 && !strcmp(NameStr, "frexp")) ||
2040 (NameLen == 6 && !strcmp(NameStr, "frexpf")) ||
2041 (NameLen == 6 && !strcmp(NameStr, "frexpl")) ||
2042 (NameLen == 8 && !strcmp(NameStr, "fstatvfs"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002043 if (FTy->getNumParams() != 2 ||
2044 !isa<PointerType>(FTy->getParamType(1)))
2045 continue;
2046 setDoesNotThrow(F);
2047 setDoesNotCapture(F, 2);
2048 } else if (NameLen == 5 && !strcmp(NameStr, "fgets")) {
2049 if (FTy->getNumParams() != 3 ||
2050 !isa<PointerType>(FTy->getParamType(0)) ||
2051 !isa<PointerType>(FTy->getParamType(2)))
2052 continue;
2053 setDoesNotThrow(F);
2054 setDoesNotCapture(F, 3);
2055 } else if ((NameLen == 5 && !strcmp(NameStr, "fread")) ||
2056 (NameLen == 6 && !strcmp(NameStr, "fwrite"))) {
2057 if (FTy->getNumParams() != 4 ||
2058 !isa<PointerType>(FTy->getParamType(0)) ||
2059 !isa<PointerType>(FTy->getParamType(3)))
2060 continue;
2061 setDoesNotThrow(F);
2062 setDoesNotCapture(F, 1);
2063 setDoesNotCapture(F, 4);
Nick Lewycky225f7472009-02-15 22:47:25 +00002064 } else if ((NameLen == 5 && !strcmp(NameStr, "fputs")) ||
2065 (NameLen == 6 && !strcmp(NameStr, "fscanf")) ||
2066 (NameLen == 7 && !strcmp(NameStr, "fprintf")) ||
2067 (NameLen == 7 && !strcmp(NameStr, "fgetpos"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002068 if (FTy->getNumParams() < 2 ||
2069 !isa<PointerType>(FTy->getParamType(0)) ||
2070 !isa<PointerType>(FTy->getParamType(1)))
2071 continue;
2072 setDoesNotThrow(F);
2073 setDoesNotCapture(F, 1);
2074 setDoesNotCapture(F, 2);
2075 }
2076 break;
2077 case 'g':
2078 if ((NameLen == 4 && !strcmp(NameStr, "getc")) ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002079 (NameLen == 10 && !strcmp(NameStr, "getlogin_r")) ||
2080 (NameLen == 13 && !strcmp(NameStr, "getc_unlocked"))) {
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002081 if (FTy->getNumParams() == 0 ||
2082 !isa<PointerType>(FTy->getParamType(0)))
2083 continue;
2084 setDoesNotThrow(F);
2085 setDoesNotCapture(F, 1);
2086 } else if (NameLen == 6 && !strcmp(NameStr, "getenv")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002087 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002088 !isa<PointerType>(FTy->getParamType(0)))
2089 continue;
2090 setDoesNotThrow(F);
2091 setOnlyReadsMemory(F);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002092 setDoesNotCapture(F, 1);
2093 } else if ((NameLen == 4 && !strcmp(NameStr, "gets")) ||
2094 (NameLen == 7 && !strcmp(NameStr, "getchar"))) {
2095 setDoesNotThrow(F);
Nick Lewycky225f7472009-02-15 22:47:25 +00002096 } else if (NameLen == 9 && !strcmp(NameStr, "getitimer")) {
2097 if (FTy->getNumParams() != 2 ||
2098 !isa<PointerType>(FTy->getParamType(1)))
2099 continue;
2100 setDoesNotThrow(F);
2101 setDoesNotCapture(F, 2);
2102 } else if (NameLen == 8 && !strcmp(NameStr, "getpwnam")) {
2103 if (FTy->getNumParams() != 1 ||
2104 !isa<PointerType>(FTy->getParamType(0)))
2105 continue;
2106 setDoesNotThrow(F);
2107 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002108 }
2109 break;
2110 case 'u':
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002111 if (NameLen == 6 && !strcmp(NameStr, "ungetc")) {
2112 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002113 !isa<PointerType>(FTy->getParamType(1)))
2114 continue;
2115 setDoesNotThrow(F);
2116 setDoesNotCapture(F, 2);
Nick Lewycky225f7472009-02-15 22:47:25 +00002117 } else if ((NameLen == 5 && !strcmp(NameStr, "uname")) ||
2118 (NameLen == 6 && !strcmp(NameStr, "unlink")) ||
2119 (NameLen == 8 && !strcmp(NameStr, "unsetenv"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002120 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002121 !isa<PointerType>(FTy->getParamType(0)))
2122 continue;
2123 setDoesNotThrow(F);
2124 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00002125 } else if ((NameLen == 5 && !strcmp(NameStr, "utime")) ||
2126 (NameLen == 6 && !strcmp(NameStr, "utimes"))) {
2127 if (FTy->getNumParams() != 2 ||
2128 !isa<PointerType>(FTy->getParamType(0)) ||
2129 !isa<PointerType>(FTy->getParamType(1)))
2130 continue;
2131 setDoesNotThrow(F);
2132 setDoesNotCapture(F, 1);
2133 setDoesNotCapture(F, 2);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002134 }
2135 break;
2136 case 'p':
2137 if (NameLen == 4 && !strcmp(NameStr, "putc")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002138 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002139 !isa<PointerType>(FTy->getParamType(1)))
2140 continue;
2141 setDoesNotThrow(F);
2142 setDoesNotCapture(F, 2);
2143 } else if ((NameLen == 4 && !strcmp(NameStr, "puts")) ||
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002144 (NameLen == 6 && !strcmp(NameStr, "printf")) ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002145 (NameLen == 6 && !strcmp(NameStr, "perror"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002146 if (FTy->getNumParams() != 1 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002147 !isa<PointerType>(FTy->getParamType(0)))
2148 continue;
2149 setDoesNotThrow(F);
2150 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002151 } else if ((NameLen == 5 && !strcmp(NameStr, "pread")) ||
2152 (NameLen == 6 && !strcmp(NameStr, "pwrite"))) {
2153 if (FTy->getNumParams() != 4 ||
2154 !isa<PointerType>(FTy->getParamType(1)))
2155 continue;
2156 // May throw; these are valid pthread cancellation points.
2157 setDoesNotCapture(F, 2);
2158 } else if (NameLen == 7 && !strcmp(NameStr, "putchar")) {
2159 setDoesNotThrow(F);
Nick Lewycky225f7472009-02-15 22:47:25 +00002160 } else if (NameLen == 5 && !strcmp(NameStr, "popen")) {
2161 if (FTy->getNumParams() != 2 ||
2162 !isa<PointerType>(FTy->getReturnType()) ||
2163 !isa<PointerType>(FTy->getParamType(0)) ||
2164 !isa<PointerType>(FTy->getParamType(1)))
2165 continue;
2166 setDoesNotThrow(F);
2167 setDoesNotAlias(F, 0);
2168 setDoesNotCapture(F, 1);
2169 setDoesNotCapture(F, 2);
2170 } else if (NameLen == 6 && !strcmp(NameStr, "pclose")) {
2171 if (FTy->getNumParams() != 1 ||
2172 !isa<PointerType>(FTy->getParamType(0)))
2173 continue;
2174 setDoesNotThrow(F);
2175 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002176 }
2177 break;
2178 case 'v':
2179 if (NameLen == 6 && !strcmp(NameStr, "vscanf")) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002180 if (FTy->getNumParams() != 2 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002181 !isa<PointerType>(FTy->getParamType(1)))
2182 continue;
2183 setDoesNotThrow(F);
2184 setDoesNotCapture(F, 1);
2185 } else if ((NameLen == 7 && !strcmp(NameStr, "vsscanf")) ||
2186 (NameLen == 7 && !strcmp(NameStr, "vfscanf"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002187 if (FTy->getNumParams() != 3 ||
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002188 !isa<PointerType>(FTy->getParamType(1)) ||
2189 !isa<PointerType>(FTy->getParamType(2)))
2190 continue;
2191 setDoesNotThrow(F);
2192 setDoesNotCapture(F, 1);
2193 setDoesNotCapture(F, 2);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002194 } else if (NameLen == 6 && !strcmp(NameStr, "valloc")) {
2195 if (!isa<PointerType>(FTy->getReturnType()))
2196 continue;
2197 setDoesNotThrow(F);
2198 setDoesNotAlias(F, 0);
2199 } else if (NameLen == 7 && !strcmp(NameStr, "vprintf")) {
2200 if (FTy->getNumParams() != 2 ||
2201 !isa<PointerType>(FTy->getParamType(0)))
2202 continue;
2203 setDoesNotThrow(F);
2204 setDoesNotCapture(F, 1);
2205 } else if ((NameLen == 8 && !strcmp(NameStr, "vfprintf")) ||
2206 (NameLen == 8 && !strcmp(NameStr, "vsprintf"))) {
2207 if (FTy->getNumParams() != 3 ||
2208 !isa<PointerType>(FTy->getParamType(0)) ||
2209 !isa<PointerType>(FTy->getParamType(1)))
2210 continue;
2211 setDoesNotThrow(F);
2212 setDoesNotCapture(F, 1);
2213 setDoesNotCapture(F, 2);
2214 } else if (NameLen == 9 && !strcmp(NameStr, "vsnprintf")) {
2215 if (FTy->getNumParams() != 4 ||
2216 !isa<PointerType>(FTy->getParamType(0)) ||
2217 !isa<PointerType>(FTy->getParamType(2)))
2218 continue;
2219 setDoesNotThrow(F);
2220 setDoesNotCapture(F, 1);
2221 setDoesNotCapture(F, 3);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002222 }
2223 break;
2224 case 'o':
Nick Lewycky225f7472009-02-15 22:47:25 +00002225 if (NameLen == 4 && !strcmp(NameStr, "open")) {
2226 if (FTy->getNumParams() < 2 ||
2227 !isa<PointerType>(FTy->getParamType(0)))
2228 continue;
2229 // May throw; "open" is a valid pthread cancellation point.
2230 setDoesNotCapture(F, 1);
2231 } else if (NameLen == 7 && !strcmp(NameStr, "opendir")) {
2232 if (FTy->getNumParams() != 1 ||
2233 !isa<PointerType>(FTy->getReturnType()) ||
2234 !isa<PointerType>(FTy->getParamType(0)))
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002235 continue;
2236 setDoesNotThrow(F);
2237 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002238 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002239 }
2240 break;
2241 case 't':
2242 if (NameLen == 7 && !strcmp(NameStr, "tmpfile")) {
2243 if (!isa<PointerType>(FTy->getReturnType()))
2244 continue;
2245 setDoesNotThrow(F);
2246 setDoesNotAlias(F, 0);
Nick Lewycky225f7472009-02-15 22:47:25 +00002247 } else if (NameLen == 5 && !strcmp(NameStr, "times")) {
2248 if (FTy->getNumParams() != 1 ||
2249 !isa<PointerType>(FTy->getParamType(0)))
2250 continue;
2251 setDoesNotThrow(F);
2252 setDoesNotCapture(F, 1);
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002253 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002254 break;
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002255 case 'h':
2256 if ((NameLen == 5 && !strcmp(NameStr, "htonl")) ||
2257 (NameLen == 5 && !strcmp(NameStr, "htons"))) {
2258 setDoesNotThrow(F);
2259 setDoesNotAccessMemory(F);
2260 }
2261 break;
2262 case 'n':
2263 if ((NameLen == 5 && !strcmp(NameStr, "ntohl")) ||
2264 (NameLen == 5 && !strcmp(NameStr, "ntohs"))) {
2265 setDoesNotThrow(F);
2266 setDoesNotAccessMemory(F);
2267 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002268 break;
2269 case 'l':
2270 if (NameLen == 5 && !strcmp(NameStr, "lstat")) {
2271 if (FTy->getNumParams() != 2 ||
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);
2278 } else if (NameLen == 6 && !strcmp(NameStr, "lchown")) {
2279 if (FTy->getNumParams() != 3 ||
2280 !isa<PointerType>(FTy->getParamType(0)))
2281 continue;
2282 setDoesNotThrow(F);
2283 setDoesNotCapture(F, 1);
2284 }
2285 break;
2286 case 'q':
2287 if (NameLen == 5 && !strcmp(NameStr, "qsort")) {
2288 if (FTy->getNumParams() != 4 ||
2289 !isa<PointerType>(FTy->getParamType(3)))
2290 continue;
2291 // May throw; places call through function pointer.
2292 setDoesNotCapture(F, 4);
2293 }
2294 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002295 case '_':
2296 if ((NameLen == 8 && !strcmp(NameStr, "__strdup")) ||
2297 (NameLen == 9 && !strcmp(NameStr, "__strndup"))) {
2298 if (FTy->getNumParams() < 1 ||
2299 !isa<PointerType>(FTy->getReturnType()) ||
2300 !isa<PointerType>(FTy->getParamType(0)))
2301 continue;
2302 setDoesNotThrow(F);
2303 setDoesNotAlias(F, 0);
2304 setDoesNotCapture(F, 1);
2305 } else if (NameLen == 10 && !strcmp(NameStr, "__strtok_r")) {
2306 if (FTy->getNumParams() != 3 ||
2307 !isa<PointerType>(FTy->getParamType(1)))
2308 continue;
2309 setDoesNotThrow(F);
2310 setDoesNotCapture(F, 2);
2311 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_getc")) {
2312 if (FTy->getNumParams() != 1 ||
2313 !isa<PointerType>(FTy->getParamType(0)))
2314 continue;
2315 setDoesNotThrow(F);
2316 setDoesNotCapture(F, 1);
2317 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_putc")) {
2318 if (FTy->getNumParams() != 2 ||
2319 !isa<PointerType>(FTy->getParamType(1)))
2320 continue;
2321 setDoesNotThrow(F);
2322 setDoesNotCapture(F, 2);
2323 }
Nick Lewycky225f7472009-02-15 22:47:25 +00002324 break;
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002325 case 1:
2326 if (NameLen == 15 && !strcmp(NameStr, "\1__isoc99_scanf")) {
2327 if (FTy->getNumParams() < 1 ||
2328 !isa<PointerType>(FTy->getParamType(0)))
2329 continue;
2330 setDoesNotThrow(F);
2331 setDoesNotCapture(F, 1);
Nick Lewycky225f7472009-02-15 22:47:25 +00002332 } else if ((NameLen == 7 && !strcmp(NameStr, "\1stat64")) ||
2333 (NameLen == 8 && !strcmp(NameStr, "\1lstat64")) ||
2334 (NameLen == 10 && !strcmp(NameStr, "\1statvfs64")) ||
2335 (NameLen == 16 && !strcmp(NameStr, "\1__isoc99_sscanf"))) {
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002336 if (FTy->getNumParams() < 1 ||
Nick Lewycky225f7472009-02-15 22:47:25 +00002337 !isa<PointerType>(FTy->getParamType(0)) ||
2338 !isa<PointerType>(FTy->getParamType(1)))
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002339 continue;
2340 setDoesNotThrow(F);
2341 setDoesNotCapture(F, 1);
2342 setDoesNotCapture(F, 2);
Nick Lewycky225f7472009-02-15 22:47:25 +00002343 } else if (NameLen == 8 && !strcmp(NameStr, "\1fopen64")) {
2344 if (FTy->getNumParams() != 2 ||
2345 !isa<PointerType>(FTy->getReturnType()) ||
2346 !isa<PointerType>(FTy->getParamType(0)) ||
2347 !isa<PointerType>(FTy->getParamType(1)))
2348 continue;
2349 setDoesNotThrow(F);
2350 setDoesNotAlias(F, 0);
2351 setDoesNotCapture(F, 1);
2352 setDoesNotCapture(F, 2);
2353 } else if ((NameLen == 9 && !strcmp(NameStr, "\1fseeko64")) ||
2354 (NameLen == 9 && !strcmp(NameStr, "\1ftello64"))) {
2355 if (FTy->getNumParams() == 0 ||
2356 !isa<PointerType>(FTy->getParamType(0)))
2357 continue;
2358 setDoesNotThrow(F);
2359 setDoesNotCapture(F, 1);
2360 } else if (NameLen == 10 && !strcmp(NameStr, "\1tmpfile64")) {
2361 if (!isa<PointerType>(FTy->getReturnType()))
2362 continue;
2363 setDoesNotThrow(F);
2364 setDoesNotAlias(F, 0);
2365 } else if ((NameLen == 8 && !strcmp(NameStr, "\1fstat64")) ||
2366 (NameLen == 11 && !strcmp(NameStr, "\1fstatvfs64"))) {
2367 if (FTy->getNumParams() != 2 ||
2368 !isa<PointerType>(FTy->getParamType(1)))
2369 continue;
2370 setDoesNotThrow(F);
2371 setDoesNotCapture(F, 2);
2372 } else if (NameLen == 7 && !strcmp(NameStr, "\1open64")) {
2373 if (FTy->getNumParams() < 2 ||
2374 !isa<PointerType>(FTy->getParamType(0)))
2375 continue;
2376 // May throw; "open" is a valid pthread cancellation point.
2377 setDoesNotCapture(F, 1);
Nick Lewycky0b6679d2009-01-18 04:34:36 +00002378 }
Nick Lewycky0f8df9a2009-01-04 20:27:34 +00002379 break;
2380 }
2381 }
2382 return Modified;
2383}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002384
2385// TODO:
2386// Additional cases that we need to add to this file:
2387//
2388// cbrt:
2389// * cbrt(expN(X)) -> expN(x/3)
2390// * cbrt(sqrt(x)) -> pow(x,1/6)
2391// * cbrt(sqrt(x)) -> pow(x,1/9)
2392//
2393// cos, cosf, cosl:
2394// * cos(-x) -> cos(x)
2395//
2396// exp, expf, expl:
2397// * exp(log(x)) -> x
2398//
2399// log, logf, logl:
2400// * log(exp(x)) -> x
2401// * log(x**y) -> y*log(x)
2402// * log(exp(y)) -> y*log(e)
2403// * log(exp2(y)) -> y*log(2)
2404// * log(exp10(y)) -> y*log(10)
2405// * log(sqrt(x)) -> 0.5*log(x)
2406// * log(pow(x,y)) -> y*log(x)
2407//
2408// lround, lroundf, lroundl:
2409// * lround(cnst) -> cnst'
2410//
2411// memcmp:
2412// * memcmp(x,y,l) -> cnst
2413// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2414//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002415// pow, powf, powl:
2416// * pow(exp(x),y) -> exp(x*y)
2417// * pow(sqrt(x),y) -> pow(x,y*0.5)
2418// * pow(pow(x,y),z)-> pow(x,y*z)
2419//
2420// puts:
2421// * puts("") -> putchar("\n")
2422//
2423// round, roundf, roundl:
2424// * round(cnst) -> cnst'
2425//
2426// signbit:
2427// * signbit(cnst) -> cnst'
2428// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2429//
2430// sqrt, sqrtf, sqrtl:
2431// * sqrt(expN(x)) -> expN(x*0.5)
2432// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2433// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2434//
2435// stpcpy:
2436// * stpcpy(str, "literal") ->
2437// llvm.memcpy(str,"literal",strlen("literal")+1,1)
2438// strrchr:
2439// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2440// (if c is a constant integer and s is a constant string)
2441// * strrchr(s1,0) -> strchr(s1,0)
2442//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00002443// strpbrk:
2444// * strpbrk(s,a) -> offset_in_for(s,a)
2445// (if s and a are both constant strings)
2446// * strpbrk(s,"") -> 0
2447// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2448//
2449// strspn, strcspn:
2450// * strspn(s,a) -> const_int (if both args are constant)
2451// * strspn("",a) -> 0
2452// * strspn(s,"") -> 0
2453// * strcspn(s,a) -> const_int (if both args are constant)
2454// * strcspn("",a) -> 0
2455// * strcspn(s,"") -> strlen(a)
2456//
2457// strstr:
2458// * strstr(x,x) -> x
2459// * strstr(s1,s2) -> offset_of_s2_in(s1)
2460// (if s1 and s2 are constant strings)
2461//
2462// tan, tanf, tanl:
2463// * tan(atan(x)) -> x
2464//
2465// trunc, truncf, truncl:
2466// * trunc(cnst) -> cnst'
2467//
2468//