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