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