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