instcombine: Migrate memmove optimizations
[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/IRBuilder.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/LLVMContext.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/STLExtras.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/DataLayout.h"
35 #include "llvm/Target/TargetLibraryInfo.h"
36 #include "llvm/Config/config.h"            // FIXME: Shouldn't depend on host!
37 using namespace llvm;
38
39 STATISTIC(NumSimplified, "Number of library calls simplified");
40 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
41
42 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
43                                    cl::init(false),
44                                    cl::desc("Enable unsafe double to float "
45                                             "shrinking for math lib calls"));
46 //===----------------------------------------------------------------------===//
47 // Optimizer Base Class
48 //===----------------------------------------------------------------------===//
49
50 /// This class is the abstract base class for the set of optimizations that
51 /// corresponds to one library call.
52 namespace {
53 class LibCallOptimization {
54 protected:
55   Function *Caller;
56   const DataLayout *TD;
57   const TargetLibraryInfo *TLI;
58   LLVMContext* Context;
59 public:
60   LibCallOptimization() { }
61   virtual ~LibCallOptimization() {}
62
63   /// CallOptimizer - This pure virtual method is implemented by base classes to
64   /// do various optimizations.  If this returns null then no transformation was
65   /// performed.  If it returns CI, then it transformed the call and CI is to be
66   /// deleted.  If it returns something else, replace CI with the new value and
67   /// delete CI.
68   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
69     =0;
70
71   Value *OptimizeCall(CallInst *CI, const DataLayout *TD,
72                       const TargetLibraryInfo *TLI, IRBuilder<> &B) {
73     Caller = CI->getParent()->getParent();
74     this->TD = TD;
75     this->TLI = TLI;
76     if (CI->getCalledFunction())
77       Context = &CI->getCalledFunction()->getContext();
78
79     // We never change the calling convention.
80     if (CI->getCallingConv() != llvm::CallingConv::C)
81       return NULL;
82
83     return CallOptimizer(CI->getCalledFunction(), CI, B);
84   }
85 };
86 } // End anonymous namespace.
87
88
89 //===----------------------------------------------------------------------===//
90 // Helper Functions
91 //===----------------------------------------------------------------------===//
92
93 static bool CallHasFloatingPointArgument(const CallInst *CI) {
94   for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
95        it != e; ++it) {
96     if ((*it)->getType()->isFloatingPointTy())
97       return true;
98   }
99   return false;
100 }
101
102 //===----------------------------------------------------------------------===//
103 // Memory LibCall Optimizations
104 //===----------------------------------------------------------------------===//
105
106 namespace {
107 //===---------------------------------------===//
108 // 'memset' Optimizations
109
110 struct MemSetOpt : public LibCallOptimization {
111   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
112     // These optimizations require DataLayout.
113     if (!TD) return 0;
114
115     FunctionType *FT = Callee->getFunctionType();
116     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
117         !FT->getParamType(0)->isPointerTy() ||
118         !FT->getParamType(1)->isIntegerTy() ||
119         FT->getParamType(2) != TD->getIntPtrType(*Context))
120       return 0;
121
122     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
123     Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
124     B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
125     return CI->getArgOperand(0);
126   }
127 };
128
129 //===----------------------------------------------------------------------===//
130 // Math Library Optimizations
131 //===----------------------------------------------------------------------===//
132
133 //===---------------------------------------===//
134 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
135
136 struct UnaryDoubleFPOpt : public LibCallOptimization {
137   bool CheckRetType;
138   UnaryDoubleFPOpt(bool CheckReturnType): CheckRetType(CheckReturnType) {}
139   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
140     FunctionType *FT = Callee->getFunctionType();
141     if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
142         !FT->getParamType(0)->isDoubleTy())
143       return 0;
144
145     if (CheckRetType) {
146       // Check if all the uses for function like 'sin' are converted to float.
147       for (Value::use_iterator UseI = CI->use_begin(); UseI != CI->use_end();
148           ++UseI) {
149         FPTruncInst *Cast = dyn_cast<FPTruncInst>(*UseI);
150         if (Cast == 0 || !Cast->getType()->isFloatTy())
151           return 0;
152       }
153     }
154
155     // If this is something like 'floor((double)floatval)', convert to floorf.
156     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getArgOperand(0));
157     if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
158       return 0;
159
160     // floor((double)floatval) -> (double)floorf(floatval)
161     Value *V = Cast->getOperand(0);
162     V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
163     return B.CreateFPExt(V, B.getDoubleTy());
164   }
165 };
166
167 //===---------------------------------------===//
168 // 'cos*' Optimizations
169 struct CosOpt : public LibCallOptimization {
170   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
171     Value *Ret = NULL;
172     if (UnsafeFPShrink && Callee->getName() == "cos" &&
173         TLI->has(LibFunc::cosf)) {
174       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
175       Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
176     }
177
178     FunctionType *FT = Callee->getFunctionType();
179     // Just make sure this has 1 argument of FP type, which matches the
180     // result type.
181     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
182         !FT->getParamType(0)->isFloatingPointTy())
183       return Ret;
184
185     // cos(-x) -> cos(x)
186     Value *Op1 = CI->getArgOperand(0);
187     if (BinaryOperator::isFNeg(Op1)) {
188       BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
189       return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
190     }
191     return Ret;
192   }
193 };
194
195 //===---------------------------------------===//
196 // 'pow*' Optimizations
197
198 struct PowOpt : public LibCallOptimization {
199   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
200     Value *Ret = NULL;
201     if (UnsafeFPShrink && Callee->getName() == "pow" &&
202         TLI->has(LibFunc::powf)) {
203       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
204       Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
205     }
206
207     FunctionType *FT = Callee->getFunctionType();
208     // Just make sure this has 2 arguments of the same FP type, which match the
209     // result type.
210     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
211         FT->getParamType(0) != FT->getParamType(1) ||
212         !FT->getParamType(0)->isFloatingPointTy())
213       return Ret;
214
215     Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
216     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
217       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
218         return Op1C;
219       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
220         return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
221     }
222
223     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
224     if (Op2C == 0) return Ret;
225
226     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
227       return ConstantFP::get(CI->getType(), 1.0);
228
229     if (Op2C->isExactlyValue(0.5)) {
230       // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
231       // This is faster than calling pow, and still handles negative zero
232       // and negative infinity correctly.
233       // TODO: In fast-math mode, this could be just sqrt(x).
234       // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
235       Value *Inf = ConstantFP::getInfinity(CI->getType());
236       Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
237       Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
238                                          Callee->getAttributes());
239       Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
240                                          Callee->getAttributes());
241       Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
242       Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
243       return Sel;
244     }
245
246     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
247       return Op1;
248     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
249       return B.CreateFMul(Op1, Op1, "pow2");
250     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
251       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
252                           Op1, "powrecip");
253     return 0;
254   }
255 };
256
257 //===---------------------------------------===//
258 // 'exp2' Optimizations
259
260 struct Exp2Opt : public LibCallOptimization {
261   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
262     Value *Ret = NULL;
263     if (UnsafeFPShrink && Callee->getName() == "exp2" &&
264         TLI->has(LibFunc::exp2)) {
265       UnaryDoubleFPOpt UnsafeUnaryDoubleFP(true);
266       Ret = UnsafeUnaryDoubleFP.CallOptimizer(Callee, CI, B);
267     }
268
269     FunctionType *FT = Callee->getFunctionType();
270     // Just make sure this has 1 argument of FP type, which matches the
271     // result type.
272     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
273         !FT->getParamType(0)->isFloatingPointTy())
274       return Ret;
275
276     Value *Op = CI->getArgOperand(0);
277     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
278     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
279     Value *LdExpArg = 0;
280     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
281       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
282         LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
283     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
284       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
285         LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
286     }
287
288     if (LdExpArg) {
289       const char *Name;
290       if (Op->getType()->isFloatTy())
291         Name = "ldexpf";
292       else if (Op->getType()->isDoubleTy())
293         Name = "ldexp";
294       else
295         Name = "ldexpl";
296
297       Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
298       if (!Op->getType()->isFloatTy())
299         One = ConstantExpr::getFPExtend(One, Op->getType());
300
301       Module *M = Caller->getParent();
302       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
303                                              Op->getType(),
304                                              B.getInt32Ty(), NULL);
305       CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
306       if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
307         CI->setCallingConv(F->getCallingConv());
308
309       return CI;
310     }
311     return Ret;
312   }
313 };
314
315 //===----------------------------------------------------------------------===//
316 // Integer Optimizations
317 //===----------------------------------------------------------------------===//
318
319 //===---------------------------------------===//
320 // 'ffs*' Optimizations
321
322 struct FFSOpt : public LibCallOptimization {
323   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
324     FunctionType *FT = Callee->getFunctionType();
325     // Just make sure this has 2 arguments of the same FP type, which match the
326     // result type.
327     if (FT->getNumParams() != 1 ||
328         !FT->getReturnType()->isIntegerTy(32) ||
329         !FT->getParamType(0)->isIntegerTy())
330       return 0;
331
332     Value *Op = CI->getArgOperand(0);
333
334     // Constant fold.
335     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
336       if (CI->isZero()) // ffs(0) -> 0.
337         return B.getInt32(0);
338       // ffs(c) -> cttz(c)+1
339       return B.getInt32(CI->getValue().countTrailingZeros() + 1);
340     }
341
342     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
343     Type *ArgType = Op->getType();
344     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
345                                          Intrinsic::cttz, ArgType);
346     Value *V = B.CreateCall2(F, Op, B.getFalse(), "cttz");
347     V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
348     V = B.CreateIntCast(V, B.getInt32Ty(), false);
349
350     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
351     return B.CreateSelect(Cond, V, B.getInt32(0));
352   }
353 };
354
355 //===---------------------------------------===//
356 // 'isdigit' Optimizations
357
358 struct IsDigitOpt : public LibCallOptimization {
359   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
360     FunctionType *FT = Callee->getFunctionType();
361     // We require integer(i32)
362     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
363         !FT->getParamType(0)->isIntegerTy(32))
364       return 0;
365
366     // isdigit(c) -> (c-'0') <u 10
367     Value *Op = CI->getArgOperand(0);
368     Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
369     Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
370     return B.CreateZExt(Op, CI->getType());
371   }
372 };
373
374 //===---------------------------------------===//
375 // 'isascii' Optimizations
376
377 struct IsAsciiOpt : public LibCallOptimization {
378   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
379     FunctionType *FT = Callee->getFunctionType();
380     // We require integer(i32)
381     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
382         !FT->getParamType(0)->isIntegerTy(32))
383       return 0;
384
385     // isascii(c) -> c <u 128
386     Value *Op = CI->getArgOperand(0);
387     Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
388     return B.CreateZExt(Op, CI->getType());
389   }
390 };
391
392 //===---------------------------------------===//
393 // 'abs', 'labs', 'llabs' Optimizations
394
395 struct AbsOpt : public LibCallOptimization {
396   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
397     FunctionType *FT = Callee->getFunctionType();
398     // We require integer(integer) where the types agree.
399     if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
400         FT->getParamType(0) != FT->getReturnType())
401       return 0;
402
403     // abs(x) -> x >s -1 ? x : -x
404     Value *Op = CI->getArgOperand(0);
405     Value *Pos = B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()),
406                                  "ispos");
407     Value *Neg = B.CreateNeg(Op, "neg");
408     return B.CreateSelect(Pos, Op, Neg);
409   }
410 };
411
412
413 //===---------------------------------------===//
414 // 'toascii' Optimizations
415
416 struct ToAsciiOpt : public LibCallOptimization {
417   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
418     FunctionType *FT = Callee->getFunctionType();
419     // We require i32(i32)
420     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
421         !FT->getParamType(0)->isIntegerTy(32))
422       return 0;
423
424     // isascii(c) -> c & 0x7f
425     return B.CreateAnd(CI->getArgOperand(0),
426                        ConstantInt::get(CI->getType(),0x7F));
427   }
428 };
429
430 //===----------------------------------------------------------------------===//
431 // Formatting and IO Optimizations
432 //===----------------------------------------------------------------------===//
433
434 //===---------------------------------------===//
435 // 'printf' Optimizations
436
437 struct PrintFOpt : public LibCallOptimization {
438   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
439                                    IRBuilder<> &B) {
440     // Check for a fixed format string.
441     StringRef FormatStr;
442     if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
443       return 0;
444
445     // Empty format string -> noop.
446     if (FormatStr.empty())  // Tolerate printf's declared void.
447       return CI->use_empty() ? (Value*)CI :
448                                ConstantInt::get(CI->getType(), 0);
449
450     // Do not do any of the following transformations if the printf return value
451     // is used, in general the printf return value is not compatible with either
452     // putchar() or puts().
453     if (!CI->use_empty())
454       return 0;
455
456     // printf("x") -> putchar('x'), even for '%'.
457     if (FormatStr.size() == 1) {
458       Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TD, TLI);
459       if (CI->use_empty() || !Res) return Res;
460       return B.CreateIntCast(Res, CI->getType(), true);
461     }
462
463     // printf("foo\n") --> puts("foo")
464     if (FormatStr[FormatStr.size()-1] == '\n' &&
465         FormatStr.find('%') == std::string::npos) {  // no format characters.
466       // Create a string literal with no \n on it.  We expect the constant merge
467       // pass to be run after this pass, to merge duplicate strings.
468       FormatStr = FormatStr.drop_back();
469       Value *GV = B.CreateGlobalString(FormatStr, "str");
470       Value *NewCI = EmitPutS(GV, B, TD, TLI);
471       return (CI->use_empty() || !NewCI) ?
472               NewCI :
473               ConstantInt::get(CI->getType(), FormatStr.size()+1);
474     }
475
476     // Optimize specific format strings.
477     // printf("%c", chr) --> putchar(chr)
478     if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
479         CI->getArgOperand(1)->getType()->isIntegerTy()) {
480       Value *Res = EmitPutChar(CI->getArgOperand(1), B, TD, TLI);
481
482       if (CI->use_empty() || !Res) return Res;
483       return B.CreateIntCast(Res, CI->getType(), true);
484     }
485
486     // printf("%s\n", str) --> puts(str)
487     if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
488         CI->getArgOperand(1)->getType()->isPointerTy()) {
489       return EmitPutS(CI->getArgOperand(1), B, TD, TLI);
490     }
491     return 0;
492   }
493
494   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
495     // Require one fixed pointer argument and an integer/void result.
496     FunctionType *FT = Callee->getFunctionType();
497     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
498         !(FT->getReturnType()->isIntegerTy() ||
499           FT->getReturnType()->isVoidTy()))
500       return 0;
501
502     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
503       return V;
504     }
505
506     // printf(format, ...) -> iprintf(format, ...) if no floating point
507     // arguments.
508     if (TLI->has(LibFunc::iprintf) && !CallHasFloatingPointArgument(CI)) {
509       Module *M = B.GetInsertBlock()->getParent()->getParent();
510       Constant *IPrintFFn =
511         M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
512       CallInst *New = cast<CallInst>(CI->clone());
513       New->setCalledFunction(IPrintFFn);
514       B.Insert(New);
515       return New;
516     }
517     return 0;
518   }
519 };
520
521 //===---------------------------------------===//
522 // 'sprintf' Optimizations
523
524 struct SPrintFOpt : public LibCallOptimization {
525   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
526                                    IRBuilder<> &B) {
527     // Check for a fixed format string.
528     StringRef FormatStr;
529     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
530       return 0;
531
532     // If we just have a format string (nothing else crazy) transform it.
533     if (CI->getNumArgOperands() == 2) {
534       // Make sure there's no % in the constant array.  We could try to handle
535       // %% -> % in the future if we cared.
536       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
537         if (FormatStr[i] == '%')
538           return 0; // we found a format specifier, bail out.
539
540       // These optimizations require DataLayout.
541       if (!TD) return 0;
542
543       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
544       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
545                      ConstantInt::get(TD->getIntPtrType(*Context), // Copy the
546                                       FormatStr.size() + 1), 1);   // nul byte.
547       return ConstantInt::get(CI->getType(), FormatStr.size());
548     }
549
550     // The remaining optimizations require the format string to be "%s" or "%c"
551     // and have an extra operand.
552     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
553         CI->getNumArgOperands() < 3)
554       return 0;
555
556     // Decode the second character of the format string.
557     if (FormatStr[1] == 'c') {
558       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
559       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
560       Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
561       Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
562       B.CreateStore(V, Ptr);
563       Ptr = B.CreateGEP(Ptr, B.getInt32(1), "nul");
564       B.CreateStore(B.getInt8(0), Ptr);
565
566       return ConstantInt::get(CI->getType(), 1);
567     }
568
569     if (FormatStr[1] == 's') {
570       // These optimizations require DataLayout.
571       if (!TD) return 0;
572
573       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
574       if (!CI->getArgOperand(2)->getType()->isPointerTy()) return 0;
575
576       Value *Len = EmitStrLen(CI->getArgOperand(2), B, TD, TLI);
577       if (!Len)
578         return 0;
579       Value *IncLen = B.CreateAdd(Len,
580                                   ConstantInt::get(Len->getType(), 1),
581                                   "leninc");
582       B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
583
584       // The sprintf result is the unincremented number of bytes in the string.
585       return B.CreateIntCast(Len, CI->getType(), false);
586     }
587     return 0;
588   }
589
590   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
591     // Require two fixed pointer arguments and an integer result.
592     FunctionType *FT = Callee->getFunctionType();
593     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
594         !FT->getParamType(1)->isPointerTy() ||
595         !FT->getReturnType()->isIntegerTy())
596       return 0;
597
598     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
599       return V;
600     }
601
602     // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
603     // point arguments.
604     if (TLI->has(LibFunc::siprintf) && !CallHasFloatingPointArgument(CI)) {
605       Module *M = B.GetInsertBlock()->getParent()->getParent();
606       Constant *SIPrintFFn =
607         M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
608       CallInst *New = cast<CallInst>(CI->clone());
609       New->setCalledFunction(SIPrintFFn);
610       B.Insert(New);
611       return New;
612     }
613     return 0;
614   }
615 };
616
617 //===---------------------------------------===//
618 // 'fwrite' Optimizations
619
620 struct FWriteOpt : public LibCallOptimization {
621   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
622     // Require a pointer, an integer, an integer, a pointer, returning integer.
623     FunctionType *FT = Callee->getFunctionType();
624     if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
625         !FT->getParamType(1)->isIntegerTy() ||
626         !FT->getParamType(2)->isIntegerTy() ||
627         !FT->getParamType(3)->isPointerTy() ||
628         !FT->getReturnType()->isIntegerTy())
629       return 0;
630
631     // Get the element size and count.
632     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
633     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
634     if (!SizeC || !CountC) return 0;
635     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
636
637     // If this is writing zero records, remove the call (it's a noop).
638     if (Bytes == 0)
639       return ConstantInt::get(CI->getType(), 0);
640
641     // If this is writing one byte, turn it into fputc.
642     // This optimisation is only valid, if the return value is unused.
643     if (Bytes == 1 && CI->use_empty()) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
644       Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
645       Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TD, TLI);
646       return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
647     }
648
649     return 0;
650   }
651 };
652
653 //===---------------------------------------===//
654 // 'fputs' Optimizations
655
656 struct FPutsOpt : public LibCallOptimization {
657   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
658     // These optimizations require DataLayout.
659     if (!TD) return 0;
660
661     // Require two pointers.  Also, we can't optimize if return value is used.
662     FunctionType *FT = Callee->getFunctionType();
663     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
664         !FT->getParamType(1)->isPointerTy() ||
665         !CI->use_empty())
666       return 0;
667
668     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
669     uint64_t Len = GetStringLength(CI->getArgOperand(0));
670     if (!Len) return 0;
671     // Known to have no uses (see above).
672     return EmitFWrite(CI->getArgOperand(0),
673                       ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
674                       CI->getArgOperand(1), B, TD, TLI);
675   }
676 };
677
678 //===---------------------------------------===//
679 // 'fprintf' Optimizations
680
681 struct FPrintFOpt : public LibCallOptimization {
682   Value *OptimizeFixedFormatString(Function *Callee, CallInst *CI,
683                                    IRBuilder<> &B) {
684     // All the optimizations depend on the format string.
685     StringRef FormatStr;
686     if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
687       return 0;
688
689     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
690     if (CI->getNumArgOperands() == 2) {
691       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
692         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
693           return 0; // We found a format specifier.
694
695       // These optimizations require DataLayout.
696       if (!TD) return 0;
697
698       Value *NewCI = EmitFWrite(CI->getArgOperand(1),
699                                 ConstantInt::get(TD->getIntPtrType(*Context),
700                                                  FormatStr.size()),
701                                 CI->getArgOperand(0), B, TD, TLI);
702       return NewCI ? ConstantInt::get(CI->getType(), FormatStr.size()) : 0;
703     }
704
705     // The remaining optimizations require the format string to be "%s" or "%c"
706     // and have an extra operand.
707     if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
708         CI->getNumArgOperands() < 3)
709       return 0;
710
711     // Decode the second character of the format string.
712     if (FormatStr[1] == 'c') {
713       // fprintf(F, "%c", chr) --> fputc(chr, F)
714       if (!CI->getArgOperand(2)->getType()->isIntegerTy()) return 0;
715       Value *NewCI = EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B,
716                                TD, TLI);
717       return NewCI ? ConstantInt::get(CI->getType(), 1) : 0;
718     }
719
720     if (FormatStr[1] == 's') {
721       // fprintf(F, "%s", str) --> fputs(str, F)
722       if (!CI->getArgOperand(2)->getType()->isPointerTy() || !CI->use_empty())
723         return 0;
724       return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TD, TLI);
725     }
726     return 0;
727   }
728
729   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
730     // Require two fixed paramters as pointers and integer result.
731     FunctionType *FT = Callee->getFunctionType();
732     if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
733         !FT->getParamType(1)->isPointerTy() ||
734         !FT->getReturnType()->isIntegerTy())
735       return 0;
736
737     if (Value *V = OptimizeFixedFormatString(Callee, CI, B)) {
738       return V;
739     }
740
741     // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
742     // floating point arguments.
743     if (TLI->has(LibFunc::fiprintf) && !CallHasFloatingPointArgument(CI)) {
744       Module *M = B.GetInsertBlock()->getParent()->getParent();
745       Constant *FIPrintFFn =
746         M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
747       CallInst *New = cast<CallInst>(CI->clone());
748       New->setCalledFunction(FIPrintFFn);
749       B.Insert(New);
750       return New;
751     }
752     return 0;
753   }
754 };
755
756 //===---------------------------------------===//
757 // 'puts' Optimizations
758
759 struct PutsOpt : public LibCallOptimization {
760   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
761     // Require one fixed pointer argument and an integer/void result.
762     FunctionType *FT = Callee->getFunctionType();
763     if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
764         !(FT->getReturnType()->isIntegerTy() ||
765           FT->getReturnType()->isVoidTy()))
766       return 0;
767
768     // Check for a constant string.
769     StringRef Str;
770     if (!getConstantStringInfo(CI->getArgOperand(0), Str))
771       return 0;
772
773     if (Str.empty() && CI->use_empty()) {
774       // puts("") -> putchar('\n')
775       Value *Res = EmitPutChar(B.getInt32('\n'), B, TD, TLI);
776       if (CI->use_empty() || !Res) return Res;
777       return B.CreateIntCast(Res, CI->getType(), true);
778     }
779
780     return 0;
781   }
782 };
783
784 } // end anonymous namespace.
785
786 //===----------------------------------------------------------------------===//
787 // SimplifyLibCalls Pass Implementation
788 //===----------------------------------------------------------------------===//
789
790 namespace {
791   /// This pass optimizes well known library functions from libc and libm.
792   ///
793   class SimplifyLibCalls : public FunctionPass {
794     TargetLibraryInfo *TLI;
795
796     StringMap<LibCallOptimization*> Optimizations;
797     // Memory LibCall Optimizations
798     MemSetOpt MemSet;
799     // Math Library Optimizations
800     CosOpt Cos; PowOpt Pow; Exp2Opt Exp2;
801     UnaryDoubleFPOpt UnaryDoubleFP, UnsafeUnaryDoubleFP;
802     // Integer Optimizations
803     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
804     ToAsciiOpt ToAscii;
805     // Formatting and IO Optimizations
806     SPrintFOpt SPrintF; PrintFOpt PrintF;
807     FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
808     PutsOpt Puts;
809
810     bool Modified;  // This is only used by doInitialization.
811   public:
812     static char ID; // Pass identification
813     SimplifyLibCalls() : FunctionPass(ID), UnaryDoubleFP(false),
814                          UnsafeUnaryDoubleFP(true) {
815       initializeSimplifyLibCallsPass(*PassRegistry::getPassRegistry());
816     }
817     void AddOpt(LibFunc::Func F, LibCallOptimization* Opt);
818     void AddOpt(LibFunc::Func F1, LibFunc::Func F2, LibCallOptimization* Opt);
819
820     void InitOptimizations();
821     bool runOnFunction(Function &F);
822
823     void setDoesNotAccessMemory(Function &F);
824     void setOnlyReadsMemory(Function &F);
825     void setDoesNotThrow(Function &F);
826     void setDoesNotCapture(Function &F, unsigned n);
827     void setDoesNotAlias(Function &F, unsigned n);
828     bool doInitialization(Module &M);
829
830     void inferPrototypeAttributes(Function &F);
831     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
832       AU.addRequired<TargetLibraryInfo>();
833     }
834   };
835 } // end anonymous namespace.
836
837 char SimplifyLibCalls::ID = 0;
838
839 INITIALIZE_PASS_BEGIN(SimplifyLibCalls, "simplify-libcalls",
840                       "Simplify well-known library calls", false, false)
841 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
842 INITIALIZE_PASS_END(SimplifyLibCalls, "simplify-libcalls",
843                     "Simplify well-known library calls", false, false)
844
845 // Public interface to the Simplify LibCalls pass.
846 FunctionPass *llvm::createSimplifyLibCallsPass() {
847   return new SimplifyLibCalls();
848 }
849
850 void SimplifyLibCalls::AddOpt(LibFunc::Func F, LibCallOptimization* Opt) {
851   if (TLI->has(F))
852     Optimizations[TLI->getName(F)] = Opt;
853 }
854
855 void SimplifyLibCalls::AddOpt(LibFunc::Func F1, LibFunc::Func F2,
856                               LibCallOptimization* Opt) {
857   if (TLI->has(F1) && TLI->has(F2))
858     Optimizations[TLI->getName(F1)] = Opt;
859 }
860
861 /// Optimizations - Populate the Optimizations map with all the optimizations
862 /// we know.
863 void SimplifyLibCalls::InitOptimizations() {
864   // Memory LibCall Optimizations
865   AddOpt(LibFunc::memset, &MemSet);
866
867   // Math Library Optimizations
868   Optimizations["cosf"] = &Cos;
869   Optimizations["cos"] = &Cos;
870   Optimizations["cosl"] = &Cos;
871   Optimizations["powf"] = &Pow;
872   Optimizations["pow"] = &Pow;
873   Optimizations["powl"] = &Pow;
874   Optimizations["llvm.pow.f32"] = &Pow;
875   Optimizations["llvm.pow.f64"] = &Pow;
876   Optimizations["llvm.pow.f80"] = &Pow;
877   Optimizations["llvm.pow.f128"] = &Pow;
878   Optimizations["llvm.pow.ppcf128"] = &Pow;
879   Optimizations["exp2l"] = &Exp2;
880   Optimizations["exp2"] = &Exp2;
881   Optimizations["exp2f"] = &Exp2;
882   Optimizations["llvm.exp2.ppcf128"] = &Exp2;
883   Optimizations["llvm.exp2.f128"] = &Exp2;
884   Optimizations["llvm.exp2.f80"] = &Exp2;
885   Optimizations["llvm.exp2.f64"] = &Exp2;
886   Optimizations["llvm.exp2.f32"] = &Exp2;
887
888   AddOpt(LibFunc::ceil, LibFunc::ceilf, &UnaryDoubleFP);
889   AddOpt(LibFunc::fabs, LibFunc::fabsf, &UnaryDoubleFP);
890   AddOpt(LibFunc::floor, LibFunc::floorf, &UnaryDoubleFP);
891   AddOpt(LibFunc::rint, LibFunc::rintf, &UnaryDoubleFP);
892   AddOpt(LibFunc::round, LibFunc::roundf, &UnaryDoubleFP);
893   AddOpt(LibFunc::nearbyint, LibFunc::nearbyintf, &UnaryDoubleFP);
894   AddOpt(LibFunc::trunc, LibFunc::truncf, &UnaryDoubleFP);
895
896   if(UnsafeFPShrink) {
897     AddOpt(LibFunc::acos, LibFunc::acosf, &UnsafeUnaryDoubleFP);
898     AddOpt(LibFunc::acosh, LibFunc::acoshf, &UnsafeUnaryDoubleFP);
899     AddOpt(LibFunc::asin, LibFunc::asinf, &UnsafeUnaryDoubleFP);
900     AddOpt(LibFunc::asinh, LibFunc::asinhf, &UnsafeUnaryDoubleFP);
901     AddOpt(LibFunc::atan, LibFunc::atanf, &UnsafeUnaryDoubleFP);
902     AddOpt(LibFunc::atanh, LibFunc::atanhf, &UnsafeUnaryDoubleFP);
903     AddOpt(LibFunc::cbrt, LibFunc::cbrtf, &UnsafeUnaryDoubleFP);
904     AddOpt(LibFunc::cosh, LibFunc::coshf, &UnsafeUnaryDoubleFP);
905     AddOpt(LibFunc::exp, LibFunc::expf, &UnsafeUnaryDoubleFP);
906     AddOpt(LibFunc::exp10, LibFunc::exp10f, &UnsafeUnaryDoubleFP);
907     AddOpt(LibFunc::expm1, LibFunc::expm1f, &UnsafeUnaryDoubleFP);
908     AddOpt(LibFunc::log, LibFunc::logf, &UnsafeUnaryDoubleFP);
909     AddOpt(LibFunc::log10, LibFunc::log10f, &UnsafeUnaryDoubleFP);
910     AddOpt(LibFunc::log1p, LibFunc::log1pf, &UnsafeUnaryDoubleFP);
911     AddOpt(LibFunc::log2, LibFunc::log2f, &UnsafeUnaryDoubleFP);
912     AddOpt(LibFunc::logb, LibFunc::logbf, &UnsafeUnaryDoubleFP);
913     AddOpt(LibFunc::sin, LibFunc::sinf, &UnsafeUnaryDoubleFP);
914     AddOpt(LibFunc::sinh, LibFunc::sinhf, &UnsafeUnaryDoubleFP);
915     AddOpt(LibFunc::sqrt, LibFunc::sqrtf, &UnsafeUnaryDoubleFP);
916     AddOpt(LibFunc::tan, LibFunc::tanf, &UnsafeUnaryDoubleFP);
917     AddOpt(LibFunc::tanh, LibFunc::tanhf, &UnsafeUnaryDoubleFP);
918   }
919
920   // Integer Optimizations
921   Optimizations["ffs"] = &FFS;
922   Optimizations["ffsl"] = &FFS;
923   Optimizations["ffsll"] = &FFS;
924   Optimizations["abs"] = &Abs;
925   Optimizations["labs"] = &Abs;
926   Optimizations["llabs"] = &Abs;
927   Optimizations["isdigit"] = &IsDigit;
928   Optimizations["isascii"] = &IsAscii;
929   Optimizations["toascii"] = &ToAscii;
930
931   // Formatting and IO Optimizations
932   Optimizations["sprintf"] = &SPrintF;
933   Optimizations["printf"] = &PrintF;
934   AddOpt(LibFunc::fwrite, &FWrite);
935   AddOpt(LibFunc::fputs, &FPuts);
936   Optimizations["fprintf"] = &FPrintF;
937   Optimizations["puts"] = &Puts;
938 }
939
940
941 /// runOnFunction - Top level algorithm.
942 ///
943 bool SimplifyLibCalls::runOnFunction(Function &F) {
944   TLI = &getAnalysis<TargetLibraryInfo>();
945
946   if (Optimizations.empty())
947     InitOptimizations();
948
949   const DataLayout *TD = getAnalysisIfAvailable<DataLayout>();
950
951   IRBuilder<> Builder(F.getContext());
952
953   bool Changed = false;
954   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
955     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
956       // Ignore non-calls.
957       CallInst *CI = dyn_cast<CallInst>(I++);
958       if (!CI) continue;
959
960       // Ignore indirect calls and calls to non-external functions.
961       Function *Callee = CI->getCalledFunction();
962       if (Callee == 0 || !Callee->isDeclaration() ||
963           !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
964         continue;
965
966       // Ignore unknown calls.
967       LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
968       if (!LCO) continue;
969
970       // Set the builder to the instruction after the call.
971       Builder.SetInsertPoint(BB, I);
972
973       // Use debug location of CI for all new instructions.
974       Builder.SetCurrentDebugLocation(CI->getDebugLoc());
975
976       // Try to optimize this call.
977       Value *Result = LCO->OptimizeCall(CI, TD, TLI, Builder);
978       if (Result == 0) continue;
979
980       DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
981             dbgs() << "  into: " << *Result << "\n");
982
983       // Something changed!
984       Changed = true;
985       ++NumSimplified;
986
987       // Inspect the instruction after the call (which was potentially just
988       // added) next.
989       I = CI; ++I;
990
991       if (CI != Result && !CI->use_empty()) {
992         CI->replaceAllUsesWith(Result);
993         if (!Result->hasName())
994           Result->takeName(CI);
995       }
996       CI->eraseFromParent();
997     }
998   }
999   return Changed;
1000 }
1001
1002 // Utility methods for doInitialization.
1003
1004 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1005   if (!F.doesNotAccessMemory()) {
1006     F.setDoesNotAccessMemory();
1007     ++NumAnnotated;
1008     Modified = true;
1009   }
1010 }
1011 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1012   if (!F.onlyReadsMemory()) {
1013     F.setOnlyReadsMemory();
1014     ++NumAnnotated;
1015     Modified = true;
1016   }
1017 }
1018 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1019   if (!F.doesNotThrow()) {
1020     F.setDoesNotThrow();
1021     ++NumAnnotated;
1022     Modified = true;
1023   }
1024 }
1025 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1026   if (!F.doesNotCapture(n)) {
1027     F.setDoesNotCapture(n);
1028     ++NumAnnotated;
1029     Modified = true;
1030   }
1031 }
1032 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1033   if (!F.doesNotAlias(n)) {
1034     F.setDoesNotAlias(n);
1035     ++NumAnnotated;
1036     Modified = true;
1037   }
1038 }
1039
1040
1041 void SimplifyLibCalls::inferPrototypeAttributes(Function &F) {
1042   FunctionType *FTy = F.getFunctionType();
1043
1044   StringRef Name = F.getName();
1045   switch (Name[0]) {
1046   case 's':
1047     if (Name == "strlen") {
1048       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1049         return;
1050       setOnlyReadsMemory(F);
1051       setDoesNotThrow(F);
1052       setDoesNotCapture(F, 1);
1053     } else if (Name == "strchr" ||
1054                Name == "strrchr") {
1055       if (FTy->getNumParams() != 2 ||
1056           !FTy->getParamType(0)->isPointerTy() ||
1057           !FTy->getParamType(1)->isIntegerTy())
1058         return;
1059       setOnlyReadsMemory(F);
1060       setDoesNotThrow(F);
1061     } else if (Name == "strcpy" ||
1062                Name == "stpcpy" ||
1063                Name == "strcat" ||
1064                Name == "strtol" ||
1065                Name == "strtod" ||
1066                Name == "strtof" ||
1067                Name == "strtoul" ||
1068                Name == "strtoll" ||
1069                Name == "strtold" ||
1070                Name == "strncat" ||
1071                Name == "strncpy" ||
1072                Name == "stpncpy" ||
1073                Name == "strtoull") {
1074       if (FTy->getNumParams() < 2 ||
1075           !FTy->getParamType(1)->isPointerTy())
1076         return;
1077       setDoesNotThrow(F);
1078       setDoesNotCapture(F, 2);
1079     } else if (Name == "strxfrm") {
1080       if (FTy->getNumParams() != 3 ||
1081           !FTy->getParamType(0)->isPointerTy() ||
1082           !FTy->getParamType(1)->isPointerTy())
1083         return;
1084       setDoesNotThrow(F);
1085       setDoesNotCapture(F, 1);
1086       setDoesNotCapture(F, 2);
1087     } else if (Name == "strcmp" ||
1088                Name == "strspn" ||
1089                Name == "strncmp" ||
1090                Name == "strcspn" ||
1091                Name == "strcoll" ||
1092                Name == "strcasecmp" ||
1093                Name == "strncasecmp") {
1094       if (FTy->getNumParams() < 2 ||
1095           !FTy->getParamType(0)->isPointerTy() ||
1096           !FTy->getParamType(1)->isPointerTy())
1097         return;
1098       setOnlyReadsMemory(F);
1099       setDoesNotThrow(F);
1100       setDoesNotCapture(F, 1);
1101       setDoesNotCapture(F, 2);
1102     } else if (Name == "strstr" ||
1103                Name == "strpbrk") {
1104       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1105         return;
1106       setOnlyReadsMemory(F);
1107       setDoesNotThrow(F);
1108       setDoesNotCapture(F, 2);
1109     } else if (Name == "strtok" ||
1110                Name == "strtok_r") {
1111       if (FTy->getNumParams() < 2 || !FTy->getParamType(1)->isPointerTy())
1112         return;
1113       setDoesNotThrow(F);
1114       setDoesNotCapture(F, 2);
1115     } else if (Name == "scanf" ||
1116                Name == "setbuf" ||
1117                Name == "setvbuf") {
1118       if (FTy->getNumParams() < 1 || !FTy->getParamType(0)->isPointerTy())
1119         return;
1120       setDoesNotThrow(F);
1121       setDoesNotCapture(F, 1);
1122     } else if (Name == "strdup" ||
1123                Name == "strndup") {
1124       if (FTy->getNumParams() < 1 || !FTy->getReturnType()->isPointerTy() ||
1125           !FTy->getParamType(0)->isPointerTy())
1126         return;
1127       setDoesNotThrow(F);
1128       setDoesNotAlias(F, 0);
1129       setDoesNotCapture(F, 1);
1130     } else if (Name == "stat" ||
1131                Name == "sscanf" ||
1132                Name == "sprintf" ||
1133                Name == "statvfs") {
1134       if (FTy->getNumParams() < 2 ||
1135           !FTy->getParamType(0)->isPointerTy() ||
1136           !FTy->getParamType(1)->isPointerTy())
1137         return;
1138       setDoesNotThrow(F);
1139       setDoesNotCapture(F, 1);
1140       setDoesNotCapture(F, 2);
1141     } else if (Name == "snprintf") {
1142       if (FTy->getNumParams() != 3 ||
1143           !FTy->getParamType(0)->isPointerTy() ||
1144           !FTy->getParamType(2)->isPointerTy())
1145         return;
1146       setDoesNotThrow(F);
1147       setDoesNotCapture(F, 1);
1148       setDoesNotCapture(F, 3);
1149     } else if (Name == "setitimer") {
1150       if (FTy->getNumParams() != 3 ||
1151           !FTy->getParamType(1)->isPointerTy() ||
1152           !FTy->getParamType(2)->isPointerTy())
1153         return;
1154       setDoesNotThrow(F);
1155       setDoesNotCapture(F, 2);
1156       setDoesNotCapture(F, 3);
1157     } else if (Name == "system") {
1158       if (FTy->getNumParams() != 1 ||
1159           !FTy->getParamType(0)->isPointerTy())
1160         return;
1161       // May throw; "system" is a valid pthread cancellation point.
1162       setDoesNotCapture(F, 1);
1163     }
1164     break;
1165   case 'm':
1166     if (Name == "malloc") {
1167       if (FTy->getNumParams() != 1 ||
1168           !FTy->getReturnType()->isPointerTy())
1169         return;
1170       setDoesNotThrow(F);
1171       setDoesNotAlias(F, 0);
1172     } else if (Name == "memcmp") {
1173       if (FTy->getNumParams() != 3 ||
1174           !FTy->getParamType(0)->isPointerTy() ||
1175           !FTy->getParamType(1)->isPointerTy())
1176         return;
1177       setOnlyReadsMemory(F);
1178       setDoesNotThrow(F);
1179       setDoesNotCapture(F, 1);
1180       setDoesNotCapture(F, 2);
1181     } else if (Name == "memchr" ||
1182                Name == "memrchr") {
1183       if (FTy->getNumParams() != 3)
1184         return;
1185       setOnlyReadsMemory(F);
1186       setDoesNotThrow(F);
1187     } else if (Name == "modf" ||
1188                Name == "modff" ||
1189                Name == "modfl" ||
1190                Name == "memcpy" ||
1191                Name == "memccpy" ||
1192                Name == "memmove") {
1193       if (FTy->getNumParams() < 2 ||
1194           !FTy->getParamType(1)->isPointerTy())
1195         return;
1196       setDoesNotThrow(F);
1197       setDoesNotCapture(F, 2);
1198     } else if (Name == "memalign") {
1199       if (!FTy->getReturnType()->isPointerTy())
1200         return;
1201       setDoesNotAlias(F, 0);
1202     } else if (Name == "mkdir" ||
1203                Name == "mktime") {
1204       if (FTy->getNumParams() == 0 ||
1205           !FTy->getParamType(0)->isPointerTy())
1206         return;
1207       setDoesNotThrow(F);
1208       setDoesNotCapture(F, 1);
1209     }
1210     break;
1211   case 'r':
1212     if (Name == "realloc") {
1213       if (FTy->getNumParams() != 2 ||
1214           !FTy->getParamType(0)->isPointerTy() ||
1215           !FTy->getReturnType()->isPointerTy())
1216         return;
1217       setDoesNotThrow(F);
1218       setDoesNotAlias(F, 0);
1219       setDoesNotCapture(F, 1);
1220     } else if (Name == "read") {
1221       if (FTy->getNumParams() != 3 ||
1222           !FTy->getParamType(1)->isPointerTy())
1223         return;
1224       // May throw; "read" is a valid pthread cancellation point.
1225       setDoesNotCapture(F, 2);
1226     } else if (Name == "rmdir" ||
1227                Name == "rewind" ||
1228                Name == "remove" ||
1229                Name == "realpath") {
1230       if (FTy->getNumParams() < 1 ||
1231           !FTy->getParamType(0)->isPointerTy())
1232         return;
1233       setDoesNotThrow(F);
1234       setDoesNotCapture(F, 1);
1235     } else if (Name == "rename" ||
1236                Name == "readlink") {
1237       if (FTy->getNumParams() < 2 ||
1238           !FTy->getParamType(0)->isPointerTy() ||
1239           !FTy->getParamType(1)->isPointerTy())
1240         return;
1241       setDoesNotThrow(F);
1242       setDoesNotCapture(F, 1);
1243       setDoesNotCapture(F, 2);
1244     }
1245     break;
1246   case 'w':
1247     if (Name == "write") {
1248       if (FTy->getNumParams() != 3 || !FTy->getParamType(1)->isPointerTy())
1249         return;
1250       // May throw; "write" is a valid pthread cancellation point.
1251       setDoesNotCapture(F, 2);
1252     }
1253     break;
1254   case 'b':
1255     if (Name == "bcopy") {
1256       if (FTy->getNumParams() != 3 ||
1257           !FTy->getParamType(0)->isPointerTy() ||
1258           !FTy->getParamType(1)->isPointerTy())
1259         return;
1260       setDoesNotThrow(F);
1261       setDoesNotCapture(F, 1);
1262       setDoesNotCapture(F, 2);
1263     } else if (Name == "bcmp") {
1264       if (FTy->getNumParams() != 3 ||
1265           !FTy->getParamType(0)->isPointerTy() ||
1266           !FTy->getParamType(1)->isPointerTy())
1267         return;
1268       setDoesNotThrow(F);
1269       setOnlyReadsMemory(F);
1270       setDoesNotCapture(F, 1);
1271       setDoesNotCapture(F, 2);
1272     } else if (Name == "bzero") {
1273       if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1274         return;
1275       setDoesNotThrow(F);
1276       setDoesNotCapture(F, 1);
1277     }
1278     break;
1279   case 'c':
1280     if (Name == "calloc") {
1281       if (FTy->getNumParams() != 2 ||
1282           !FTy->getReturnType()->isPointerTy())
1283         return;
1284       setDoesNotThrow(F);
1285       setDoesNotAlias(F, 0);
1286     } else if (Name == "chmod" ||
1287                Name == "chown" ||
1288                Name == "ctermid" ||
1289                Name == "clearerr" ||
1290                Name == "closedir") {
1291       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1292         return;
1293       setDoesNotThrow(F);
1294       setDoesNotCapture(F, 1);
1295     }
1296     break;
1297   case 'a':
1298     if (Name == "atoi" ||
1299         Name == "atol" ||
1300         Name == "atof" ||
1301         Name == "atoll") {
1302       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1303         return;
1304       setDoesNotThrow(F);
1305       setOnlyReadsMemory(F);
1306       setDoesNotCapture(F, 1);
1307     } else if (Name == "access") {
1308       if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1309         return;
1310       setDoesNotThrow(F);
1311       setDoesNotCapture(F, 1);
1312     }
1313     break;
1314   case 'f':
1315     if (Name == "fopen") {
1316       if (FTy->getNumParams() != 2 ||
1317           !FTy->getReturnType()->isPointerTy() ||
1318           !FTy->getParamType(0)->isPointerTy() ||
1319           !FTy->getParamType(1)->isPointerTy())
1320         return;
1321       setDoesNotThrow(F);
1322       setDoesNotAlias(F, 0);
1323       setDoesNotCapture(F, 1);
1324       setDoesNotCapture(F, 2);
1325     } else if (Name == "fdopen") {
1326       if (FTy->getNumParams() != 2 ||
1327           !FTy->getReturnType()->isPointerTy() ||
1328           !FTy->getParamType(1)->isPointerTy())
1329         return;
1330       setDoesNotThrow(F);
1331       setDoesNotAlias(F, 0);
1332       setDoesNotCapture(F, 2);
1333     } else if (Name == "feof" ||
1334                Name == "free" ||
1335                Name == "fseek" ||
1336                Name == "ftell" ||
1337                Name == "fgetc" ||
1338                Name == "fseeko" ||
1339                Name == "ftello" ||
1340                Name == "fileno" ||
1341                Name == "fflush" ||
1342                Name == "fclose" ||
1343                Name == "fsetpos" ||
1344                Name == "flockfile" ||
1345                Name == "funlockfile" ||
1346                Name == "ftrylockfile") {
1347       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1348         return;
1349       setDoesNotThrow(F);
1350       setDoesNotCapture(F, 1);
1351     } else if (Name == "ferror") {
1352       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1353         return;
1354       setDoesNotThrow(F);
1355       setDoesNotCapture(F, 1);
1356       setOnlyReadsMemory(F);
1357     } else if (Name == "fputc" ||
1358                Name == "fstat" ||
1359                Name == "frexp" ||
1360                Name == "frexpf" ||
1361                Name == "frexpl" ||
1362                Name == "fstatvfs") {
1363       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1364         return;
1365       setDoesNotThrow(F);
1366       setDoesNotCapture(F, 2);
1367     } else if (Name == "fgets") {
1368       if (FTy->getNumParams() != 3 ||
1369           !FTy->getParamType(0)->isPointerTy() ||
1370           !FTy->getParamType(2)->isPointerTy())
1371         return;
1372       setDoesNotThrow(F);
1373       setDoesNotCapture(F, 3);
1374     } else if (Name == "fread" ||
1375                Name == "fwrite") {
1376       if (FTy->getNumParams() != 4 ||
1377           !FTy->getParamType(0)->isPointerTy() ||
1378           !FTy->getParamType(3)->isPointerTy())
1379         return;
1380       setDoesNotThrow(F);
1381       setDoesNotCapture(F, 1);
1382       setDoesNotCapture(F, 4);
1383     } else if (Name == "fputs" ||
1384                Name == "fscanf" ||
1385                Name == "fprintf" ||
1386                Name == "fgetpos") {
1387       if (FTy->getNumParams() < 2 ||
1388           !FTy->getParamType(0)->isPointerTy() ||
1389           !FTy->getParamType(1)->isPointerTy())
1390         return;
1391       setDoesNotThrow(F);
1392       setDoesNotCapture(F, 1);
1393       setDoesNotCapture(F, 2);
1394     }
1395     break;
1396   case 'g':
1397     if (Name == "getc" ||
1398         Name == "getlogin_r" ||
1399         Name == "getc_unlocked") {
1400       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1401         return;
1402       setDoesNotThrow(F);
1403       setDoesNotCapture(F, 1);
1404     } else if (Name == "getenv") {
1405       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1406         return;
1407       setDoesNotThrow(F);
1408       setOnlyReadsMemory(F);
1409       setDoesNotCapture(F, 1);
1410     } else if (Name == "gets" ||
1411                Name == "getchar") {
1412       setDoesNotThrow(F);
1413     } else if (Name == "getitimer") {
1414       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1415         return;
1416       setDoesNotThrow(F);
1417       setDoesNotCapture(F, 2);
1418     } else if (Name == "getpwnam") {
1419       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1420         return;
1421       setDoesNotThrow(F);
1422       setDoesNotCapture(F, 1);
1423     }
1424     break;
1425   case 'u':
1426     if (Name == "ungetc") {
1427       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1428         return;
1429       setDoesNotThrow(F);
1430       setDoesNotCapture(F, 2);
1431     } else if (Name == "uname" ||
1432                Name == "unlink" ||
1433                Name == "unsetenv") {
1434       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1435         return;
1436       setDoesNotThrow(F);
1437       setDoesNotCapture(F, 1);
1438     } else if (Name == "utime" ||
1439                Name == "utimes") {
1440       if (FTy->getNumParams() != 2 ||
1441           !FTy->getParamType(0)->isPointerTy() ||
1442           !FTy->getParamType(1)->isPointerTy())
1443         return;
1444       setDoesNotThrow(F);
1445       setDoesNotCapture(F, 1);
1446       setDoesNotCapture(F, 2);
1447     }
1448     break;
1449   case 'p':
1450     if (Name == "putc") {
1451       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1452         return;
1453       setDoesNotThrow(F);
1454       setDoesNotCapture(F, 2);
1455     } else if (Name == "puts" ||
1456                Name == "printf" ||
1457                Name == "perror") {
1458       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1459         return;
1460       setDoesNotThrow(F);
1461       setDoesNotCapture(F, 1);
1462     } else if (Name == "pread" ||
1463                Name == "pwrite") {
1464       if (FTy->getNumParams() != 4 || !FTy->getParamType(1)->isPointerTy())
1465         return;
1466       // May throw; these are valid pthread cancellation points.
1467       setDoesNotCapture(F, 2);
1468     } else if (Name == "putchar") {
1469       setDoesNotThrow(F);
1470     } else if (Name == "popen") {
1471       if (FTy->getNumParams() != 2 ||
1472           !FTy->getReturnType()->isPointerTy() ||
1473           !FTy->getParamType(0)->isPointerTy() ||
1474           !FTy->getParamType(1)->isPointerTy())
1475         return;
1476       setDoesNotThrow(F);
1477       setDoesNotAlias(F, 0);
1478       setDoesNotCapture(F, 1);
1479       setDoesNotCapture(F, 2);
1480     } else if (Name == "pclose") {
1481       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1482         return;
1483       setDoesNotThrow(F);
1484       setDoesNotCapture(F, 1);
1485     }
1486     break;
1487   case 'v':
1488     if (Name == "vscanf") {
1489       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1490         return;
1491       setDoesNotThrow(F);
1492       setDoesNotCapture(F, 1);
1493     } else if (Name == "vsscanf" ||
1494                Name == "vfscanf") {
1495       if (FTy->getNumParams() != 3 ||
1496           !FTy->getParamType(1)->isPointerTy() ||
1497           !FTy->getParamType(2)->isPointerTy())
1498         return;
1499       setDoesNotThrow(F);
1500       setDoesNotCapture(F, 1);
1501       setDoesNotCapture(F, 2);
1502     } else if (Name == "valloc") {
1503       if (!FTy->getReturnType()->isPointerTy())
1504         return;
1505       setDoesNotThrow(F);
1506       setDoesNotAlias(F, 0);
1507     } else if (Name == "vprintf") {
1508       if (FTy->getNumParams() != 2 || !FTy->getParamType(0)->isPointerTy())
1509         return;
1510       setDoesNotThrow(F);
1511       setDoesNotCapture(F, 1);
1512     } else if (Name == "vfprintf" ||
1513                Name == "vsprintf") {
1514       if (FTy->getNumParams() != 3 ||
1515           !FTy->getParamType(0)->isPointerTy() ||
1516           !FTy->getParamType(1)->isPointerTy())
1517         return;
1518       setDoesNotThrow(F);
1519       setDoesNotCapture(F, 1);
1520       setDoesNotCapture(F, 2);
1521     } else if (Name == "vsnprintf") {
1522       if (FTy->getNumParams() != 4 ||
1523           !FTy->getParamType(0)->isPointerTy() ||
1524           !FTy->getParamType(2)->isPointerTy())
1525         return;
1526       setDoesNotThrow(F);
1527       setDoesNotCapture(F, 1);
1528       setDoesNotCapture(F, 3);
1529     }
1530     break;
1531   case 'o':
1532     if (Name == "open") {
1533       if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1534         return;
1535       // May throw; "open" is a valid pthread cancellation point.
1536       setDoesNotCapture(F, 1);
1537     } else if (Name == "opendir") {
1538       if (FTy->getNumParams() != 1 ||
1539           !FTy->getReturnType()->isPointerTy() ||
1540           !FTy->getParamType(0)->isPointerTy())
1541         return;
1542       setDoesNotThrow(F);
1543       setDoesNotAlias(F, 0);
1544       setDoesNotCapture(F, 1);
1545     }
1546     break;
1547   case 't':
1548     if (Name == "tmpfile") {
1549       if (!FTy->getReturnType()->isPointerTy())
1550         return;
1551       setDoesNotThrow(F);
1552       setDoesNotAlias(F, 0);
1553     } else if (Name == "times") {
1554       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1555         return;
1556       setDoesNotThrow(F);
1557       setDoesNotCapture(F, 1);
1558     }
1559     break;
1560   case 'h':
1561     if (Name == "htonl" ||
1562         Name == "htons") {
1563       setDoesNotThrow(F);
1564       setDoesNotAccessMemory(F);
1565     }
1566     break;
1567   case 'n':
1568     if (Name == "ntohl" ||
1569         Name == "ntohs") {
1570       setDoesNotThrow(F);
1571       setDoesNotAccessMemory(F);
1572     }
1573     break;
1574   case 'l':
1575     if (Name == "lstat") {
1576       if (FTy->getNumParams() != 2 ||
1577           !FTy->getParamType(0)->isPointerTy() ||
1578           !FTy->getParamType(1)->isPointerTy())
1579         return;
1580       setDoesNotThrow(F);
1581       setDoesNotCapture(F, 1);
1582       setDoesNotCapture(F, 2);
1583     } else if (Name == "lchown") {
1584       if (FTy->getNumParams() != 3 || !FTy->getParamType(0)->isPointerTy())
1585         return;
1586       setDoesNotThrow(F);
1587       setDoesNotCapture(F, 1);
1588     }
1589     break;
1590   case 'q':
1591     if (Name == "qsort") {
1592       if (FTy->getNumParams() != 4 || !FTy->getParamType(3)->isPointerTy())
1593         return;
1594       // May throw; places call through function pointer.
1595       setDoesNotCapture(F, 4);
1596     }
1597     break;
1598   case '_':
1599     if (Name == "__strdup" ||
1600         Name == "__strndup") {
1601       if (FTy->getNumParams() < 1 ||
1602           !FTy->getReturnType()->isPointerTy() ||
1603           !FTy->getParamType(0)->isPointerTy())
1604         return;
1605       setDoesNotThrow(F);
1606       setDoesNotAlias(F, 0);
1607       setDoesNotCapture(F, 1);
1608     } else if (Name == "__strtok_r") {
1609       if (FTy->getNumParams() != 3 ||
1610           !FTy->getParamType(1)->isPointerTy())
1611         return;
1612       setDoesNotThrow(F);
1613       setDoesNotCapture(F, 2);
1614     } else if (Name == "_IO_getc") {
1615       if (FTy->getNumParams() != 1 || !FTy->getParamType(0)->isPointerTy())
1616         return;
1617       setDoesNotThrow(F);
1618       setDoesNotCapture(F, 1);
1619     } else if (Name == "_IO_putc") {
1620       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1621         return;
1622       setDoesNotThrow(F);
1623       setDoesNotCapture(F, 2);
1624     }
1625     break;
1626   case 1:
1627     if (Name == "\1__isoc99_scanf") {
1628       if (FTy->getNumParams() < 1 ||
1629           !FTy->getParamType(0)->isPointerTy())
1630         return;
1631       setDoesNotThrow(F);
1632       setDoesNotCapture(F, 1);
1633     } else if (Name == "\1stat64" ||
1634                Name == "\1lstat64" ||
1635                Name == "\1statvfs64" ||
1636                Name == "\1__isoc99_sscanf") {
1637       if (FTy->getNumParams() < 1 ||
1638           !FTy->getParamType(0)->isPointerTy() ||
1639           !FTy->getParamType(1)->isPointerTy())
1640         return;
1641       setDoesNotThrow(F);
1642       setDoesNotCapture(F, 1);
1643       setDoesNotCapture(F, 2);
1644     } else if (Name == "\1fopen64") {
1645       if (FTy->getNumParams() != 2 ||
1646           !FTy->getReturnType()->isPointerTy() ||
1647           !FTy->getParamType(0)->isPointerTy() ||
1648           !FTy->getParamType(1)->isPointerTy())
1649         return;
1650       setDoesNotThrow(F);
1651       setDoesNotAlias(F, 0);
1652       setDoesNotCapture(F, 1);
1653       setDoesNotCapture(F, 2);
1654     } else if (Name == "\1fseeko64" ||
1655                Name == "\1ftello64") {
1656       if (FTy->getNumParams() == 0 || !FTy->getParamType(0)->isPointerTy())
1657         return;
1658       setDoesNotThrow(F);
1659       setDoesNotCapture(F, 1);
1660     } else if (Name == "\1tmpfile64") {
1661       if (!FTy->getReturnType()->isPointerTy())
1662         return;
1663       setDoesNotThrow(F);
1664       setDoesNotAlias(F, 0);
1665     } else if (Name == "\1fstat64" ||
1666                Name == "\1fstatvfs64") {
1667       if (FTy->getNumParams() != 2 || !FTy->getParamType(1)->isPointerTy())
1668         return;
1669       setDoesNotThrow(F);
1670       setDoesNotCapture(F, 2);
1671     } else if (Name == "\1open64") {
1672       if (FTy->getNumParams() < 2 || !FTy->getParamType(0)->isPointerTy())
1673         return;
1674       // May throw; "open" is a valid pthread cancellation point.
1675       setDoesNotCapture(F, 1);
1676     }
1677     break;
1678   }
1679 }
1680
1681 /// doInitialization - Add attributes to well-known functions.
1682 ///
1683 bool SimplifyLibCalls::doInitialization(Module &M) {
1684   Modified = false;
1685   for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1686     Function &F = *I;
1687     if (F.isDeclaration() && F.hasName())
1688       inferPrototypeAttributes(F);
1689   }
1690   return Modified;
1691 }
1692
1693 // TODO:
1694 //   Additional cases that we need to add to this file:
1695 //
1696 // cbrt:
1697 //   * cbrt(expN(X))  -> expN(x/3)
1698 //   * cbrt(sqrt(x))  -> pow(x,1/6)
1699 //   * cbrt(sqrt(x))  -> pow(x,1/9)
1700 //
1701 // exp, expf, expl:
1702 //   * exp(log(x))  -> x
1703 //
1704 // log, logf, logl:
1705 //   * log(exp(x))   -> x
1706 //   * log(x**y)     -> y*log(x)
1707 //   * log(exp(y))   -> y*log(e)
1708 //   * log(exp2(y))  -> y*log(2)
1709 //   * log(exp10(y)) -> y*log(10)
1710 //   * log(sqrt(x))  -> 0.5*log(x)
1711 //   * log(pow(x,y)) -> y*log(x)
1712 //
1713 // lround, lroundf, lroundl:
1714 //   * lround(cnst) -> cnst'
1715 //
1716 // pow, powf, powl:
1717 //   * pow(exp(x),y)  -> exp(x*y)
1718 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1719 //   * pow(pow(x,y),z)-> pow(x,y*z)
1720 //
1721 // round, roundf, roundl:
1722 //   * round(cnst) -> cnst'
1723 //
1724 // signbit:
1725 //   * signbit(cnst) -> cnst'
1726 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1727 //
1728 // sqrt, sqrtf, sqrtl:
1729 //   * sqrt(expN(x))  -> expN(x*0.5)
1730 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1731 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1732 //
1733 // strchr:
1734 //   * strchr(p, 0) -> strlen(p)
1735 // tan, tanf, tanl:
1736 //   * tan(atan(x)) -> x
1737 //
1738 // trunc, truncf, truncl:
1739 //   * trunc(cnst) -> cnst'
1740 //
1741 //