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