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