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