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