Move GetStringLength and helper from SimplifyLibCalls to ValueTracking.
[oota-llvm.git] / lib / Transforms / Scalar / SimplifyLibCalls.cpp
1 //===- 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).   Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/IRBuilder.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Config/config.h"
34 using namespace llvm;
35
36 STATISTIC(NumSimplified, "Number of library calls simplified");
37 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
38
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.
45 namespace {
46 class LibCallOptimization {
47 protected:
48   Function *Caller;
49   const TargetData *TD;
50   LLVMContext* Context;
51 public:
52   LibCallOptimization() { }
53   virtual ~LibCallOptimization() {}
54
55   /// CallOptimizer - This pure virtual method is implemented by base classes to
56   /// do various optimizations.  If this returns null then no transformation was
57   /// performed.  If it returns CI, then it transformed the call and CI is to be
58   /// deleted.  If it returns something else, replace CI with the new value and
59   /// delete CI.
60   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
61     =0;
62
63   Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
64     Caller = CI->getParent()->getParent();
65     this->TD = TD;
66     if (CI->getCalledFunction())
67       Context = &CI->getCalledFunction()->getContext();
68     return CallOptimizer(CI->getCalledFunction(), CI, B);
69   }
70
71   /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
72   Value *CastToCStr(Value *V, IRBuilder<> &B);
73
74   /// EmitStrLen - Emit a call to the strlen function to the builder, for the
75   /// specified pointer.  Ptr is required to be some pointer type, and the
76   /// return value has 'intptr_t' type.
77   Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
78
79   /// EmitStrChr - Emit a call to the strchr function to the builder, for the
80   /// specified pointer and character.  Ptr is required to be some pointer type,
81   /// and the return value has 'i8*' type.
82   Value *EmitStrChr(Value *Ptr, char C, IRBuilder<> &B);
83
84   /// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
85   /// specified pointer arguments.
86   Value *EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B);
87   
88   /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This
89   /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
90   Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
91                     unsigned Align, IRBuilder<> &B);
92
93   /// EmitMemMove - Emit a call to the memmove function to the builder.  This
94   /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
95   Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
96                      unsigned Align, IRBuilder<> &B);
97
98   /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
99   /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
100   Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
101
102   /// EmitMemCmp - Emit a call to the memcmp function.
103   Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
104
105   /// EmitMemSet - Emit a call to the memset function
106   Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
107
108   /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name'
109   /// (e.g.  'floor').  This function is known to take a single of type matching
110   /// 'Op' and returns one value with the same type.  If 'Op' is a long double,
111   /// 'l' is added as the suffix of name, if 'Op' is a float, we add a 'f'
112   /// suffix.
113   Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
114                               const AttrListPtr &Attrs);
115
116   /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
117   /// is an integer.
118   Value *EmitPutChar(Value *Char, IRBuilder<> &B);
119
120   /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
121   /// some pointer.
122   void EmitPutS(Value *Str, IRBuilder<> &B);
123
124   /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
125   /// an i32, and File is a pointer to FILE.
126   void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
127
128   /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
129   /// pointer and File is a pointer to FILE.
130   void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
131
132   /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
133   /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
134   void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
135
136 };
137 } // End anonymous namespace.
138
139 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
140 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
141   return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
142 }
143
144 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
145 /// specified pointer.  This always returns an integer value of size intptr_t.
146 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
147   Module *M = Caller->getParent();
148   AttributeWithIndex AWI[2];
149   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
150   AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
151                                    Attribute::NoUnwind);
152
153   Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
154                                            TD->getIntPtrType(*Context),
155                                            Type::getInt8PtrTy(*Context),
156                                            NULL);
157   CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
158   if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
159     CI->setCallingConv(F->getCallingConv());
160
161   return CI;
162 }
163
164 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
165 /// specified pointer and character.  Ptr is required to be some pointer type,
166 /// and the return value has 'i8*' type.
167 Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
168   Module *M = Caller->getParent();
169   AttributeWithIndex AWI =
170     AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
171
172   const Type *I8Ptr = Type::getInt8PtrTy(*Context);
173   const Type *I32Ty = Type::getInt32Ty(*Context);
174   Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
175                                             I8Ptr, I8Ptr, I32Ty, NULL);
176   CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
177                                ConstantInt::get(I32Ty, C), "strchr");
178   if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
179     CI->setCallingConv(F->getCallingConv());
180   return CI;
181 }
182
183 /// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
184 /// specified pointer arguments.
185 Value *LibCallOptimization::EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B) {
186   Module *M = Caller->getParent();
187   AttributeWithIndex AWI[2];
188   AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
189   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
190   const Type *I8Ptr = Type::getInt8PtrTy(*Context);
191   Value *StrCpy = M->getOrInsertFunction("strcpy", AttrListPtr::get(AWI, 2),
192                                          I8Ptr, I8Ptr, I8Ptr, NULL);
193   CallInst *CI = B.CreateCall2(StrCpy, CastToCStr(Dst, B), CastToCStr(Src, B),
194                                "strcpy");
195   if (const Function *F = dyn_cast<Function>(StrCpy->stripPointerCasts()))
196     CI->setCallingConv(F->getCallingConv());
197   return CI;
198 }
199
200 /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This always
201 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
202 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
203                                        unsigned Align, IRBuilder<> &B) {
204   Module *M = Caller->getParent();
205   const Type *Ty = Len->getType();
206   Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
207   Dst = CastToCStr(Dst, B);
208   Src = CastToCStr(Src, B);
209   return B.CreateCall4(MemCpy, Dst, Src, Len,
210                        ConstantInt::get(Type::getInt32Ty(*Context), Align));
211 }
212
213 /// EmitMemMove - Emit a call to the memmove function to the builder.  This
214 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
215 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
216                                         unsigned Align, IRBuilder<> &B) {
217   Module *M = Caller->getParent();
218   const Type *Ty = TD->getIntPtrType(*Context);
219   Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
220   Dst = CastToCStr(Dst, B);
221   Src = CastToCStr(Src, B);
222   Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
223   return B.CreateCall4(MemMove, Dst, Src, Len, A);
224 }
225
226 /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
227 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
228 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
229                                        Value *Len, IRBuilder<> &B) {
230   Module *M = Caller->getParent();
231   AttributeWithIndex AWI;
232   AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
233
234   Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
235                                          Type::getInt8PtrTy(*Context),
236                                          Type::getInt8PtrTy(*Context),
237                                          Type::getInt32Ty(*Context),
238                                          TD->getIntPtrType(*Context),
239                                          NULL);
240   CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
241
242   if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
243     CI->setCallingConv(F->getCallingConv());
244
245   return CI;
246 }
247
248 /// EmitMemCmp - Emit a call to the memcmp function.
249 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
250                                        Value *Len, IRBuilder<> &B) {
251   Module *M = Caller->getParent();
252   AttributeWithIndex AWI[3];
253   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
254   AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
255   AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
256                                    Attribute::NoUnwind);
257
258   Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
259                                          Type::getInt32Ty(*Context),
260                                          Type::getInt8PtrTy(*Context),
261                                          Type::getInt8PtrTy(*Context),
262                                          TD->getIntPtrType(*Context), NULL);
263   CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
264                                Len, "memcmp");
265
266   if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
267     CI->setCallingConv(F->getCallingConv());
268
269   return CI;
270 }
271
272 /// EmitMemSet - Emit a call to the memset function
273 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
274                                        Value *Len, IRBuilder<> &B) {
275  Module *M = Caller->getParent();
276  Intrinsic::ID IID = Intrinsic::memset;
277  const Type *Tys[1];
278  Tys[0] = Len->getType();
279  Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
280  Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
281  return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
282 }
283
284 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
285 /// 'floor').  This function is known to take a single of type matching 'Op' and
286 /// returns one value with the same type.  If 'Op' is a long double, 'l' is
287 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
288 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
289                                                  IRBuilder<> &B,
290                                                  const AttrListPtr &Attrs) {
291   char NameBuffer[20];
292   if (!Op->getType()->isDoubleTy()) {
293     // If we need to add a suffix, copy into NameBuffer.
294     unsigned NameLen = strlen(Name);
295     assert(NameLen < sizeof(NameBuffer)-2);
296     memcpy(NameBuffer, Name, NameLen);
297     if (Op->getType()->isFloatTy())
298       NameBuffer[NameLen] = 'f';  // floorf
299     else
300       NameBuffer[NameLen] = 'l';  // floorl
301     NameBuffer[NameLen+1] = 0;
302     Name = NameBuffer;
303   }
304
305   Module *M = Caller->getParent();
306   Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
307                                          Op->getType(), NULL);
308   CallInst *CI = B.CreateCall(Callee, Op, Name);
309   CI->setAttributes(Attrs);
310   if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
311     CI->setCallingConv(F->getCallingConv());
312
313   return CI;
314 }
315
316 /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
317 /// is an integer.
318 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
319   Module *M = Caller->getParent();
320   Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
321                                           Type::getInt32Ty(*Context), NULL);
322   CallInst *CI = B.CreateCall(PutChar,
323                               B.CreateIntCast(Char,
324                               Type::getInt32Ty(*Context),
325                               /*isSigned*/true,
326                               "chari"),
327                               "putchar");
328
329   if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
330     CI->setCallingConv(F->getCallingConv());
331   return CI;
332 }
333
334 /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
335 /// some pointer.
336 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
337   Module *M = Caller->getParent();
338   AttributeWithIndex AWI[2];
339   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
340   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
341
342   Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
343                                        Type::getInt32Ty(*Context),
344                                        Type::getInt8PtrTy(*Context),
345                                        NULL);
346   CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
347   if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
348     CI->setCallingConv(F->getCallingConv());
349
350 }
351
352 /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
353 /// an integer and File is a pointer to FILE.
354 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
355   Module *M = Caller->getParent();
356   AttributeWithIndex AWI[2];
357   AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
358   AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
359   Constant *F;
360   if (File->getType()->isPointerTy())
361     F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
362                                Type::getInt32Ty(*Context),
363                                Type::getInt32Ty(*Context), File->getType(),
364                                NULL);
365   else
366     F = M->getOrInsertFunction("fputc",
367                                Type::getInt32Ty(*Context),
368                                Type::getInt32Ty(*Context),
369                                File->getType(), NULL);
370   Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
371                          "chari");
372   CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
373
374   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
375     CI->setCallingConv(Fn->getCallingConv());
376 }
377
378 /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
379 /// pointer and File is a pointer to FILE.
380 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
381   Module *M = Caller->getParent();
382   AttributeWithIndex AWI[3];
383   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
384   AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
385   AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
386   Constant *F;
387   if (File->getType()->isPointerTy())
388     F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
389                                Type::getInt32Ty(*Context),
390                                Type::getInt8PtrTy(*Context),
391                                File->getType(), NULL);
392   else
393     F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
394                                Type::getInt8PtrTy(*Context),
395                                File->getType(), NULL);
396   CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
397
398   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
399     CI->setCallingConv(Fn->getCallingConv());
400 }
401
402 /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
403 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
404 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
405                                      IRBuilder<> &B) {
406   Module *M = Caller->getParent();
407   AttributeWithIndex AWI[3];
408   AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
409   AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
410   AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
411   Constant *F;
412   if (File->getType()->isPointerTy())
413     F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
414                                TD->getIntPtrType(*Context),
415                                Type::getInt8PtrTy(*Context),
416                                TD->getIntPtrType(*Context),
417                                TD->getIntPtrType(*Context),
418                                File->getType(), NULL);
419   else
420     F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
421                                Type::getInt8PtrTy(*Context),
422                                TD->getIntPtrType(*Context),
423                                TD->getIntPtrType(*Context),
424                                File->getType(), NULL);
425   CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
426                         ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
427
428   if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
429     CI->setCallingConv(Fn->getCallingConv());
430 }
431
432 //===----------------------------------------------------------------------===//
433 // Helper Functions
434 //===----------------------------------------------------------------------===//
435
436 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
437 /// value is equal or not-equal to zero.
438 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
439   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
440        UI != E; ++UI) {
441     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
442       if (IC->isEquality())
443         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
444           if (C->isNullValue())
445             continue;
446     // Unknown instruction.
447     return false;
448   }
449   return true;
450 }
451
452 //===----------------------------------------------------------------------===//
453 // String and Memory LibCall Optimizations
454 //===----------------------------------------------------------------------===//
455
456 //===---------------------------------------===//
457 // 'strcat' Optimizations
458 namespace {
459 struct StrCatOpt : public LibCallOptimization {
460   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
461     // Verify the "strcat" function prototype.
462     const FunctionType *FT = Callee->getFunctionType();
463     if (FT->getNumParams() != 2 ||
464         FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
465         FT->getParamType(0) != FT->getReturnType() ||
466         FT->getParamType(1) != FT->getReturnType())
467       return 0;
468
469     // Extract some information from the instruction
470     Value *Dst = CI->getOperand(1);
471     Value *Src = CI->getOperand(2);
472
473     // See if we can get the length of the input string.
474     uint64_t Len = GetStringLength(Src);
475     if (Len == 0) return 0;
476     --Len;  // Unbias length.
477
478     // Handle the simple, do-nothing case: strcat(x, "") -> x
479     if (Len == 0)
480       return Dst;
481
482     // These optimizations require TargetData.
483     if (!TD) return 0;
484
485     EmitStrLenMemCpy(Src, Dst, Len, B);
486     return Dst;
487   }
488
489   void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
490     // We need to find the end of the destination string.  That's where the
491     // memory is to be moved to. We just generate a call to strlen.
492     Value *DstLen = EmitStrLen(Dst, B);
493
494     // Now that we have the destination's length, we must index into the
495     // destination's pointer to get the actual memcpy destination (end of
496     // the string .. we're concatenating).
497     Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
498
499     // We have enough information to now generate the memcpy call to do the
500     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
501     EmitMemCpy(CpyDst, Src,
502                ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
503   }
504 };
505
506 //===---------------------------------------===//
507 // 'strncat' Optimizations
508
509 struct StrNCatOpt : public StrCatOpt {
510   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
511     // Verify the "strncat" function prototype.
512     const FunctionType *FT = Callee->getFunctionType();
513     if (FT->getNumParams() != 3 ||
514         FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
515         FT->getParamType(0) != FT->getReturnType() ||
516         FT->getParamType(1) != FT->getReturnType() ||
517         !FT->getParamType(2)->isIntegerTy())
518       return 0;
519
520     // Extract some information from the instruction
521     Value *Dst = CI->getOperand(1);
522     Value *Src = CI->getOperand(2);
523     uint64_t Len;
524
525     // We don't do anything if length is not constant
526     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
527       Len = LengthArg->getZExtValue();
528     else
529       return 0;
530
531     // See if we can get the length of the input string.
532     uint64_t SrcLen = GetStringLength(Src);
533     if (SrcLen == 0) return 0;
534     --SrcLen;  // Unbias length.
535
536     // Handle the simple, do-nothing cases:
537     // strncat(x, "", c) -> x
538     // strncat(x,  c, 0) -> x
539     if (SrcLen == 0 || Len == 0) return Dst;
540
541     // These optimizations require TargetData.
542     if (!TD) return 0;
543
544     // We don't optimize this case
545     if (Len < SrcLen) return 0;
546
547     // strncat(x, s, c) -> strcat(x, s)
548     // s is constant so the strcat can be optimized further
549     EmitStrLenMemCpy(Src, Dst, SrcLen, B);
550     return Dst;
551   }
552 };
553
554 //===---------------------------------------===//
555 // 'strchr' Optimizations
556
557 struct StrChrOpt : public LibCallOptimization {
558   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
559     // Verify the "strchr" function prototype.
560     const FunctionType *FT = Callee->getFunctionType();
561     if (FT->getNumParams() != 2 ||
562         FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
563         FT->getParamType(0) != FT->getReturnType())
564       return 0;
565
566     Value *SrcStr = CI->getOperand(1);
567
568     // If the second operand is non-constant, see if we can compute the length
569     // of the input string and turn this into memchr.
570     ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
571     if (CharC == 0) {
572       // These optimizations require TargetData.
573       if (!TD) return 0;
574
575       uint64_t Len = GetStringLength(SrcStr);
576       if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32))// memchr needs i32.
577         return 0;
578
579       return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
580                         ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
581     }
582
583     // Otherwise, the character is a constant, see if the first argument is
584     // a string literal.  If so, we can constant fold.
585     std::string Str;
586     if (!GetConstantStringInfo(SrcStr, Str))
587       return 0;
588
589     // strchr can find the nul character.
590     Str += '\0';
591     char CharValue = CharC->getSExtValue();
592
593     // Compute the offset.
594     uint64_t i = 0;
595     while (1) {
596       if (i == Str.size())    // Didn't find the char.  strchr returns null.
597         return Constant::getNullValue(CI->getType());
598       // Did we find our match?
599       if (Str[i] == CharValue)
600         break;
601       ++i;
602     }
603
604     // strchr(s+n,c)  -> gep(s+n+i,c)
605     Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
606     return B.CreateGEP(SrcStr, Idx, "strchr");
607   }
608 };
609
610 //===---------------------------------------===//
611 // 'strcmp' Optimizations
612
613 struct StrCmpOpt : public LibCallOptimization {
614   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
615     // Verify the "strcmp" function prototype.
616     const FunctionType *FT = Callee->getFunctionType();
617     if (FT->getNumParams() != 2 ||
618         !FT->getReturnType()->isIntegerTy(32) ||
619         FT->getParamType(0) != FT->getParamType(1) ||
620         FT->getParamType(0) != Type::getInt8PtrTy(*Context))
621       return 0;
622
623     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
624     if (Str1P == Str2P)      // strcmp(x,x)  -> 0
625       return ConstantInt::get(CI->getType(), 0);
626
627     std::string Str1, Str2;
628     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
629     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
630
631     if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
632       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
633
634     if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
635       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
636
637     // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
638     if (HasStr1 && HasStr2)
639       return ConstantInt::get(CI->getType(),
640                                      strcmp(Str1.c_str(),Str2.c_str()));
641
642     // strcmp(P, "x") -> memcmp(P, "x", 2)
643     uint64_t Len1 = GetStringLength(Str1P);
644     uint64_t Len2 = GetStringLength(Str2P);
645     if (Len1 && Len2) {
646       // These optimizations require TargetData.
647       if (!TD) return 0;
648
649       return EmitMemCmp(Str1P, Str2P,
650                         ConstantInt::get(TD->getIntPtrType(*Context),
651                         std::min(Len1, Len2)), B);
652     }
653
654     return 0;
655   }
656 };
657
658 //===---------------------------------------===//
659 // 'strncmp' Optimizations
660
661 struct StrNCmpOpt : public LibCallOptimization {
662   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
663     // Verify the "strncmp" function prototype.
664     const FunctionType *FT = Callee->getFunctionType();
665     if (FT->getNumParams() != 3 ||
666         !FT->getReturnType()->isIntegerTy(32) ||
667         FT->getParamType(0) != FT->getParamType(1) ||
668         FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
669         !FT->getParamType(2)->isIntegerTy())
670       return 0;
671
672     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
673     if (Str1P == Str2P)      // strncmp(x,x,n)  -> 0
674       return ConstantInt::get(CI->getType(), 0);
675
676     // Get the length argument if it is constant.
677     uint64_t Length;
678     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
679       Length = LengthArg->getZExtValue();
680     else
681       return 0;
682
683     if (Length == 0) // strncmp(x,y,0)   -> 0
684       return ConstantInt::get(CI->getType(), 0);
685
686     std::string Str1, Str2;
687     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
688     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
689
690     if (HasStr1 && Str1.empty())  // strncmp("", x, n) -> *x
691       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
692
693     if (HasStr2 && Str2.empty())  // strncmp(x, "", n) -> *x
694       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
695
696     // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
697     if (HasStr1 && HasStr2)
698       return ConstantInt::get(CI->getType(),
699                               strncmp(Str1.c_str(), Str2.c_str(), Length));
700     return 0;
701   }
702 };
703
704
705 //===---------------------------------------===//
706 // 'strcpy' Optimizations
707
708 struct StrCpyOpt : public LibCallOptimization {
709   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
710     // Verify the "strcpy" function prototype.
711     const FunctionType *FT = Callee->getFunctionType();
712     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
713         FT->getParamType(0) != FT->getParamType(1) ||
714         FT->getParamType(0) != Type::getInt8PtrTy(*Context))
715       return 0;
716
717     Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
718     if (Dst == Src)      // strcpy(x,x)  -> x
719       return Src;
720
721     // These optimizations require TargetData.
722     if (!TD) return 0;
723
724     // See if we can get the length of the input string.
725     uint64_t Len = GetStringLength(Src);
726     if (Len == 0) return 0;
727
728     // We have enough information to now generate the memcpy call to do the
729     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
730     EmitMemCpy(Dst, Src,
731                ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
732     return Dst;
733   }
734 };
735
736 //===---------------------------------------===//
737 // 'strncpy' Optimizations
738
739 struct StrNCpyOpt : public LibCallOptimization {
740   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
741     const FunctionType *FT = Callee->getFunctionType();
742     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
743         FT->getParamType(0) != FT->getParamType(1) ||
744         FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
745         !FT->getParamType(2)->isIntegerTy())
746       return 0;
747
748     Value *Dst = CI->getOperand(1);
749     Value *Src = CI->getOperand(2);
750     Value *LenOp = CI->getOperand(3);
751
752     // See if we can get the length of the input string.
753     uint64_t SrcLen = GetStringLength(Src);
754     if (SrcLen == 0) return 0;
755     --SrcLen;
756
757     if (SrcLen == 0) {
758       // strncpy(x, "", y) -> memset(x, '\0', y, 1)
759       EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
760                  B);
761       return Dst;
762     }
763
764     uint64_t Len;
765     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
766       Len = LengthArg->getZExtValue();
767     else
768       return 0;
769
770     if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
771
772     // These optimizations require TargetData.
773     if (!TD) return 0;
774
775     // Let strncpy handle the zero padding
776     if (Len > SrcLen+1) return 0;
777
778     // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
779     EmitMemCpy(Dst, Src,
780                ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
781
782     return Dst;
783   }
784 };
785
786 //===---------------------------------------===//
787 // 'strlen' Optimizations
788
789 struct StrLenOpt : public LibCallOptimization {
790   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
791     const FunctionType *FT = Callee->getFunctionType();
792     if (FT->getNumParams() != 1 ||
793         FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
794         !FT->getReturnType()->isIntegerTy())
795       return 0;
796
797     Value *Src = CI->getOperand(1);
798
799     // Constant folding: strlen("xyz") -> 3
800     if (uint64_t Len = GetStringLength(Src))
801       return ConstantInt::get(CI->getType(), Len-1);
802
803     // strlen(x) != 0 --> *x != 0
804     // strlen(x) == 0 --> *x == 0
805     if (IsOnlyUsedInZeroEqualityComparison(CI))
806       return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
807     return 0;
808   }
809 };
810
811 //===---------------------------------------===//
812 // 'strto*' Optimizations.  This handles strtol, strtod, strtof, strtoul, etc.
813
814 struct StrToOpt : public LibCallOptimization {
815   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
816     const FunctionType *FT = Callee->getFunctionType();
817     if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
818         !FT->getParamType(0)->isPointerTy() ||
819         !FT->getParamType(1)->isPointerTy())
820       return 0;
821
822     Value *EndPtr = CI->getOperand(2);
823     if (isa<ConstantPointerNull>(EndPtr)) {
824       CI->setOnlyReadsMemory();
825       CI->addAttribute(1, Attribute::NoCapture);
826     }
827
828     return 0;
829   }
830 };
831
832 //===---------------------------------------===//
833 // 'strstr' Optimizations
834
835 struct StrStrOpt : public LibCallOptimization {
836   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
837     const FunctionType *FT = Callee->getFunctionType();
838     if (FT->getNumParams() != 2 ||
839         !FT->getParamType(0)->isPointerTy() ||
840         !FT->getParamType(1)->isPointerTy() ||
841         !FT->getReturnType()->isPointerTy())
842       return 0;
843
844     // fold strstr(x, x) -> x.
845     if (CI->getOperand(1) == CI->getOperand(2))
846       return B.CreateBitCast(CI->getOperand(1), CI->getType());
847
848     // See if either input string is a constant string.
849     std::string SearchStr, ToFindStr;
850     bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
851     bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
852
853     // fold strstr(x, "") -> x.
854     if (HasStr2 && ToFindStr.empty())
855       return B.CreateBitCast(CI->getOperand(1), CI->getType());
856
857     // If both strings are known, constant fold it.
858     if (HasStr1 && HasStr2) {
859       std::string::size_type Offset = SearchStr.find(ToFindStr);
860
861       if (Offset == std::string::npos) // strstr("foo", "bar") -> null
862         return Constant::getNullValue(CI->getType());
863
864       // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
865       Value *Result = CastToCStr(CI->getOperand(1), B);
866       Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
867       return B.CreateBitCast(Result, CI->getType());
868     }
869
870     // fold strstr(x, "y") -> strchr(x, 'y').
871     if (HasStr2 && ToFindStr.size() == 1)
872       return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
873                              CI->getType());
874     return 0;
875   }
876 };
877
878
879 //===---------------------------------------===//
880 // 'memcmp' Optimizations
881
882 struct MemCmpOpt : public LibCallOptimization {
883   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
884     const FunctionType *FT = Callee->getFunctionType();
885     if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
886         !FT->getParamType(1)->isPointerTy() ||
887         !FT->getReturnType()->isIntegerTy(32))
888       return 0;
889
890     Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
891
892     if (LHS == RHS)  // memcmp(s,s,x) -> 0
893       return Constant::getNullValue(CI->getType());
894
895     // Make sure we have a constant length.
896     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
897     if (!LenC) return 0;
898     uint64_t Len = LenC->getZExtValue();
899
900     if (Len == 0) // memcmp(s1,s2,0) -> 0
901       return Constant::getNullValue(CI->getType());
902
903     if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
904       Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
905       Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
906       return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
907     }
908
909     // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
910     std::string LHSStr, RHSStr;
911     if (GetConstantStringInfo(LHS, LHSStr) &&
912         GetConstantStringInfo(RHS, RHSStr)) {
913       // Make sure we're not reading out-of-bounds memory.
914       if (Len > LHSStr.length() || Len > RHSStr.length())
915         return 0;
916       uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
917       return ConstantInt::get(CI->getType(), Ret);
918     }
919
920     return 0;
921   }
922 };
923
924 //===---------------------------------------===//
925 // 'memcpy' Optimizations
926
927 struct MemCpyOpt : public LibCallOptimization {
928   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
929     // These optimizations require TargetData.
930     if (!TD) return 0;
931
932     const FunctionType *FT = Callee->getFunctionType();
933     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
934         !FT->getParamType(0)->isPointerTy() ||
935         !FT->getParamType(1)->isPointerTy() ||
936         FT->getParamType(2) != TD->getIntPtrType(*Context))
937       return 0;
938
939     // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
940     EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
941     return CI->getOperand(1);
942   }
943 };
944
945 //===---------------------------------------===//
946 // 'memmove' Optimizations
947
948 struct MemMoveOpt : public LibCallOptimization {
949   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
950     // These optimizations require TargetData.
951     if (!TD) return 0;
952
953     const FunctionType *FT = Callee->getFunctionType();
954     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
955         !FT->getParamType(0)->isPointerTy() ||
956         !FT->getParamType(1)->isPointerTy() ||
957         FT->getParamType(2) != TD->getIntPtrType(*Context))
958       return 0;
959
960     // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
961     EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
962     return CI->getOperand(1);
963   }
964 };
965
966 //===---------------------------------------===//
967 // 'memset' Optimizations
968
969 struct MemSetOpt : public LibCallOptimization {
970   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
971     // These optimizations require TargetData.
972     if (!TD) return 0;
973
974     const FunctionType *FT = Callee->getFunctionType();
975     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
976         !FT->getParamType(0)->isPointerTy() ||
977         !FT->getParamType(1)->isIntegerTy() ||
978         FT->getParamType(2) != TD->getIntPtrType(*Context))
979       return 0;
980
981     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
982     Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
983                                  false);
984     EmitMemSet(CI->getOperand(1), Val,  CI->getOperand(3), B);
985     return CI->getOperand(1);
986   }
987 };
988
989 //===----------------------------------------------------------------------===//
990 // Object Size Checking Optimizations
991 //===----------------------------------------------------------------------===//
992
993 //===---------------------------------------===//
994 // 'memcpy_chk' Optimizations
995
996 struct MemCpyChkOpt : public LibCallOptimization {
997   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
998     // These optimizations require TargetData.
999     if (!TD) return 0;
1000
1001     const FunctionType *FT = Callee->getFunctionType();
1002     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1003         !FT->getParamType(0)->isPointerTy() ||
1004         !FT->getParamType(1)->isPointerTy() ||
1005         !FT->getParamType(3)->isIntegerTy() ||
1006         FT->getParamType(2) != TD->getIntPtrType(*Context))
1007       return 0;
1008
1009     ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1010     if (!SizeCI)
1011       return 0;
1012     if (SizeCI->isAllOnesValue()) {
1013       EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1014       return CI->getOperand(1);
1015     }
1016
1017     return 0;
1018   }
1019 };
1020
1021 //===---------------------------------------===//
1022 // 'memset_chk' Optimizations
1023
1024 struct MemSetChkOpt : public LibCallOptimization {
1025   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1026     // These optimizations require TargetData.
1027     if (!TD) return 0;
1028
1029     const FunctionType *FT = Callee->getFunctionType();
1030     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1031         !FT->getParamType(0)->isPointerTy() ||
1032         !FT->getParamType(1)->isIntegerTy() ||
1033         !FT->getParamType(3)->isIntegerTy() ||
1034         FT->getParamType(2) != TD->getIntPtrType(*Context))
1035       return 0;
1036
1037     ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1038     if (!SizeCI)
1039       return 0;
1040     if (SizeCI->isAllOnesValue()) {
1041       Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1042                                    false);
1043       EmitMemSet(CI->getOperand(1), Val,  CI->getOperand(3), B);
1044       return CI->getOperand(1);
1045     }
1046
1047     return 0;
1048   }
1049 };
1050
1051 //===---------------------------------------===//
1052 // 'memmove_chk' Optimizations
1053
1054 struct MemMoveChkOpt : public LibCallOptimization {
1055   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1056     // These optimizations require TargetData.
1057     if (!TD) return 0;
1058
1059     const FunctionType *FT = Callee->getFunctionType();
1060     if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1061         !FT->getParamType(0)->isPointerTy() ||
1062         !FT->getParamType(1)->isPointerTy() ||
1063         !FT->getParamType(3)->isIntegerTy() ||
1064         FT->getParamType(2) != TD->getIntPtrType(*Context))
1065       return 0;
1066
1067     ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1068     if (!SizeCI)
1069       return 0;
1070     if (SizeCI->isAllOnesValue()) {
1071       EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1072                   1, B);
1073       return CI->getOperand(1);
1074     }
1075
1076     return 0;
1077   }
1078 };
1079
1080 struct StrCpyChkOpt : public LibCallOptimization {
1081   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1082     const FunctionType *FT = Callee->getFunctionType();
1083     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1084         !FT->getParamType(0)->isPointerTy() ||
1085         !FT->getParamType(1)->isPointerTy())
1086       return 0;
1087
1088     ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(3));
1089     if (!SizeCI)
1090       return 0;
1091     
1092     // If a) we don't have any length information, or b) we know this will
1093     // fit then just lower to a plain strcpy. Otherwise we'll keep our
1094     // strcpy_chk call which may fail at runtime if the size is too long.
1095     // TODO: It might be nice to get a maximum length out of the possible
1096     // string lengths for varying.
1097     if (SizeCI->isAllOnesValue() ||
1098         SizeCI->getZExtValue() >= GetStringLength(CI->getOperand(2)))
1099       return EmitStrCpy(CI->getOperand(1), CI->getOperand(2), B);
1100
1101     return 0;
1102   }
1103 };
1104
1105   
1106 //===----------------------------------------------------------------------===//
1107 // Math Library Optimizations
1108 //===----------------------------------------------------------------------===//
1109
1110 //===---------------------------------------===//
1111 // 'pow*' Optimizations
1112
1113 struct PowOpt : public LibCallOptimization {
1114   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1115     const FunctionType *FT = Callee->getFunctionType();
1116     // Just make sure this has 2 arguments of the same FP type, which match the
1117     // result type.
1118     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1119         FT->getParamType(0) != FT->getParamType(1) ||
1120         !FT->getParamType(0)->isFloatingPointTy())
1121       return 0;
1122
1123     Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1124     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1125       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
1126         return Op1C;
1127       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
1128         return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1129     }
1130
1131     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1132     if (Op2C == 0) return 0;
1133
1134     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
1135       return ConstantFP::get(CI->getType(), 1.0);
1136
1137     if (Op2C->isExactlyValue(0.5)) {
1138       // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1139       // This is faster than calling pow, and still handles negative zero
1140       // and negative infinite correctly.
1141       // TODO: In fast-math mode, this could be just sqrt(x).
1142       // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1143       Value *Inf = ConstantFP::getInfinity(CI->getType());
1144       Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1145       Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1146                                          Callee->getAttributes());
1147       Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1148                                          Callee->getAttributes());
1149       Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1150       Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1151       return Sel;
1152     }
1153
1154     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
1155       return Op1;
1156     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
1157       return B.CreateFMul(Op1, Op1, "pow2");
1158     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1159       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1160                           Op1, "powrecip");
1161     return 0;
1162   }
1163 };
1164
1165 //===---------------------------------------===//
1166 // 'exp2' Optimizations
1167
1168 struct Exp2Opt : public LibCallOptimization {
1169   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1170     const FunctionType *FT = Callee->getFunctionType();
1171     // Just make sure this has 1 argument of FP type, which matches the
1172     // result type.
1173     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1174         !FT->getParamType(0)->isFloatingPointTy())
1175       return 0;
1176
1177     Value *Op = CI->getOperand(1);
1178     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
1179     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
1180     Value *LdExpArg = 0;
1181     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1182       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1183         LdExpArg = B.CreateSExt(OpC->getOperand(0),
1184                                 Type::getInt32Ty(*Context), "tmp");
1185     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1186       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1187         LdExpArg = B.CreateZExt(OpC->getOperand(0),
1188                                 Type::getInt32Ty(*Context), "tmp");
1189     }
1190
1191     if (LdExpArg) {
1192       const char *Name;
1193       if (Op->getType()->isFloatTy())
1194         Name = "ldexpf";
1195       else if (Op->getType()->isDoubleTy())
1196         Name = "ldexp";
1197       else
1198         Name = "ldexpl";
1199
1200       Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1201       if (!Op->getType()->isFloatTy())
1202         One = ConstantExpr::getFPExtend(One, Op->getType());
1203
1204       Module *M = Caller->getParent();
1205       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1206                                              Op->getType(),
1207                                              Type::getInt32Ty(*Context),NULL);
1208       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1209       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1210         CI->setCallingConv(F->getCallingConv());
1211
1212       return CI;
1213     }
1214     return 0;
1215   }
1216 };
1217
1218 //===---------------------------------------===//
1219 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1220
1221 struct UnaryDoubleFPOpt : public LibCallOptimization {
1222   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1223     const FunctionType *FT = Callee->getFunctionType();
1224     if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1225         !FT->getParamType(0)->isDoubleTy())
1226       return 0;
1227
1228     // If this is something like 'floor((double)floatval)', convert to floorf.
1229     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1230     if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1231       return 0;
1232
1233     // floor((double)floatval) -> (double)floorf(floatval)
1234     Value *V = Cast->getOperand(0);
1235     V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1236                              Callee->getAttributes());
1237     return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1238   }
1239 };
1240
1241 //===----------------------------------------------------------------------===//
1242 // Integer Optimizations
1243 //===----------------------------------------------------------------------===//
1244
1245 //===---------------------------------------===//
1246 // 'ffs*' Optimizations
1247
1248 struct FFSOpt : public LibCallOptimization {
1249   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1250     const FunctionType *FT = Callee->getFunctionType();
1251     // Just make sure this has 2 arguments of the same FP type, which match the
1252     // result type.
1253     if (FT->getNumParams() != 1 ||
1254         !FT->getReturnType()->isIntegerTy(32) ||
1255         !FT->getParamType(0)->isIntegerTy())
1256       return 0;
1257
1258     Value *Op = CI->getOperand(1);
1259
1260     // Constant fold.
1261     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1262       if (CI->getValue() == 0)  // ffs(0) -> 0.
1263         return Constant::getNullValue(CI->getType());
1264       return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1265                               CI->getValue().countTrailingZeros()+1);
1266     }
1267
1268     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1269     const Type *ArgType = Op->getType();
1270     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1271                                          Intrinsic::cttz, &ArgType, 1);
1272     Value *V = B.CreateCall(F, Op, "cttz");
1273     V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1274     V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1275
1276     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1277     return B.CreateSelect(Cond, V,
1278                           ConstantInt::get(Type::getInt32Ty(*Context), 0));
1279   }
1280 };
1281
1282 //===---------------------------------------===//
1283 // 'isdigit' Optimizations
1284
1285 struct IsDigitOpt : public LibCallOptimization {
1286   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1287     const FunctionType *FT = Callee->getFunctionType();
1288     // We require integer(i32)
1289     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1290         !FT->getParamType(0)->isIntegerTy(32))
1291       return 0;
1292
1293     // isdigit(c) -> (c-'0') <u 10
1294     Value *Op = CI->getOperand(1);
1295     Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1296                      "isdigittmp");
1297     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1298                          "isdigit");
1299     return B.CreateZExt(Op, CI->getType());
1300   }
1301 };
1302
1303 //===---------------------------------------===//
1304 // 'isascii' Optimizations
1305
1306 struct IsAsciiOpt : public LibCallOptimization {
1307   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1308     const FunctionType *FT = Callee->getFunctionType();
1309     // We require integer(i32)
1310     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1311         !FT->getParamType(0)->isIntegerTy(32))
1312       return 0;
1313
1314     // isascii(c) -> c <u 128
1315     Value *Op = CI->getOperand(1);
1316     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1317                          "isascii");
1318     return B.CreateZExt(Op, CI->getType());
1319   }
1320 };
1321
1322 //===---------------------------------------===//
1323 // 'abs', 'labs', 'llabs' Optimizations
1324
1325 struct AbsOpt : public LibCallOptimization {
1326   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1327     const FunctionType *FT = Callee->getFunctionType();
1328     // We require integer(integer) where the types agree.
1329     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
1330         FT->getParamType(0) != FT->getReturnType())
1331       return 0;
1332
1333     // abs(x) -> x >s -1 ? x : -x
1334     Value *Op = CI->getOperand(1);
1335     Value *Pos = B.CreateICmpSGT(Op,
1336                              Constant::getAllOnesValue(Op->getType()),
1337                                  "ispos");
1338     Value *Neg = B.CreateNeg(Op, "neg");
1339     return B.CreateSelect(Pos, Op, Neg);
1340   }
1341 };
1342
1343
1344 //===---------------------------------------===//
1345 // 'toascii' Optimizations
1346
1347 struct ToAsciiOpt : public LibCallOptimization {
1348   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1349     const FunctionType *FT = Callee->getFunctionType();
1350     // We require i32(i32)
1351     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1352         !FT->getParamType(0)->isIntegerTy(32))
1353       return 0;
1354
1355     // isascii(c) -> c & 0x7f
1356     return B.CreateAnd(CI->getOperand(1),
1357                        ConstantInt::get(CI->getType(),0x7F));
1358   }
1359 };
1360
1361 //===----------------------------------------------------------------------===//
1362 // Formatting and IO Optimizations
1363 //===----------------------------------------------------------------------===//
1364
1365 //===---------------------------------------===//
1366 // 'printf' Optimizations
1367
1368 struct PrintFOpt : public LibCallOptimization {
1369   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1370     // Require one fixed pointer argument and an integer/void result.
1371     const FunctionType *FT = Callee->getFunctionType();
1372     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
1373         !(FT->getReturnType()->isIntegerTy() ||
1374           FT->getReturnType()->isVoidTy()))
1375       return 0;
1376
1377     // Check for a fixed format string.
1378     std::string FormatStr;
1379     if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1380       return 0;
1381
1382     // Empty format string -> noop.
1383     if (FormatStr.empty())  // Tolerate printf's declared void.
1384       return CI->use_empty() ? (Value*)CI :
1385                                ConstantInt::get(CI->getType(), 0);
1386
1387     // printf("x") -> putchar('x'), even for '%'.  Return the result of putchar
1388     // in case there is an error writing to stdout.
1389     if (FormatStr.size() == 1) {
1390       Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1391                                                 FormatStr[0]), B);
1392       if (CI->use_empty()) return CI;
1393       return B.CreateIntCast(Res, CI->getType(), true);
1394     }
1395
1396     // printf("foo\n") --> puts("foo")
1397     if (FormatStr[FormatStr.size()-1] == '\n' &&
1398         FormatStr.find('%') == std::string::npos) {  // no format characters.
1399       // Create a string literal with no \n on it.  We expect the constant merge
1400       // pass to be run after this pass, to merge duplicate strings.
1401       FormatStr.erase(FormatStr.end()-1);
1402       Constant *C = ConstantArray::get(*Context, FormatStr, true);
1403       C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1404                              GlobalVariable::InternalLinkage, C, "str");
1405       EmitPutS(C, B);
1406       return CI->use_empty() ? (Value*)CI :
1407                     ConstantInt::get(CI->getType(), FormatStr.size()+1);
1408     }
1409
1410     // Optimize specific format strings.
1411     // printf("%c", chr) --> putchar(*(i8*)dst)
1412     if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1413         CI->getOperand(2)->getType()->isIntegerTy()) {
1414       Value *Res = EmitPutChar(CI->getOperand(2), B);
1415
1416       if (CI->use_empty()) return CI;
1417       return B.CreateIntCast(Res, CI->getType(), true);
1418     }
1419
1420     // printf("%s\n", str) --> puts(str)
1421     if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1422         CI->getOperand(2)->getType()->isPointerTy() &&
1423         CI->use_empty()) {
1424       EmitPutS(CI->getOperand(2), B);
1425       return CI;
1426     }
1427     return 0;
1428   }
1429 };
1430
1431 //===---------------------------------------===//
1432 // 'sprintf' Optimizations
1433
1434 struct SPrintFOpt : public LibCallOptimization {
1435   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1436     // Require two fixed pointer arguments and an integer result.
1437     const FunctionType *FT = Callee->getFunctionType();
1438     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1439         !FT->getParamType(1)->isPointerTy() ||
1440         !FT->getReturnType()->isIntegerTy())
1441       return 0;
1442
1443     // Check for a fixed format string.
1444     std::string FormatStr;
1445     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1446       return 0;
1447
1448     // If we just have a format string (nothing else crazy) transform it.
1449     if (CI->getNumOperands() == 3) {
1450       // Make sure there's no % in the constant array.  We could try to handle
1451       // %% -> % in the future if we cared.
1452       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1453         if (FormatStr[i] == '%')
1454           return 0; // we found a format specifier, bail out.
1455
1456       // These optimizations require TargetData.
1457       if (!TD) return 0;
1458
1459       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1460       EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1461           ConstantInt::get
1462                  (TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1463       return ConstantInt::get(CI->getType(), FormatStr.size());
1464     }
1465
1466     // The remaining optimizations require the format string to be "%s" or "%c"
1467     // and have an extra operand.
1468     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1469       return 0;
1470
1471     // Decode the second character of the format string.
1472     if (FormatStr[1] == 'c') {
1473       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1474       if (!CI->getOperand(3)->getType()->isIntegerTy()) return 0;
1475       Value *V = B.CreateTrunc(CI->getOperand(3),
1476                                Type::getInt8Ty(*Context), "char");
1477       Value *Ptr = CastToCStr(CI->getOperand(1), B);
1478       B.CreateStore(V, Ptr);
1479       Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1480                         "nul");
1481       B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1482
1483       return ConstantInt::get(CI->getType(), 1);
1484     }
1485
1486     if (FormatStr[1] == 's') {
1487       // These optimizations require TargetData.
1488       if (!TD) return 0;
1489
1490       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1491       if (!CI->getOperand(3)->getType()->isPointerTy()) return 0;
1492
1493       Value *Len = EmitStrLen(CI->getOperand(3), B);
1494       Value *IncLen = B.CreateAdd(Len,
1495                                   ConstantInt::get(Len->getType(), 1),
1496                                   "leninc");
1497       EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1498
1499       // The sprintf result is the unincremented number of bytes in the string.
1500       return B.CreateIntCast(Len, CI->getType(), false);
1501     }
1502     return 0;
1503   }
1504 };
1505
1506 //===---------------------------------------===//
1507 // 'fwrite' Optimizations
1508
1509 struct FWriteOpt : public LibCallOptimization {
1510   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1511     // Require a pointer, an integer, an integer, a pointer, returning integer.
1512     const FunctionType *FT = Callee->getFunctionType();
1513     if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
1514         !FT->getParamType(1)->isIntegerTy() ||
1515         !FT->getParamType(2)->isIntegerTy() ||
1516         !FT->getParamType(3)->isPointerTy() ||
1517         !FT->getReturnType()->isIntegerTy())
1518       return 0;
1519
1520     // Get the element size and count.
1521     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1522     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1523     if (!SizeC || !CountC) return 0;
1524     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1525
1526     // If this is writing zero records, remove the call (it's a noop).
1527     if (Bytes == 0)
1528       return ConstantInt::get(CI->getType(), 0);
1529
1530     // If this is writing one byte, turn it into fputc.
1531     if (Bytes == 1) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
1532       Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1533       EmitFPutC(Char, CI->getOperand(4), B);
1534       return ConstantInt::get(CI->getType(), 1);
1535     }
1536
1537     return 0;
1538   }
1539 };
1540
1541 //===---------------------------------------===//
1542 // 'fputs' Optimizations
1543
1544 struct FPutsOpt : public LibCallOptimization {
1545   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1546     // These optimizations require TargetData.
1547     if (!TD) return 0;
1548
1549     // Require two pointers.  Also, we can't optimize if return value is used.
1550     const FunctionType *FT = Callee->getFunctionType();
1551     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1552         !FT->getParamType(1)->isPointerTy() ||
1553         !CI->use_empty())
1554       return 0;
1555
1556     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1557     uint64_t Len = GetStringLength(CI->getOperand(1));
1558     if (!Len) return 0;
1559     EmitFWrite(CI->getOperand(1),
1560                ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1561                CI->getOperand(2), B);
1562     return CI;  // Known to have no uses (see above).
1563   }
1564 };
1565
1566 //===---------------------------------------===//
1567 // 'fprintf' Optimizations
1568
1569 struct FPrintFOpt : public LibCallOptimization {
1570   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1571     // Require two fixed paramters as pointers and integer result.
1572     const FunctionType *FT = Callee->getFunctionType();
1573     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
1574         !FT->getParamType(1)->isPointerTy() ||
1575         !FT->getReturnType()->isIntegerTy())
1576       return 0;
1577
1578     // All the optimizations depend on the format string.
1579     std::string FormatStr;
1580     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1581       return 0;
1582
1583     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1584     if (CI->getNumOperands() == 3) {
1585       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1586         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
1587           return 0; // We found a format specifier.
1588
1589       // These optimizations require TargetData.
1590       if (!TD) return 0;
1591
1592       EmitFWrite(CI->getOperand(2),
1593                  ConstantInt::get(TD->getIntPtrType(*Context),
1594                                   FormatStr.size()),
1595                  CI->getOperand(1), B);
1596       return ConstantInt::get(CI->getType(), FormatStr.size());
1597     }
1598
1599     // The remaining optimizations require the format string to be "%s" or "%c"
1600     // and have an extra operand.
1601     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1602       return 0;
1603
1604     // Decode the second character of the format string.
1605     if (FormatStr[1] == 'c') {
1606       // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1607       if (!CI->getOperand(3)->getType()->isIntegerTy()) return 0;
1608       EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1609       return ConstantInt::get(CI->getType(), 1);
1610     }
1611
1612     if (FormatStr[1] == 's') {
1613       // fprintf(F, "%s", str) -> fputs(str, F)
1614       if (!CI->getOperand(3)->getType()->isPointerTy() || !CI->use_empty())
1615         return 0;
1616       EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1617       return CI;
1618     }
1619     return 0;
1620   }
1621 };
1622
1623 } // end anonymous namespace.
1624
1625 //===----------------------------------------------------------------------===//
1626 // SimplifyLibCalls Pass Implementation
1627 //===----------------------------------------------------------------------===//
1628
1629 namespace {
1630   /// This pass optimizes well known library functions from libc and libm.
1631   ///
1632   class SimplifyLibCalls : public FunctionPass {
1633     StringMap<LibCallOptimization*> Optimizations;
1634     // String and Memory LibCall Optimizations
1635     StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1636     StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1637     StrToOpt StrTo; StrStrOpt StrStr;
1638     MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1639     // Math Library Optimizations
1640     PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1641     // Integer Optimizations
1642     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1643     ToAsciiOpt ToAscii;
1644     // Formatting and IO Optimizations
1645     SPrintFOpt SPrintF; PrintFOpt PrintF;
1646     FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1647
1648     // Object Size Checking
1649     MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1650     StrCpyChkOpt StrCpyChk;
1651
1652     bool Modified;  // This is only used by doInitialization.
1653   public:
1654     static char ID; // Pass identification
1655     SimplifyLibCalls() : FunctionPass(&ID) {}
1656
1657     void InitOptimizations();
1658     bool runOnFunction(Function &F);
1659
1660     void setDoesNotAccessMemory(Function &F);
1661     void setOnlyReadsMemory(Function &F);
1662     void setDoesNotThrow(Function &F);
1663     void setDoesNotCapture(Function &F, unsigned n);
1664     void setDoesNotAlias(Function &F, unsigned n);
1665     bool doInitialization(Module &M);
1666
1667     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1668     }
1669   };
1670   char SimplifyLibCalls::ID = 0;
1671 } // end anonymous namespace.
1672
1673 static RegisterPass<SimplifyLibCalls>
1674 X("simplify-libcalls", "Simplify well-known library calls");
1675
1676 // Public interface to the Simplify LibCalls pass.
1677 FunctionPass *llvm::createSimplifyLibCallsPass() {
1678   return new SimplifyLibCalls();
1679 }
1680
1681 /// Optimizations - Populate the Optimizations map with all the optimizations
1682 /// we know.
1683 void SimplifyLibCalls::InitOptimizations() {
1684   // String and Memory LibCall Optimizations
1685   Optimizations["strcat"] = &StrCat;
1686   Optimizations["strncat"] = &StrNCat;
1687   Optimizations["strchr"] = &StrChr;
1688   Optimizations["strcmp"] = &StrCmp;
1689   Optimizations["strncmp"] = &StrNCmp;
1690   Optimizations["strcpy"] = &StrCpy;
1691   Optimizations["strncpy"] = &StrNCpy;
1692   Optimizations["strlen"] = &StrLen;
1693   Optimizations["strtol"] = &StrTo;
1694   Optimizations["strtod"] = &StrTo;
1695   Optimizations["strtof"] = &StrTo;
1696   Optimizations["strtoul"] = &StrTo;
1697   Optimizations["strtoll"] = &StrTo;
1698   Optimizations["strtold"] = &StrTo;
1699   Optimizations["strtoull"] = &StrTo;
1700   Optimizations["strstr"] = &StrStr;
1701   Optimizations["memcmp"] = &MemCmp;
1702   Optimizations["memcpy"] = &MemCpy;
1703   Optimizations["memmove"] = &MemMove;
1704   Optimizations["memset"] = &MemSet;
1705
1706   // Math Library Optimizations
1707   Optimizations["powf"] = &Pow;
1708   Optimizations["pow"] = &Pow;
1709   Optimizations["powl"] = &Pow;
1710   Optimizations["llvm.pow.f32"] = &Pow;
1711   Optimizations["llvm.pow.f64"] = &Pow;
1712   Optimizations["llvm.pow.f80"] = &Pow;
1713   Optimizations["llvm.pow.f128"] = &Pow;
1714   Optimizations["llvm.pow.ppcf128"] = &Pow;
1715   Optimizations["exp2l"] = &Exp2;
1716   Optimizations["exp2"] = &Exp2;
1717   Optimizations["exp2f"] = &Exp2;
1718   Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1719   Optimizations["llvm.exp2.f128"] = &Exp2;
1720   Optimizations["llvm.exp2.f80"] = &Exp2;
1721   Optimizations["llvm.exp2.f64"] = &Exp2;
1722   Optimizations["llvm.exp2.f32"] = &Exp2;
1723
1724 #ifdef HAVE_FLOORF
1725   Optimizations["floor"] = &UnaryDoubleFP;
1726 #endif
1727 #ifdef HAVE_CEILF
1728   Optimizations["ceil"] = &UnaryDoubleFP;
1729 #endif
1730 #ifdef HAVE_ROUNDF
1731   Optimizations["round"] = &UnaryDoubleFP;
1732 #endif
1733 #ifdef HAVE_RINTF
1734   Optimizations["rint"] = &UnaryDoubleFP;
1735 #endif
1736 #ifdef HAVE_NEARBYINTF
1737   Optimizations["nearbyint"] = &UnaryDoubleFP;
1738 #endif
1739
1740   // Integer Optimizations
1741   Optimizations["ffs"] = &FFS;
1742   Optimizations["ffsl"] = &FFS;
1743   Optimizations["ffsll"] = &FFS;
1744   Optimizations["abs"] = &Abs;
1745   Optimizations["labs"] = &Abs;
1746   Optimizations["llabs"] = &Abs;
1747   Optimizations["isdigit"] = &IsDigit;
1748   Optimizations["isascii"] = &IsAscii;
1749   Optimizations["toascii"] = &ToAscii;
1750
1751   // Formatting and IO Optimizations
1752   Optimizations["sprintf"] = &SPrintF;
1753   Optimizations["printf"] = &PrintF;
1754   Optimizations["fwrite"] = &FWrite;
1755   Optimizations["fputs"] = &FPuts;
1756   Optimizations["fprintf"] = &FPrintF;
1757
1758   // Object Size Checking
1759   Optimizations["__memcpy_chk"] = &MemCpyChk;
1760   Optimizations["__memset_chk"] = &MemSetChk;
1761   Optimizations["__memmove_chk"] = &MemMoveChk;
1762   Optimizations["__strcpy_chk"] = &StrCpyChk;
1763 }
1764
1765
1766 /// runOnFunction - Top level algorithm.
1767 ///
1768 bool SimplifyLibCalls::runOnFunction(Function &F) {
1769   if (Optimizations.empty())
1770     InitOptimizations();
1771
1772   const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1773
1774   IRBuilder<> Builder(F.getContext());
1775
1776   bool Changed = false;
1777   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1778     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1779       // Ignore non-calls.
1780       CallInst *CI = dyn_cast<CallInst>(I++);
1781       if (!CI) continue;
1782
1783       // Ignore indirect calls and calls to non-external functions.
1784       Function *Callee = CI->getCalledFunction();
1785       if (Callee == 0 || !Callee->isDeclaration() ||
1786           !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1787         continue;
1788
1789       // Ignore unknown calls.
1790       LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1791       if (!LCO) continue;
1792
1793       // Set the builder to the instruction after the call.
1794       Builder.SetInsertPoint(BB, I);
1795
1796       // Try to optimize this call.
1797       Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1798       if (Result == 0) continue;
1799
1800       DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1801             dbgs() << "  into: " << *Result << "\n");
1802
1803       // Something changed!
1804       Changed = true;
1805       ++NumSimplified;
1806
1807       // Inspect the instruction after the call (which was potentially just
1808       // added) next.
1809       I = CI; ++I;
1810
1811       if (CI != Result && !CI->use_empty()) {
1812         CI->replaceAllUsesWith(Result);
1813         if (!Result->hasName())
1814           Result->takeName(CI);
1815       }
1816       CI->eraseFromParent();
1817     }
1818   }
1819   return Changed;
1820 }
1821
1822 // Utility methods for doInitialization.
1823
1824 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1825   if (!F.doesNotAccessMemory()) {
1826     F.setDoesNotAccessMemory();
1827     ++NumAnnotated;
1828     Modified = true;
1829   }
1830 }
1831 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1832   if (!F.onlyReadsMemory()) {
1833     F.setOnlyReadsMemory();
1834     ++NumAnnotated;
1835     Modified = true;
1836   }
1837 }
1838 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1839   if (!F.doesNotThrow()) {
1840     F.setDoesNotThrow();
1841     ++NumAnnotated;
1842     Modified = true;
1843   }
1844 }
1845 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1846   if (!F.doesNotCapture(n)) {
1847     F.setDoesNotCapture(n);
1848     ++NumAnnotated;
1849     Modified = true;
1850   }
1851 }
1852 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1853   if (!F.doesNotAlias(n)) {
1854     F.setDoesNotAlias(n);
1855     ++NumAnnotated;
1856     Modified = true;
1857   }
1858 }
1859
1860 /// doInitialization - Add attributes to well-known functions.
1861 ///
1862 bool SimplifyLibCalls::doInitialization(Module &M) {
1863   Modified = false;
1864   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1865     Function &F = *I;
1866     if (!F.isDeclaration())
1867       continue;
1868
1869     if (!F.hasName())
1870       continue;
1871
1872     const FunctionType *FTy = F.getFunctionType();
1873
1874     StringRef Name = F.getName();
1875     switch (Name[0]) {
1876       case 's':
1877         if (Name == "strlen") {
1878           if (FTy->getNumParams() != 1 ||
1879               !FTy->getParamType(0)->isPointerTy())
1880             continue;
1881           setOnlyReadsMemory(F);
1882           setDoesNotThrow(F);
1883           setDoesNotCapture(F, 1);
1884         } else if (Name == "strcpy" ||
1885                    Name == "stpcpy" ||
1886                    Name == "strcat" ||
1887                    Name == "strtol" ||
1888                    Name == "strtod" ||
1889                    Name == "strtof" ||
1890                    Name == "strtoul" ||
1891                    Name == "strtoll" ||
1892                    Name == "strtold" ||
1893                    Name == "strncat" ||
1894                    Name == "strncpy" ||
1895                    Name == "strtoull") {
1896           if (FTy->getNumParams() < 2 ||
1897               !FTy->getParamType(1)->isPointerTy())
1898             continue;
1899           setDoesNotThrow(F);
1900           setDoesNotCapture(F, 2);
1901         } else if (Name == "strxfrm") {
1902           if (FTy->getNumParams() != 3 ||
1903               !FTy->getParamType(0)->isPointerTy() ||
1904               !FTy->getParamType(1)->isPointerTy())
1905             continue;
1906           setDoesNotThrow(F);
1907           setDoesNotCapture(F, 1);
1908           setDoesNotCapture(F, 2);
1909         } else if (Name == "strcmp" ||
1910                    Name == "strspn" ||
1911                    Name == "strncmp" ||
1912                    Name ==" strcspn" ||
1913                    Name == "strcoll" ||
1914                    Name == "strcasecmp" ||
1915                    Name == "strncasecmp") {
1916           if (FTy->getNumParams() < 2 ||
1917               !FTy->getParamType(0)->isPointerTy() ||
1918               !FTy->getParamType(1)->isPointerTy())
1919             continue;
1920           setOnlyReadsMemory(F);
1921           setDoesNotThrow(F);
1922           setDoesNotCapture(F, 1);
1923           setDoesNotCapture(F, 2);
1924         } else if (Name == "strstr" ||
1925                    Name == "strpbrk") {
1926           if (FTy->getNumParams() != 2 ||
1927               !FTy->getParamType(1)->isPointerTy())
1928             continue;
1929           setOnlyReadsMemory(F);
1930           setDoesNotThrow(F);
1931           setDoesNotCapture(F, 2);
1932         } else if (Name == "strtok" ||
1933                    Name == "strtok_r") {
1934           if (FTy->getNumParams() < 2 ||
1935               !FTy->getParamType(1)->isPointerTy())
1936             continue;
1937           setDoesNotThrow(F);
1938           setDoesNotCapture(F, 2);
1939         } else if (Name == "scanf" ||
1940                    Name == "setbuf" ||
1941                    Name == "setvbuf") {
1942           if (FTy->getNumParams() < 1 ||
1943               !FTy->getParamType(0)->isPointerTy())
1944             continue;
1945           setDoesNotThrow(F);
1946           setDoesNotCapture(F, 1);
1947         } else if (Name == "strdup" ||
1948                    Name == "strndup") {
1949           if (FTy->getNumParams() < 1 ||
1950               !FTy->getReturnType()->isPointerTy() ||
1951               !FTy->getParamType(0)->isPointerTy())
1952             continue;
1953           setDoesNotThrow(F);
1954           setDoesNotAlias(F, 0);
1955           setDoesNotCapture(F, 1);
1956         } else if (Name == "stat" ||
1957                    Name == "sscanf" ||
1958                    Name == "sprintf" ||
1959                    Name == "statvfs") {
1960           if (FTy->getNumParams() < 2 ||
1961               !FTy->getParamType(0)->isPointerTy() ||
1962               !FTy->getParamType(1)->isPointerTy())
1963             continue;
1964           setDoesNotThrow(F);
1965           setDoesNotCapture(F, 1);
1966           setDoesNotCapture(F, 2);
1967         } else if (Name == "snprintf") {
1968           if (FTy->getNumParams() != 3 ||
1969               !FTy->getParamType(0)->isPointerTy() ||
1970               !FTy->getParamType(2)->isPointerTy())
1971             continue;
1972           setDoesNotThrow(F);
1973           setDoesNotCapture(F, 1);
1974           setDoesNotCapture(F, 3);
1975         } else if (Name == "setitimer") {
1976           if (FTy->getNumParams() != 3 ||
1977               !FTy->getParamType(1)->isPointerTy() ||
1978               !FTy->getParamType(2)->isPointerTy())
1979             continue;
1980           setDoesNotThrow(F);
1981           setDoesNotCapture(F, 2);
1982           setDoesNotCapture(F, 3);
1983         } else if (Name == "system") {
1984           if (FTy->getNumParams() != 1 ||
1985               !FTy->getParamType(0)->isPointerTy())
1986             continue;
1987           // May throw; "system" is a valid pthread cancellation point.
1988           setDoesNotCapture(F, 1);
1989         }
1990         break;
1991       case 'm':
1992         if (Name == "malloc") {
1993           if (FTy->getNumParams() != 1 ||
1994               !FTy->getReturnType()->isPointerTy())
1995             continue;
1996           setDoesNotThrow(F);
1997           setDoesNotAlias(F, 0);
1998         } else if (Name == "memcmp") {
1999           if (FTy->getNumParams() != 3 ||
2000               !FTy->getParamType(0)->isPointerTy() ||
2001               !FTy->getParamType(1)->isPointerTy())
2002             continue;
2003           setOnlyReadsMemory(F);
2004           setDoesNotThrow(F);
2005           setDoesNotCapture(F, 1);
2006           setDoesNotCapture(F, 2);
2007         } else if (Name == "memchr" ||
2008                    Name == "memrchr") {
2009           if (FTy->getNumParams() != 3)
2010             continue;
2011           setOnlyReadsMemory(F);
2012           setDoesNotThrow(F);
2013         } else if (Name == "modf" ||
2014                    Name == "modff" ||
2015                    Name == "modfl" ||
2016                    Name == "memcpy" ||
2017                    Name == "memccpy" ||
2018                    Name == "memmove") {
2019           if (FTy->getNumParams() < 2 ||
2020               !FTy->getParamType(1)->isPointerTy())
2021             continue;
2022           setDoesNotThrow(F);
2023           setDoesNotCapture(F, 2);
2024         } else if (Name == "memalign") {
2025           if (!FTy->getReturnType()->isPointerTy())
2026             continue;
2027           setDoesNotAlias(F, 0);
2028         } else if (Name == "mkdir" ||
2029                    Name == "mktime") {
2030           if (FTy->getNumParams() == 0 ||
2031               !FTy->getParamType(0)->isPointerTy())
2032             continue;
2033           setDoesNotThrow(F);
2034           setDoesNotCapture(F, 1);
2035         }
2036         break;
2037       case 'r':
2038         if (Name == "realloc") {
2039           if (FTy->getNumParams() != 2 ||
2040               !FTy->getParamType(0)->isPointerTy() ||
2041               !FTy->getReturnType()->isPointerTy())
2042             continue;
2043           setDoesNotThrow(F);
2044           setDoesNotAlias(F, 0);
2045           setDoesNotCapture(F, 1);
2046         } else if (Name == "read") {
2047           if (FTy->getNumParams() != 3 ||
2048               !FTy->getParamType(1)->isPointerTy())
2049             continue;
2050           // May throw; "read" is a valid pthread cancellation point.
2051           setDoesNotCapture(F, 2);
2052         } else if (Name == "rmdir" ||
2053                    Name == "rewind" ||
2054                    Name == "remove" ||
2055                    Name == "realpath") {
2056           if (FTy->getNumParams() < 1 ||
2057               !FTy->getParamType(0)->isPointerTy())
2058             continue;
2059           setDoesNotThrow(F);
2060           setDoesNotCapture(F, 1);
2061         } else if (Name == "rename" ||
2062                    Name == "readlink") {
2063           if (FTy->getNumParams() < 2 ||
2064               !FTy->getParamType(0)->isPointerTy() ||
2065               !FTy->getParamType(1)->isPointerTy())
2066             continue;
2067           setDoesNotThrow(F);
2068           setDoesNotCapture(F, 1);
2069           setDoesNotCapture(F, 2);
2070         }
2071         break;
2072       case 'w':
2073         if (Name == "write") {
2074           if (FTy->getNumParams() != 3 ||
2075               !FTy->getParamType(1)->isPointerTy())
2076             continue;
2077           // May throw; "write" is a valid pthread cancellation point.
2078           setDoesNotCapture(F, 2);
2079         }
2080         break;
2081       case 'b':
2082         if (Name == "bcopy") {
2083           if (FTy->getNumParams() != 3 ||
2084               !FTy->getParamType(0)->isPointerTy() ||
2085               !FTy->getParamType(1)->isPointerTy())
2086             continue;
2087           setDoesNotThrow(F);
2088           setDoesNotCapture(F, 1);
2089           setDoesNotCapture(F, 2);
2090         } else if (Name == "bcmp") {
2091           if (FTy->getNumParams() != 3 ||
2092               !FTy->getParamType(0)->isPointerTy() ||
2093               !FTy->getParamType(1)->isPointerTy())
2094             continue;
2095           setDoesNotThrow(F);
2096           setOnlyReadsMemory(F);
2097           setDoesNotCapture(F, 1);
2098           setDoesNotCapture(F, 2);
2099         } else if (Name == "bzero") {
2100           if (FTy->getNumParams() != 2 ||
2101               !FTy->getParamType(0)->isPointerTy())
2102             continue;
2103           setDoesNotThrow(F);
2104           setDoesNotCapture(F, 1);
2105         }
2106         break;
2107       case 'c':
2108         if (Name == "calloc") {
2109           if (FTy->getNumParams() != 2 ||
2110               !FTy->getReturnType()->isPointerTy())
2111             continue;
2112           setDoesNotThrow(F);
2113           setDoesNotAlias(F, 0);
2114         } else if (Name == "chmod" ||
2115                    Name == "chown" ||
2116                    Name == "ctermid" ||
2117                    Name == "clearerr" ||
2118                    Name == "closedir") {
2119           if (FTy->getNumParams() == 0 ||
2120               !FTy->getParamType(0)->isPointerTy())
2121             continue;
2122           setDoesNotThrow(F);
2123           setDoesNotCapture(F, 1);
2124         }
2125         break;
2126       case 'a':
2127         if (Name == "atoi" ||
2128             Name == "atol" ||
2129             Name == "atof" ||
2130             Name == "atoll") {
2131           if (FTy->getNumParams() != 1 ||
2132               !FTy->getParamType(0)->isPointerTy())
2133             continue;
2134           setDoesNotThrow(F);
2135           setOnlyReadsMemory(F);
2136           setDoesNotCapture(F, 1);
2137         } else if (Name == "access") {
2138           if (FTy->getNumParams() != 2 ||
2139               !FTy->getParamType(0)->isPointerTy())
2140             continue;
2141           setDoesNotThrow(F);
2142           setDoesNotCapture(F, 1);
2143         }
2144         break;
2145       case 'f':
2146         if (Name == "fopen") {
2147           if (FTy->getNumParams() != 2 ||
2148               !FTy->getReturnType()->isPointerTy() ||
2149               !FTy->getParamType(0)->isPointerTy() ||
2150               !FTy->getParamType(1)->isPointerTy())
2151             continue;
2152           setDoesNotThrow(F);
2153           setDoesNotAlias(F, 0);
2154           setDoesNotCapture(F, 1);
2155           setDoesNotCapture(F, 2);
2156         } else if (Name == "fdopen") {
2157           if (FTy->getNumParams() != 2 ||
2158               !FTy->getReturnType()->isPointerTy() ||
2159               !FTy->getParamType(1)->isPointerTy())
2160             continue;
2161           setDoesNotThrow(F);
2162           setDoesNotAlias(F, 0);
2163           setDoesNotCapture(F, 2);
2164         } else if (Name == "feof" ||
2165                    Name == "free" ||
2166                    Name == "fseek" ||
2167                    Name == "ftell" ||
2168                    Name == "fgetc" ||
2169                    Name == "fseeko" ||
2170                    Name == "ftello" ||
2171                    Name == "fileno" ||
2172                    Name == "fflush" ||
2173                    Name == "fclose" ||
2174                    Name == "fsetpos" ||
2175                    Name == "flockfile" ||
2176                    Name == "funlockfile" ||
2177                    Name == "ftrylockfile") {
2178           if (FTy->getNumParams() == 0 ||
2179               !FTy->getParamType(0)->isPointerTy())
2180             continue;
2181           setDoesNotThrow(F);
2182           setDoesNotCapture(F, 1);
2183         } else if (Name == "ferror") {
2184           if (FTy->getNumParams() != 1 ||
2185               !FTy->getParamType(0)->isPointerTy())
2186             continue;
2187           setDoesNotThrow(F);
2188           setDoesNotCapture(F, 1);
2189           setOnlyReadsMemory(F);
2190         } else if (Name == "fputc" ||
2191                    Name == "fstat" ||
2192                    Name == "frexp" ||
2193                    Name == "frexpf" ||
2194                    Name == "frexpl" ||
2195                    Name == "fstatvfs") {
2196           if (FTy->getNumParams() != 2 ||
2197               !FTy->getParamType(1)->isPointerTy())
2198             continue;
2199           setDoesNotThrow(F);
2200           setDoesNotCapture(F, 2);
2201         } else if (Name == "fgets") {
2202           if (FTy->getNumParams() != 3 ||
2203               !FTy->getParamType(0)->isPointerTy() ||
2204               !FTy->getParamType(2)->isPointerTy())
2205             continue;
2206           setDoesNotThrow(F);
2207           setDoesNotCapture(F, 3);
2208         } else if (Name == "fread" ||
2209                    Name == "fwrite") {
2210           if (FTy->getNumParams() != 4 ||
2211               !FTy->getParamType(0)->isPointerTy() ||
2212               !FTy->getParamType(3)->isPointerTy())
2213             continue;
2214           setDoesNotThrow(F);
2215           setDoesNotCapture(F, 1);
2216           setDoesNotCapture(F, 4);
2217         } else if (Name == "fputs" ||
2218                    Name == "fscanf" ||
2219                    Name == "fprintf" ||
2220                    Name == "fgetpos") {
2221           if (FTy->getNumParams() < 2 ||
2222               !FTy->getParamType(0)->isPointerTy() ||
2223               !FTy->getParamType(1)->isPointerTy())
2224             continue;
2225           setDoesNotThrow(F);
2226           setDoesNotCapture(F, 1);
2227           setDoesNotCapture(F, 2);
2228         }
2229         break;
2230       case 'g':
2231         if (Name == "getc" ||
2232             Name == "getlogin_r" ||
2233             Name == "getc_unlocked") {
2234           if (FTy->getNumParams() == 0 ||
2235               !FTy->getParamType(0)->isPointerTy())
2236             continue;
2237           setDoesNotThrow(F);
2238           setDoesNotCapture(F, 1);
2239         } else if (Name == "getenv") {
2240           if (FTy->getNumParams() != 1 ||
2241               !FTy->getParamType(0)->isPointerTy())
2242             continue;
2243           setDoesNotThrow(F);
2244           setOnlyReadsMemory(F);
2245           setDoesNotCapture(F, 1);
2246         } else if (Name == "gets" ||
2247                    Name == "getchar") {
2248           setDoesNotThrow(F);
2249         } else if (Name == "getitimer") {
2250           if (FTy->getNumParams() != 2 ||
2251               !FTy->getParamType(1)->isPointerTy())
2252             continue;
2253           setDoesNotThrow(F);
2254           setDoesNotCapture(F, 2);
2255         } else if (Name == "getpwnam") {
2256           if (FTy->getNumParams() != 1 ||
2257               !FTy->getParamType(0)->isPointerTy())
2258             continue;
2259           setDoesNotThrow(F);
2260           setDoesNotCapture(F, 1);
2261         }
2262         break;
2263       case 'u':
2264         if (Name == "ungetc") {
2265           if (FTy->getNumParams() != 2 ||
2266               !FTy->getParamType(1)->isPointerTy())
2267             continue;
2268           setDoesNotThrow(F);
2269           setDoesNotCapture(F, 2);
2270         } else if (Name == "uname" ||
2271                    Name == "unlink" ||
2272                    Name == "unsetenv") {
2273           if (FTy->getNumParams() != 1 ||
2274               !FTy->getParamType(0)->isPointerTy())
2275             continue;
2276           setDoesNotThrow(F);
2277           setDoesNotCapture(F, 1);
2278         } else if (Name == "utime" ||
2279                    Name == "utimes") {
2280           if (FTy->getNumParams() != 2 ||
2281               !FTy->getParamType(0)->isPointerTy() ||
2282               !FTy->getParamType(1)->isPointerTy())
2283             continue;
2284           setDoesNotThrow(F);
2285           setDoesNotCapture(F, 1);
2286           setDoesNotCapture(F, 2);
2287         }
2288         break;
2289       case 'p':
2290         if (Name == "putc") {
2291           if (FTy->getNumParams() != 2 ||
2292               !FTy->getParamType(1)->isPointerTy())
2293             continue;
2294           setDoesNotThrow(F);
2295           setDoesNotCapture(F, 2);
2296         } else if (Name == "puts" ||
2297                    Name == "printf" ||
2298                    Name == "perror") {
2299           if (FTy->getNumParams() != 1 ||
2300               !FTy->getParamType(0)->isPointerTy())
2301             continue;
2302           setDoesNotThrow(F);
2303           setDoesNotCapture(F, 1);
2304         } else if (Name == "pread" ||
2305                    Name == "pwrite") {
2306           if (FTy->getNumParams() != 4 ||
2307               !FTy->getParamType(1)->isPointerTy())
2308             continue;
2309           // May throw; these are valid pthread cancellation points.
2310           setDoesNotCapture(F, 2);
2311         } else if (Name == "putchar") {
2312           setDoesNotThrow(F);
2313         } else if (Name == "popen") {
2314           if (FTy->getNumParams() != 2 ||
2315               !FTy->getReturnType()->isPointerTy() ||
2316               !FTy->getParamType(0)->isPointerTy() ||
2317               !FTy->getParamType(1)->isPointerTy())
2318             continue;
2319           setDoesNotThrow(F);
2320           setDoesNotAlias(F, 0);
2321           setDoesNotCapture(F, 1);
2322           setDoesNotCapture(F, 2);
2323         } else if (Name == "pclose") {
2324           if (FTy->getNumParams() != 1 ||
2325               !FTy->getParamType(0)->isPointerTy())
2326             continue;
2327           setDoesNotThrow(F);
2328           setDoesNotCapture(F, 1);
2329         }
2330         break;
2331       case 'v':
2332         if (Name == "vscanf") {
2333           if (FTy->getNumParams() != 2 ||
2334               !FTy->getParamType(1)->isPointerTy())
2335             continue;
2336           setDoesNotThrow(F);
2337           setDoesNotCapture(F, 1);
2338         } else if (Name == "vsscanf" ||
2339                    Name == "vfscanf") {
2340           if (FTy->getNumParams() != 3 ||
2341               !FTy->getParamType(1)->isPointerTy() ||
2342               !FTy->getParamType(2)->isPointerTy())
2343             continue;
2344           setDoesNotThrow(F);
2345           setDoesNotCapture(F, 1);
2346           setDoesNotCapture(F, 2);
2347         } else if (Name == "valloc") {
2348           if (!FTy->getReturnType()->isPointerTy())
2349             continue;
2350           setDoesNotThrow(F);
2351           setDoesNotAlias(F, 0);
2352         } else if (Name == "vprintf") {
2353           if (FTy->getNumParams() != 2 ||
2354               !FTy->getParamType(0)->isPointerTy())
2355             continue;
2356           setDoesNotThrow(F);
2357           setDoesNotCapture(F, 1);
2358         } else if (Name == "vfprintf" ||
2359                    Name == "vsprintf") {
2360           if (FTy->getNumParams() != 3 ||
2361               !FTy->getParamType(0)->isPointerTy() ||
2362               !FTy->getParamType(1)->isPointerTy())
2363             continue;
2364           setDoesNotThrow(F);
2365           setDoesNotCapture(F, 1);
2366           setDoesNotCapture(F, 2);
2367         } else if (Name == "vsnprintf") {
2368           if (FTy->getNumParams() != 4 ||
2369               !FTy->getParamType(0)->isPointerTy() ||
2370               !FTy->getParamType(2)->isPointerTy())
2371             continue;
2372           setDoesNotThrow(F);
2373           setDoesNotCapture(F, 1);
2374           setDoesNotCapture(F, 3);
2375         }
2376         break;
2377       case 'o':
2378         if (Name == "open") {
2379           if (FTy->getNumParams() < 2 ||
2380               !FTy->getParamType(0)->isPointerTy())
2381             continue;
2382           // May throw; "open" is a valid pthread cancellation point.
2383           setDoesNotCapture(F, 1);
2384         } else if (Name == "opendir") {
2385           if (FTy->getNumParams() != 1 ||
2386               !FTy->getReturnType()->isPointerTy() ||
2387               !FTy->getParamType(0)->isPointerTy())
2388             continue;
2389           setDoesNotThrow(F);
2390           setDoesNotAlias(F, 0);
2391           setDoesNotCapture(F, 1);
2392         }
2393         break;
2394       case 't':
2395         if (Name == "tmpfile") {
2396           if (!FTy->getReturnType()->isPointerTy())
2397             continue;
2398           setDoesNotThrow(F);
2399           setDoesNotAlias(F, 0);
2400         } else if (Name == "times") {
2401           if (FTy->getNumParams() != 1 ||
2402               !FTy->getParamType(0)->isPointerTy())
2403             continue;
2404           setDoesNotThrow(F);
2405           setDoesNotCapture(F, 1);
2406         }
2407         break;
2408       case 'h':
2409         if (Name == "htonl" ||
2410             Name == "htons") {
2411           setDoesNotThrow(F);
2412           setDoesNotAccessMemory(F);
2413         }
2414         break;
2415       case 'n':
2416         if (Name == "ntohl" ||
2417             Name == "ntohs") {
2418           setDoesNotThrow(F);
2419           setDoesNotAccessMemory(F);
2420         }
2421         break;
2422       case 'l':
2423         if (Name == "lstat") {
2424           if (FTy->getNumParams() != 2 ||
2425               !FTy->getParamType(0)->isPointerTy() ||
2426               !FTy->getParamType(1)->isPointerTy())
2427             continue;
2428           setDoesNotThrow(F);
2429           setDoesNotCapture(F, 1);
2430           setDoesNotCapture(F, 2);
2431         } else if (Name == "lchown") {
2432           if (FTy->getNumParams() != 3 ||
2433               !FTy->getParamType(0)->isPointerTy())
2434             continue;
2435           setDoesNotThrow(F);
2436           setDoesNotCapture(F, 1);
2437         }
2438         break;
2439       case 'q':
2440         if (Name == "qsort") {
2441           if (FTy->getNumParams() != 4 ||
2442               !FTy->getParamType(3)->isPointerTy())
2443             continue;
2444           // May throw; places call through function pointer.
2445           setDoesNotCapture(F, 4);
2446         }
2447         break;
2448       case '_':
2449         if (Name == "__strdup" ||
2450             Name == "__strndup") {
2451           if (FTy->getNumParams() < 1 ||
2452               !FTy->getReturnType()->isPointerTy() ||
2453               !FTy->getParamType(0)->isPointerTy())
2454             continue;
2455           setDoesNotThrow(F);
2456           setDoesNotAlias(F, 0);
2457           setDoesNotCapture(F, 1);
2458         } else if (Name == "__strtok_r") {
2459           if (FTy->getNumParams() != 3 ||
2460               !FTy->getParamType(1)->isPointerTy())
2461             continue;
2462           setDoesNotThrow(F);
2463           setDoesNotCapture(F, 2);
2464         } else if (Name == "_IO_getc") {
2465           if (FTy->getNumParams() != 1 ||
2466               !FTy->getParamType(0)->isPointerTy())
2467             continue;
2468           setDoesNotThrow(F);
2469           setDoesNotCapture(F, 1);
2470         } else if (Name == "_IO_putc") {
2471           if (FTy->getNumParams() != 2 ||
2472               !FTy->getParamType(1)->isPointerTy())
2473             continue;
2474           setDoesNotThrow(F);
2475           setDoesNotCapture(F, 2);
2476         }
2477         break;
2478       case 1:
2479         if (Name == "\1__isoc99_scanf") {
2480           if (FTy->getNumParams() < 1 ||
2481               !FTy->getParamType(0)->isPointerTy())
2482             continue;
2483           setDoesNotThrow(F);
2484           setDoesNotCapture(F, 1);
2485         } else if (Name == "\1stat64" ||
2486                    Name == "\1lstat64" ||
2487                    Name == "\1statvfs64" ||
2488                    Name == "\1__isoc99_sscanf") {
2489           if (FTy->getNumParams() < 1 ||
2490               !FTy->getParamType(0)->isPointerTy() ||
2491               !FTy->getParamType(1)->isPointerTy())
2492             continue;
2493           setDoesNotThrow(F);
2494           setDoesNotCapture(F, 1);
2495           setDoesNotCapture(F, 2);
2496         } else if (Name == "\1fopen64") {
2497           if (FTy->getNumParams() != 2 ||
2498               !FTy->getReturnType()->isPointerTy() ||
2499               !FTy->getParamType(0)->isPointerTy() ||
2500               !FTy->getParamType(1)->isPointerTy())
2501             continue;
2502           setDoesNotThrow(F);
2503           setDoesNotAlias(F, 0);
2504           setDoesNotCapture(F, 1);
2505           setDoesNotCapture(F, 2);
2506         } else if (Name == "\1fseeko64" ||
2507                    Name == "\1ftello64") {
2508           if (FTy->getNumParams() == 0 ||
2509               !FTy->getParamType(0)->isPointerTy())
2510             continue;
2511           setDoesNotThrow(F);
2512           setDoesNotCapture(F, 1);
2513         } else if (Name == "\1tmpfile64") {
2514           if (!FTy->getReturnType()->isPointerTy())
2515             continue;
2516           setDoesNotThrow(F);
2517           setDoesNotAlias(F, 0);
2518         } else if (Name == "\1fstat64" ||
2519                    Name == "\1fstatvfs64") {
2520           if (FTy->getNumParams() != 2 ||
2521               !FTy->getParamType(1)->isPointerTy())
2522             continue;
2523           setDoesNotThrow(F);
2524           setDoesNotCapture(F, 2);
2525         } else if (Name == "\1open64") {
2526           if (FTy->getNumParams() < 2 ||
2527               !FTy->getParamType(0)->isPointerTy())
2528             continue;
2529           // May throw; "open" is a valid pthread cancellation point.
2530           setDoesNotCapture(F, 1);
2531         }
2532         break;
2533     }
2534   }
2535   return Modified;
2536 }
2537
2538 // TODO:
2539 //   Additional cases that we need to add to this file:
2540 //
2541 // cbrt:
2542 //   * cbrt(expN(X))  -> expN(x/3)
2543 //   * cbrt(sqrt(x))  -> pow(x,1/6)
2544 //   * cbrt(sqrt(x))  -> pow(x,1/9)
2545 //
2546 // cos, cosf, cosl:
2547 //   * cos(-x)  -> cos(x)
2548 //
2549 // exp, expf, expl:
2550 //   * exp(log(x))  -> x
2551 //
2552 // log, logf, logl:
2553 //   * log(exp(x))   -> x
2554 //   * log(x**y)     -> y*log(x)
2555 //   * log(exp(y))   -> y*log(e)
2556 //   * log(exp2(y))  -> y*log(2)
2557 //   * log(exp10(y)) -> y*log(10)
2558 //   * log(sqrt(x))  -> 0.5*log(x)
2559 //   * log(pow(x,y)) -> y*log(x)
2560 //
2561 // lround, lroundf, lroundl:
2562 //   * lround(cnst) -> cnst'
2563 //
2564 // pow, powf, powl:
2565 //   * pow(exp(x),y)  -> exp(x*y)
2566 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
2567 //   * pow(pow(x,y),z)-> pow(x,y*z)
2568 //
2569 // puts:
2570 //   * puts("") -> putchar("\n")
2571 //
2572 // round, roundf, roundl:
2573 //   * round(cnst) -> cnst'
2574 //
2575 // signbit:
2576 //   * signbit(cnst) -> cnst'
2577 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2578 //
2579 // sqrt, sqrtf, sqrtl:
2580 //   * sqrt(expN(x))  -> expN(x*0.5)
2581 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2582 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2583 //
2584 // stpcpy:
2585 //   * stpcpy(str, "literal") ->
2586 //           llvm.memcpy(str,"literal",strlen("literal")+1,1)
2587 // strrchr:
2588 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
2589 //      (if c is a constant integer and s is a constant string)
2590 //   * strrchr(s1,0) -> strchr(s1,0)
2591 //
2592 // strpbrk:
2593 //   * strpbrk(s,a) -> offset_in_for(s,a)
2594 //      (if s and a are both constant strings)
2595 //   * strpbrk(s,"") -> 0
2596 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2597 //
2598 // strspn, strcspn:
2599 //   * strspn(s,a)   -> const_int (if both args are constant)
2600 //   * strspn("",a)  -> 0
2601 //   * strspn(s,"")  -> 0
2602 //   * strcspn(s,a)  -> const_int (if both args are constant)
2603 //   * strcspn("",a) -> 0
2604 //   * strcspn(s,"") -> strlen(a)
2605 //
2606 // tan, tanf, tanl:
2607 //   * tan(atan(x)) -> x
2608 //
2609 // trunc, truncf, truncl:
2610 //   * trunc(cnst) -> cnst'
2611 //
2612 //