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