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