Turn strcmp into memcmp, such as strcmp(P, "x") --> memcmp(P, "x", 2).
[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
38 //===----------------------------------------------------------------------===//
39 // Optimizer Base Class
40 //===----------------------------------------------------------------------===//
41
42 /// This class is the abstract base class for the set of optimizations that
43 /// corresponds to one library call.
44 namespace {
45 class VISIBILITY_HIDDEN LibCallOptimization {
46 protected:
47   Function *Caller;
48   const TargetData *TD;
49 public:
50   LibCallOptimization() { }
51   virtual ~LibCallOptimization() {}
52
53   /// CallOptimizer - This pure virtual method is implemented by base classes to
54   /// do various optimizations.  If this returns null then no transformation was
55   /// performed.  If it returns CI, then it transformed the call and CI is to be
56   /// deleted.  If it returns something else, replace CI with the new value and
57   /// delete CI.
58   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) 
59     =0;
60   
61   Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
62     Caller = CI->getParent()->getParent();
63     this->TD = &TD;
64     return CallOptimizer(CI->getCalledFunction(), CI, B);
65   }
66
67   /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
68   Value *CastToCStr(Value *V, IRBuilder<> &B);
69
70   /// EmitStrLen - Emit a call to the strlen function to the builder, for the
71   /// specified pointer.  Ptr is required to be some pointer type, and the
72   /// return value has 'intptr_t' type.
73   Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
74   
75   /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This
76   /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
77   Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len, 
78                     unsigned Align, IRBuilder<> &B);
79   
80   /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
81   /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
82   Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
83
84   /// EmitMemCmp - Emit a call to the memcmp function.
85   Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
86
87   /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
88   /// 'floor').  This function is known to take a single of type matching 'Op'
89   /// and returns one value with the same type.  If 'Op' is a long double, 'l'
90   /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
91   Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
92   
93   /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
94   /// is an integer.
95   void EmitPutChar(Value *Char, IRBuilder<> &B);
96   
97   /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
98   /// some pointer.
99   void EmitPutS(Value *Str, IRBuilder<> &B);
100     
101   /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
102   /// an i32, and File is a pointer to FILE.
103   void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
104   
105   /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
106   /// pointer and File is a pointer to FILE.
107   void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
108   
109   /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
110   /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
111   void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
112   
113 };
114 } // End anonymous namespace.
115
116 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
117 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
118   return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
119 }
120
121 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
122 /// specified pointer.  This always returns an integer value of size intptr_t.
123 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
124   Module *M = Caller->getParent();
125   Constant *StrLen =M->getOrInsertFunction("strlen", TD->getIntPtrType(),
126                                            PointerType::getUnqual(Type::Int8Ty),
127                                            NULL);
128   return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
129 }
130
131 /// EmitMemCpy - Emit a call to the memcpy function to the builder.  This always
132 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
133 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
134                                        unsigned Align, IRBuilder<> &B) {
135   Module *M = Caller->getParent();
136   Intrinsic::ID IID = Intrinsic::memcpy;
137   const Type *Tys[1];
138   Tys[0] = Len->getType();
139   Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
140   return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
141                        ConstantInt::get(Type::Int32Ty, Align));
142 }
143
144 /// EmitMemChr - Emit a call to the memchr function.  This assumes that Ptr is
145 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
146 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
147                                        Value *Len, IRBuilder<> &B) {
148   Module *M = Caller->getParent();
149   Value *MemChr = M->getOrInsertFunction("memchr",
150                                          PointerType::getUnqual(Type::Int8Ty),
151                                          PointerType::getUnqual(Type::Int8Ty),
152                                          Type::Int32Ty, TD->getIntPtrType(),
153                                          NULL);
154   return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
155 }
156
157 /// EmitMemCmp - Emit a call to the memcmp function.
158 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
159                                        Value *Len, IRBuilder<> &B) {
160   Module *M = Caller->getParent();
161   Value *MemCmp = M->getOrInsertFunction("memcmp",
162                                          Type::Int32Ty,
163                                          PointerType::getUnqual(Type::Int8Ty),
164                                          PointerType::getUnqual(Type::Int8Ty),
165                                          TD->getIntPtrType(), NULL);
166   return B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
167                        Len, "memcmp");
168 }
169
170 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
171 /// 'floor').  This function is known to take a single of type matching 'Op' and
172 /// returns one value with the same type.  If 'Op' is a long double, 'l' is
173 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
174 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
175                                                  IRBuilder<> &B) {
176   char NameBuffer[20];
177   if (Op->getType() != Type::DoubleTy) {
178     // If we need to add a suffix, copy into NameBuffer.
179     unsigned NameLen = strlen(Name);
180     assert(NameLen < sizeof(NameBuffer)-2);
181     memcpy(NameBuffer, Name, NameLen);
182     if (Op->getType() == Type::FloatTy)
183       NameBuffer[NameLen] = 'f';  // floorf
184     else
185       NameBuffer[NameLen] = 'l';  // floorl
186     NameBuffer[NameLen+1] = 0;
187     Name = NameBuffer;
188   }
189   
190   Module *M = Caller->getParent();
191   Value *Callee = M->getOrInsertFunction(Name, Op->getType(), 
192                                          Op->getType(), NULL);
193   return B.CreateCall(Callee, Op, Name);
194 }
195
196 /// EmitPutChar - Emit a call to the putchar function.  This assumes that Char
197 /// is an integer.
198 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
199   Module *M = Caller->getParent();
200   Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
201                                     Type::Int32Ty, NULL);
202   B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
203 }
204
205 /// EmitPutS - Emit a call to the puts function.  This assumes that Str is
206 /// some pointer.
207 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
208   Module *M = Caller->getParent();
209   Value *F = M->getOrInsertFunction("puts", Type::Int32Ty,
210                                     PointerType::getUnqual(Type::Int8Ty), NULL);
211   B.CreateCall(F, CastToCStr(Str, B), "puts");
212 }
213
214 /// EmitFPutC - Emit a call to the fputc function.  This assumes that Char is
215 /// an integer and File is a pointer to FILE.
216 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
217   Module *M = Caller->getParent();
218   Constant *F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
219                                        File->getType(), NULL);
220   Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
221   B.CreateCall2(F, Char, File, "fputc");
222 }
223
224 /// EmitFPutS - Emit a call to the puts function.  Str is required to be a
225 /// pointer and File is a pointer to FILE.
226 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
227   Module *M = Caller->getParent();
228   Constant *F = M->getOrInsertFunction("fputs", Type::Int32Ty,
229                                        PointerType::getUnqual(Type::Int8Ty),
230                                        File->getType(), NULL);
231   B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
232 }
233
234 /// EmitFWrite - Emit a call to the fwrite function.  This assumes that Ptr is
235 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
236 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
237                                      IRBuilder<> &B) {
238   Module *M = Caller->getParent();
239   Constant *F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
240                                        PointerType::getUnqual(Type::Int8Ty),
241                                        TD->getIntPtrType(), TD->getIntPtrType(),
242                                        File->getType(), NULL);
243   B.CreateCall4(F, CastToCStr(Ptr, B), Size, 
244                 ConstantInt::get(TD->getIntPtrType(), 1), File);
245 }
246
247 //===----------------------------------------------------------------------===//
248 // Helper Functions
249 //===----------------------------------------------------------------------===//
250
251 /// GetStringLengthH - If we can compute the length of the string pointed to by
252 /// the specified pointer, return 'len+1'.  If we can't, return 0.
253 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
254   // Look through noop bitcast instructions.
255   if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
256     return GetStringLengthH(BCI->getOperand(0), PHIs);
257   
258   // If this is a PHI node, there are two cases: either we have already seen it
259   // or we haven't.
260   if (PHINode *PN = dyn_cast<PHINode>(V)) {
261     if (!PHIs.insert(PN))
262       return ~0ULL;  // already in the set.
263     
264     // If it was new, see if all the input strings are the same length.
265     uint64_t LenSoFar = ~0ULL;
266     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
267       uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
268       if (Len == 0) return 0; // Unknown length -> unknown.
269       
270       if (Len == ~0ULL) continue;
271       
272       if (Len != LenSoFar && LenSoFar != ~0ULL)
273         return 0;    // Disagree -> unknown.
274       LenSoFar = Len;
275     }
276     
277     // Success, all agree.
278     return LenSoFar;
279   }
280   
281   // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
282   if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
283     uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
284     if (Len1 == 0) return 0;
285     uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
286     if (Len2 == 0) return 0;
287     if (Len1 == ~0ULL) return Len2;
288     if (Len2 == ~0ULL) return Len1;
289     if (Len1 != Len2) return 0;
290     return Len1;
291   }
292   
293   // If the value is not a GEP instruction nor a constant expression with a
294   // GEP instruction, then return unknown.
295   User *GEP = 0;
296   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
297     GEP = GEPI;
298   } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
299     if (CE->getOpcode() != Instruction::GetElementPtr)
300       return 0;
301     GEP = CE;
302   } else {
303     return 0;
304   }
305   
306   // Make sure the GEP has exactly three arguments.
307   if (GEP->getNumOperands() != 3)
308     return 0;
309   
310   // Check to make sure that the first operand of the GEP is an integer and
311   // has value 0 so that we are sure we're indexing into the initializer.
312   if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
313     if (!Idx->isZero())
314       return 0;
315   } else
316     return 0;
317   
318   // If the second index isn't a ConstantInt, then this is a variable index
319   // into the array.  If this occurs, we can't say anything meaningful about
320   // the string.
321   uint64_t StartIdx = 0;
322   if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
323     StartIdx = CI->getZExtValue();
324   else
325     return 0;
326   
327   // The GEP instruction, constant or instruction, must reference a global
328   // variable that is a constant and is initialized. The referenced constant
329   // initializer is the array that we'll use for optimization.
330   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
331   if (!GV || !GV->isConstant() || !GV->hasInitializer())
332     return 0;
333   Constant *GlobalInit = GV->getInitializer();
334   
335   // Handle the ConstantAggregateZero case, which is a degenerate case. The
336   // initializer is constant zero so the length of the string must be zero.
337   if (isa<ConstantAggregateZero>(GlobalInit))
338     return 1;  // Len = 0 offset by 1.
339   
340   // Must be a Constant Array
341   ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
342   if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
343     return false;
344   
345   // Get the number of elements in the array
346   uint64_t NumElts = Array->getType()->getNumElements();
347   
348   // Traverse the constant array from StartIdx (derived above) which is
349   // the place the GEP refers to in the array.
350   for (unsigned i = StartIdx; i != NumElts; ++i) {
351     Constant *Elt = Array->getOperand(i);
352     ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
353     if (!CI) // This array isn't suitable, non-int initializer.
354       return 0;
355     if (CI->isZero())
356       return i-StartIdx+1; // We found end of string, success!
357   }
358   
359   return 0; // The array isn't null terminated, conservatively return 'unknown'.
360 }
361
362 /// GetStringLength - If we can compute the length of the string pointed to by
363 /// the specified pointer, return 'len+1'.  If we can't, return 0.
364 static uint64_t GetStringLength(Value *V) {
365   if (!isa<PointerType>(V->getType())) return 0;
366   
367   SmallPtrSet<PHINode*, 32> PHIs;
368   uint64_t Len = GetStringLengthH(V, PHIs);
369   // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
370   // an empty string as a length.
371   return Len == ~0ULL ? 1 : Len;
372 }
373
374 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
375 /// value is equal or not-equal to zero. 
376 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
377   for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
378        UI != E; ++UI) {
379     if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
380       if (IC->isEquality())
381         if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
382           if (C->isNullValue())
383             continue;
384     // Unknown instruction.
385     return false;
386   }
387   return true;
388 }
389
390 //===----------------------------------------------------------------------===//
391 // Miscellaneous LibCall Optimizations
392 //===----------------------------------------------------------------------===//
393
394 namespace {
395 //===---------------------------------------===//
396 // 'exit' Optimizations
397
398 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
399 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
400   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
401     // Verify we have a reasonable prototype for exit.
402     if (Callee->arg_size() == 0 || !CI->use_empty())
403       return 0;
404
405     // Verify the caller is main, and that the result type of main matches the
406     // argument type of exit.
407     if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
408         Caller->getReturnType() != CI->getOperand(1)->getType())
409       return 0;
410
411     TerminatorInst *OldTI = CI->getParent()->getTerminator();
412     
413     // Create the return after the call.
414     ReturnInst *RI = B.CreateRet(CI->getOperand(1));
415
416     // Drop all successor phi node entries.
417     for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
418       OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
419     
420     // Erase all instructions from after our return instruction until the end of
421     // the block.
422     BasicBlock::iterator FirstDead = RI; ++FirstDead;
423     CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
424     return CI;
425   }
426 };
427
428 //===----------------------------------------------------------------------===//
429 // String and Memory LibCall Optimizations
430 //===----------------------------------------------------------------------===//
431
432 //===---------------------------------------===//
433 // 'strcat' Optimizations
434
435 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
436   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
437     // Verify the "strcat" function prototype.
438     const FunctionType *FT = Callee->getFunctionType();
439     if (FT->getNumParams() != 2 ||
440         FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
441         FT->getParamType(0) != FT->getReturnType() ||
442         FT->getParamType(1) != FT->getReturnType())
443       return 0;
444     
445     // Extract some information from the instruction
446     Value *Dst = CI->getOperand(1);
447     Value *Src = CI->getOperand(2);
448     
449     // See if we can get the length of the input string.
450     uint64_t Len = GetStringLength(Src);
451     if (Len == 0) return 0;
452     --Len;  // Unbias length.
453     
454     // Handle the simple, do-nothing case: strcat(x, "") -> x
455     if (Len == 0)
456       return Dst;
457     
458     // We need to find the end of the destination string.  That's where the
459     // memory is to be moved to. We just generate a call to strlen.
460     Value *DstLen = EmitStrLen(Dst, B);
461     
462     // Now that we have the destination's length, we must index into the
463     // destination's pointer to get the actual memcpy destination (end of
464     // the string .. we're concatenating).
465     Dst = B.CreateGEP(Dst, DstLen, "endptr");
466     
467     // We have enough information to now generate the memcpy call to do the
468     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
469     EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
470     return Dst;
471   }
472 };
473
474 //===---------------------------------------===//
475 // 'strchr' Optimizations
476
477 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
478   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
479     // Verify the "strchr" function prototype.
480     const FunctionType *FT = Callee->getFunctionType();
481     if (FT->getNumParams() != 2 ||
482         FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
483         FT->getParamType(0) != FT->getReturnType())
484       return 0;
485     
486     Value *SrcStr = CI->getOperand(1);
487     
488     // If the second operand is non-constant, see if we can compute the length
489     // of the input string and turn this into memchr.
490     ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
491     if (CharC == 0) {
492       uint64_t Len = GetStringLength(SrcStr);
493       if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
494         return 0;
495       
496       return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
497                         ConstantInt::get(TD->getIntPtrType(), Len), B);
498     }
499
500     // Otherwise, the character is a constant, see if the first argument is
501     // a string literal.  If so, we can constant fold.
502     std::string Str;
503     if (!GetConstantStringInfo(SrcStr, Str))
504       return 0;
505     
506     // strchr can find the nul character.
507     Str += '\0';
508     char CharValue = CharC->getSExtValue();
509     
510     // Compute the offset.
511     uint64_t i = 0;
512     while (1) {
513       if (i == Str.size())    // Didn't find the char.  strchr returns null.
514         return Constant::getNullValue(CI->getType());
515       // Did we find our match?
516       if (Str[i] == CharValue)
517         break;
518       ++i;
519     }
520     
521     // strchr(s+n,c)  -> gep(s+n+i,c)
522     Value *Idx = ConstantInt::get(Type::Int64Ty, i);
523     return B.CreateGEP(SrcStr, Idx, "strchr");
524   }
525 };
526
527 //===---------------------------------------===//
528 // 'strcmp' Optimizations
529
530 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
531   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
532     // Verify the "strcmp" function prototype.
533     const FunctionType *FT = Callee->getFunctionType();
534     if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
535         FT->getParamType(0) != FT->getParamType(1) ||
536         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
537       return 0;
538     
539     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
540     if (Str1P == Str2P)      // strcmp(x,x)  -> 0
541       return ConstantInt::get(CI->getType(), 0);
542     
543     std::string Str1, Str2;
544     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
545     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
546     
547     if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
548       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
549     
550     if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
551       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
552     
553     // strcmp(x, y)  -> cnst  (if both x and y are constant strings)
554     if (HasStr1 && HasStr2)
555       return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
556
557     // strcmp(P, "x") -> memcmp(P, "x", 2)
558     uint64_t Len1 = GetStringLength(Str1P);
559     uint64_t Len2 = GetStringLength(Str2P);
560     if (Len1 || Len2) {
561       // Choose the smallest Len excluding 0 which means 'unknown'.
562       if (!Len1 || (Len2 && Len2 < Len1))
563         Len1 = Len2;
564       return EmitMemCmp(Str1P, Str2P,
565                         ConstantInt::get(TD->getIntPtrType(), Len1), B);
566     }
567
568     return 0;
569   }
570 };
571
572 //===---------------------------------------===//
573 // 'strncmp' Optimizations
574
575 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
576   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
577     // Verify the "strncmp" function prototype.
578     const FunctionType *FT = Callee->getFunctionType();
579     if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
580         FT->getParamType(0) != FT->getParamType(1) ||
581         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
582         !isa<IntegerType>(FT->getParamType(2)))
583       return 0;
584     
585     Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
586     if (Str1P == Str2P)      // strncmp(x,x,n)  -> 0
587       return ConstantInt::get(CI->getType(), 0);
588     
589     // Get the length argument if it is constant.
590     uint64_t Length;
591     if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
592       Length = LengthArg->getZExtValue();
593     else
594       return 0;
595     
596     if (Length == 0) // strncmp(x,y,0)   -> 0
597       return ConstantInt::get(CI->getType(), 0);
598     
599     std::string Str1, Str2;
600     bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
601     bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
602     
603     if (HasStr1 && Str1.empty())  // strncmp("", x, n) -> *x
604       return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
605     
606     if (HasStr2 && Str2.empty())  // strncmp(x, "", n) -> *x
607       return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
608     
609     // strncmp(x, y)  -> cnst  (if both x and y are constant strings)
610     if (HasStr1 && HasStr2)
611       return ConstantInt::get(CI->getType(),
612                               strncmp(Str1.c_str(), Str2.c_str(), Length));
613     return 0;
614   }
615 };
616
617
618 //===---------------------------------------===//
619 // 'strcpy' Optimizations
620
621 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
622   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
623     // Verify the "strcpy" function prototype.
624     const FunctionType *FT = Callee->getFunctionType();
625     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
626         FT->getParamType(0) != FT->getParamType(1) ||
627         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
628       return 0;
629     
630     Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
631     if (Dst == Src)      // strcpy(x,x)  -> x
632       return Src;
633     
634     // See if we can get the length of the input string.
635     uint64_t Len = GetStringLength(Src);
636     if (Len == 0) return 0;
637     
638     // We have enough information to now generate the memcpy call to do the
639     // concatenation for us.  Make a memcpy to copy the nul byte with align = 1.
640     EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
641     return Dst;
642   }
643 };
644
645
646
647 //===---------------------------------------===//
648 // 'strlen' Optimizations
649
650 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
651   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
652     const FunctionType *FT = Callee->getFunctionType();
653     if (FT->getNumParams() != 1 ||
654         FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
655         !isa<IntegerType>(FT->getReturnType()))
656       return 0;
657     
658     Value *Src = CI->getOperand(1);
659
660     // Constant folding: strlen("xyz") -> 3
661     if (uint64_t Len = GetStringLength(Src))
662       return ConstantInt::get(CI->getType(), Len-1);
663
664     // Handle strlen(p) != 0.
665     if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
666
667     // strlen(x) != 0 --> *x != 0
668     // strlen(x) == 0 --> *x == 0
669     return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
670   }
671 };
672
673 //===---------------------------------------===//
674 // 'memcmp' Optimizations
675
676 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
677   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
678     const FunctionType *FT = Callee->getFunctionType();
679     if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
680         !isa<PointerType>(FT->getParamType(1)) ||
681         FT->getReturnType() != Type::Int32Ty)
682       return 0;
683
684     Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
685
686     if (LHS == RHS)  // memcmp(s,s,x) -> 0
687       return Constant::getNullValue(CI->getType());
688
689     // Make sure we have a constant length.
690     ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
691     if (!LenC) return 0;
692     uint64_t Len = LenC->getZExtValue();
693
694     if (Len == 0) // memcmp(s1,s2,0) -> 0
695       return Constant::getNullValue(CI->getType());
696
697     if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
698       Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
699       Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
700       return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
701     }
702
703     // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS)  != 0
704     // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS)  != 0
705     if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
706       const Type *PTy = PointerType::getUnqual(Len == 2 ?
707                                                Type::Int16Ty : Type::Int32Ty);
708       LHS = B.CreateBitCast(LHS, PTy, "tmp");
709       RHS = B.CreateBitCast(RHS, PTy, "tmp");
710       LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
711       LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
712       LHSV->setAlignment(1); RHSV->setAlignment(1);  // Unaligned loads.
713       return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
714     }
715
716     return 0;
717   }
718 };
719
720 //===---------------------------------------===//
721 // 'memcpy' Optimizations
722
723 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
724   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
725     const FunctionType *FT = Callee->getFunctionType();
726     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
727         !isa<PointerType>(FT->getParamType(0)) ||
728         !isa<PointerType>(FT->getParamType(1)) ||
729         FT->getParamType(2) != TD->getIntPtrType())
730       return 0;
731
732     // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
733     EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
734     return CI->getOperand(1);
735   }
736 };
737
738 //===---------------------------------------===//
739 // 'memmove' Optimizations
740
741 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
742   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
743     const FunctionType *FT = Callee->getFunctionType();
744     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
745         !isa<PointerType>(FT->getParamType(0)) ||
746         !isa<PointerType>(FT->getParamType(1)) ||
747         FT->getParamType(2) != TD->getIntPtrType())
748       return 0;
749
750     // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
751     Module *M = Caller->getParent();
752     Intrinsic::ID IID = Intrinsic::memmove;
753     const Type *Tys[1];
754     Tys[0] = TD->getIntPtrType();
755     Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
756     Value *Dst = CastToCStr(CI->getOperand(1), B);
757     Value *Src = CastToCStr(CI->getOperand(2), B);
758     Value *Size = CI->getOperand(3);
759     Value *Align = ConstantInt::get(Type::Int32Ty, 1);
760     B.CreateCall4(MemMove, Dst, Src, Size, Align);
761     return CI->getOperand(1);
762   }
763 };
764
765 //===---------------------------------------===//
766 // 'memset' Optimizations
767
768 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
769   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
770     const FunctionType *FT = Callee->getFunctionType();
771     if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
772         !isa<PointerType>(FT->getParamType(0)) ||
773         FT->getParamType(1) != TD->getIntPtrType() ||
774         FT->getParamType(2) != TD->getIntPtrType())
775       return 0;
776
777     // memset(p, v, n) -> llvm.memset(p, v, n, 1)
778     Module *M = Caller->getParent();
779     Intrinsic::ID IID = Intrinsic::memset;
780     const Type *Tys[1];
781     Tys[0] = TD->getIntPtrType();
782     Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
783     Value *Dst = CastToCStr(CI->getOperand(1), B);
784     Value *Val = B.CreateTrunc(CI->getOperand(2), Type::Int8Ty);
785     Value *Size = CI->getOperand(3);
786     Value *Align = ConstantInt::get(Type::Int32Ty, 1);
787     B.CreateCall4(MemSet, Dst, Val, Size, Align);
788     return CI->getOperand(1);
789   }
790 };
791
792 //===----------------------------------------------------------------------===//
793 // Math Library Optimizations
794 //===----------------------------------------------------------------------===//
795
796 //===---------------------------------------===//
797 // 'pow*' Optimizations
798
799 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
800   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
801     const FunctionType *FT = Callee->getFunctionType();
802     // Just make sure this has 2 arguments of the same FP type, which match the
803     // result type.
804     if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
805         FT->getParamType(0) != FT->getParamType(1) ||
806         !FT->getParamType(0)->isFloatingPoint())
807       return 0;
808     
809     Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
810     if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
811       if (Op1C->isExactlyValue(1.0))  // pow(1.0, x) -> 1.0
812         return Op1C;
813       if (Op1C->isExactlyValue(2.0))  // pow(2.0, x) -> exp2(x)
814         return EmitUnaryFloatFnCall(Op2, "exp2", B);
815     }
816     
817     ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
818     if (Op2C == 0) return 0;
819     
820     if (Op2C->getValueAPF().isZero())  // pow(x, 0.0) -> 1.0
821       return ConstantFP::get(CI->getType(), 1.0);
822     
823     if (Op2C->isExactlyValue(0.5)) {
824       // FIXME: This is not safe for -0.0 and -inf.  This can only be done when
825       // 'unsafe' math optimizations are allowed.
826       // x    pow(x, 0.5)  sqrt(x)
827       // ---------------------------------------------
828       // -0.0    +0.0       -0.0
829       // -inf    +inf       NaN
830 #if 0
831       // pow(x, 0.5) -> sqrt(x)
832       return B.CreateCall(get_sqrt(), Op1, "sqrt");
833 #endif
834     }
835     
836     if (Op2C->isExactlyValue(1.0))  // pow(x, 1.0) -> x
837       return Op1;
838     if (Op2C->isExactlyValue(2.0))  // pow(x, 2.0) -> x*x
839       return B.CreateMul(Op1, Op1, "pow2");
840     if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
841       return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
842     return 0;
843   }
844 };
845
846 //===---------------------------------------===//
847 // 'exp2' Optimizations
848
849 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
850   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
851     const FunctionType *FT = Callee->getFunctionType();
852     // Just make sure this has 1 argument of FP type, which matches the
853     // result type.
854     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
855         !FT->getParamType(0)->isFloatingPoint())
856       return 0;
857     
858     Value *Op = CI->getOperand(1);
859     // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x))  if sizeof(x) <= 32
860     // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x))  if sizeof(x) < 32
861     Value *LdExpArg = 0;
862     if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
863       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
864         LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
865     } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
866       if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
867         LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
868     }
869     
870     if (LdExpArg) {
871       const char *Name;
872       if (Op->getType() == Type::FloatTy)
873         Name = "ldexpf";
874       else if (Op->getType() == Type::DoubleTy)
875         Name = "ldexp";
876       else
877         Name = "ldexpl";
878
879       Constant *One = ConstantFP::get(APFloat(1.0f));
880       if (Op->getType() != Type::FloatTy)
881         One = ConstantExpr::getFPExtend(One, Op->getType());
882
883       Module *M = Caller->getParent();
884       Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
885                                              Op->getType(), Type::Int32Ty,NULL);
886       return B.CreateCall2(Callee, One, LdExpArg);
887     }
888     return 0;
889   }
890 };
891     
892
893 //===---------------------------------------===//
894 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
895
896 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
897   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
898     const FunctionType *FT = Callee->getFunctionType();
899     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
900         FT->getParamType(0) != Type::DoubleTy)
901       return 0;
902     
903     // If this is something like 'floor((double)floatval)', convert to floorf.
904     FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
905     if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
906       return 0;
907
908     // floor((double)floatval) -> (double)floorf(floatval)
909     Value *V = Cast->getOperand(0);
910     V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
911     return B.CreateFPExt(V, Type::DoubleTy);
912   }
913 };
914
915 //===----------------------------------------------------------------------===//
916 // Integer Optimizations
917 //===----------------------------------------------------------------------===//
918
919 //===---------------------------------------===//
920 // 'ffs*' Optimizations
921
922 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
923   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
924     const FunctionType *FT = Callee->getFunctionType();
925     // Just make sure this has 2 arguments of the same FP type, which match the
926     // result type.
927     if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
928         !isa<IntegerType>(FT->getParamType(0)))
929       return 0;
930     
931     Value *Op = CI->getOperand(1);
932     
933     // Constant fold.
934     if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
935       if (CI->getValue() == 0)  // ffs(0) -> 0.
936         return Constant::getNullValue(CI->getType());
937       return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
938                               CI->getValue().countTrailingZeros()+1);
939     }
940     
941     // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
942     const Type *ArgType = Op->getType();
943     Value *F = Intrinsic::getDeclaration(Callee->getParent(),
944                                          Intrinsic::cttz, &ArgType, 1);
945     Value *V = B.CreateCall(F, Op, "cttz");
946     V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
947     V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
948     
949     Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
950     return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
951   }
952 };
953
954 //===---------------------------------------===//
955 // 'isdigit' Optimizations
956
957 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
958   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
959     const FunctionType *FT = Callee->getFunctionType();
960     // We require integer(i32)
961     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
962         FT->getParamType(0) != Type::Int32Ty)
963       return 0;
964     
965     // isdigit(c) -> (c-'0') <u 10
966     Value *Op = CI->getOperand(1);
967     Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
968     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
969     return B.CreateZExt(Op, CI->getType());
970   }
971 };
972
973 //===---------------------------------------===//
974 // 'isascii' Optimizations
975
976 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
977   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
978     const FunctionType *FT = Callee->getFunctionType();
979     // We require integer(i32)
980     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
981         FT->getParamType(0) != Type::Int32Ty)
982       return 0;
983     
984     // isascii(c) -> c <u 128
985     Value *Op = CI->getOperand(1);
986     Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
987     return B.CreateZExt(Op, CI->getType());
988   }
989 };
990   
991 //===---------------------------------------===//
992 // 'abs', 'labs', 'llabs' Optimizations
993
994 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
995   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
996     const FunctionType *FT = Callee->getFunctionType();
997     // We require integer(integer) where the types agree.
998     if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
999         FT->getParamType(0) != FT->getReturnType())
1000       return 0;
1001     
1002     // abs(x) -> x >s -1 ? x : -x
1003     Value *Op = CI->getOperand(1);
1004     Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
1005                                  "ispos");
1006     Value *Neg = B.CreateNeg(Op, "neg");
1007     return B.CreateSelect(Pos, Op, Neg);
1008   }
1009 };
1010   
1011
1012 //===---------------------------------------===//
1013 // 'toascii' Optimizations
1014
1015 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
1016   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1017     const FunctionType *FT = Callee->getFunctionType();
1018     // We require i32(i32)
1019     if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1020         FT->getParamType(0) != Type::Int32Ty)
1021       return 0;
1022     
1023     // isascii(c) -> c & 0x7f
1024     return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
1025   }
1026 };
1027
1028 //===----------------------------------------------------------------------===//
1029 // Formatting and IO Optimizations
1030 //===----------------------------------------------------------------------===//
1031
1032 //===---------------------------------------===//
1033 // 'printf' Optimizations
1034
1035 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1036   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1037     // Require one fixed pointer argument and an integer/void result.
1038     const FunctionType *FT = Callee->getFunctionType();
1039     if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1040         !(isa<IntegerType>(FT->getReturnType()) ||
1041           FT->getReturnType() == Type::VoidTy))
1042       return 0;
1043     
1044     // Check for a fixed format string.
1045     std::string FormatStr;
1046     if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1047       return 0;
1048
1049     // Empty format string -> noop.
1050     if (FormatStr.empty())  // Tolerate printf's declared void.
1051       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
1052     
1053     // printf("x") -> putchar('x'), even for '%'.
1054     if (FormatStr.size() == 1) {
1055       EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1056       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1057     }
1058     
1059     // printf("foo\n") --> puts("foo")
1060     if (FormatStr[FormatStr.size()-1] == '\n' &&
1061         FormatStr.find('%') == std::string::npos) {  // no format characters.
1062       // Create a string literal with no \n on it.  We expect the constant merge
1063       // pass to be run after this pass, to merge duplicate strings.
1064       FormatStr.erase(FormatStr.end()-1);
1065       Constant *C = ConstantArray::get(FormatStr, true);
1066       C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
1067                              C, "str", Callee->getParent());
1068       EmitPutS(C, B);
1069       return CI->use_empty() ? (Value*)CI : 
1070                           ConstantInt::get(CI->getType(), FormatStr.size()+1);
1071     }
1072     
1073     // Optimize specific format strings.
1074     // printf("%c", chr) --> putchar(*(i8*)dst)
1075     if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1076         isa<IntegerType>(CI->getOperand(2)->getType())) {
1077       EmitPutChar(CI->getOperand(2), B);
1078       return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1079     }
1080     
1081     // printf("%s\n", str) --> puts(str)
1082     if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1083         isa<PointerType>(CI->getOperand(2)->getType()) &&
1084         CI->use_empty()) {
1085       EmitPutS(CI->getOperand(2), B);
1086       return CI;
1087     }
1088     return 0;
1089   }
1090 };
1091
1092 //===---------------------------------------===//
1093 // 'sprintf' Optimizations
1094
1095 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1096   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1097     // Require two fixed pointer arguments and an integer result.
1098     const FunctionType *FT = Callee->getFunctionType();
1099     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1100         !isa<PointerType>(FT->getParamType(1)) ||
1101         !isa<IntegerType>(FT->getReturnType()))
1102       return 0;
1103
1104     // Check for a fixed format string.
1105     std::string FormatStr;
1106     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1107       return 0;
1108     
1109     // If we just have a format string (nothing else crazy) transform it.
1110     if (CI->getNumOperands() == 3) {
1111       // Make sure there's no % in the constant array.  We could try to handle
1112       // %% -> % in the future if we cared.
1113       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1114         if (FormatStr[i] == '%')
1115           return 0; // we found a format specifier, bail out.
1116       
1117       // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1118       EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1119                  ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1120       return ConstantInt::get(CI->getType(), FormatStr.size());
1121     }
1122     
1123     // The remaining optimizations require the format string to be "%s" or "%c"
1124     // and have an extra operand.
1125     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1126       return 0;
1127     
1128     // Decode the second character of the format string.
1129     if (FormatStr[1] == 'c') {
1130       // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1131       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1132       Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1133       Value *Ptr = CastToCStr(CI->getOperand(1), B);
1134       B.CreateStore(V, Ptr);
1135       Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1136       B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1137       
1138       return ConstantInt::get(CI->getType(), 1);
1139     }
1140     
1141     if (FormatStr[1] == 's') {
1142       // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1143       if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1144
1145       Value *Len = EmitStrLen(CI->getOperand(3), B);
1146       Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1147                                   "leninc");
1148       EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1149       
1150       // The sprintf result is the unincremented number of bytes in the string.
1151       return B.CreateIntCast(Len, CI->getType(), false);
1152     }
1153     return 0;
1154   }
1155 };
1156
1157 //===---------------------------------------===//
1158 // 'fwrite' Optimizations
1159
1160 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1161   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1162     // Require a pointer, an integer, an integer, a pointer, returning integer.
1163     const FunctionType *FT = Callee->getFunctionType();
1164     if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1165         !isa<IntegerType>(FT->getParamType(1)) ||
1166         !isa<IntegerType>(FT->getParamType(2)) ||
1167         !isa<PointerType>(FT->getParamType(3)) ||
1168         !isa<IntegerType>(FT->getReturnType()))
1169       return 0;
1170     
1171     // Get the element size and count.
1172     ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1173     ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1174     if (!SizeC || !CountC) return 0;
1175     uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1176     
1177     // If this is writing zero records, remove the call (it's a noop).
1178     if (Bytes == 0)
1179       return ConstantInt::get(CI->getType(), 0);
1180     
1181     // If this is writing one byte, turn it into fputc.
1182     if (Bytes == 1) {  // fwrite(S,1,1,F) -> fputc(S[0],F)
1183       Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1184       EmitFPutC(Char, CI->getOperand(4), B);
1185       return ConstantInt::get(CI->getType(), 1);
1186     }
1187
1188     return 0;
1189   }
1190 };
1191
1192 //===---------------------------------------===//
1193 // 'fputs' Optimizations
1194
1195 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1196   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1197     // Require two pointers.  Also, we can't optimize if return value is used.
1198     const FunctionType *FT = Callee->getFunctionType();
1199     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1200         !isa<PointerType>(FT->getParamType(1)) ||
1201         !CI->use_empty())
1202       return 0;
1203     
1204     // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1205     uint64_t Len = GetStringLength(CI->getOperand(1));
1206     if (!Len) return 0;
1207     EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1208                CI->getOperand(2), B);
1209     return CI;  // Known to have no uses (see above).
1210   }
1211 };
1212
1213 //===---------------------------------------===//
1214 // 'fprintf' Optimizations
1215
1216 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1217   virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1218     // Require two fixed paramters as pointers and integer result.
1219     const FunctionType *FT = Callee->getFunctionType();
1220     if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1221         !isa<PointerType>(FT->getParamType(1)) ||
1222         !isa<IntegerType>(FT->getReturnType()))
1223       return 0;
1224     
1225     // All the optimizations depend on the format string.
1226     std::string FormatStr;
1227     if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1228       return 0;
1229
1230     // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1231     if (CI->getNumOperands() == 3) {
1232       for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1233         if (FormatStr[i] == '%')  // Could handle %% -> % if we cared.
1234           return 0; // We found a format specifier.
1235       
1236       EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1237                                                      FormatStr.size()),
1238                  CI->getOperand(1), B);
1239       return ConstantInt::get(CI->getType(), FormatStr.size());
1240     }
1241     
1242     // The remaining optimizations require the format string to be "%s" or "%c"
1243     // and have an extra operand.
1244     if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1245       return 0;
1246     
1247     // Decode the second character of the format string.
1248     if (FormatStr[1] == 'c') {
1249       // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1250       if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1251       EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1252       return ConstantInt::get(CI->getType(), 1);
1253     }
1254     
1255     if (FormatStr[1] == 's') {
1256       // fprintf(F, "%s", str) -> fputs(str, F)
1257       if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1258         return 0;
1259       EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1260       return CI;
1261     }
1262     return 0;
1263   }
1264 };
1265
1266 } // end anonymous namespace.
1267
1268 //===----------------------------------------------------------------------===//
1269 // SimplifyLibCalls Pass Implementation
1270 //===----------------------------------------------------------------------===//
1271
1272 namespace {
1273   /// This pass optimizes well known library functions from libc and libm.
1274   ///
1275   class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1276     StringMap<LibCallOptimization*> Optimizations;
1277     // Miscellaneous LibCall Optimizations
1278     ExitOpt Exit; 
1279     // String and Memory LibCall Optimizations
1280     StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1281     StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt  MemCpy;
1282     MemMoveOpt MemMove; MemSetOpt MemSet;
1283     // Math Library Optimizations
1284     PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1285     // Integer Optimizations
1286     FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1287     ToAsciiOpt ToAscii;
1288     // Formatting and IO Optimizations
1289     SPrintFOpt SPrintF; PrintFOpt PrintF;
1290     FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1291   public:
1292     static char ID; // Pass identification
1293     SimplifyLibCalls() : FunctionPass(&ID) {}
1294
1295     void InitOptimizations();
1296     bool runOnFunction(Function &F);
1297
1298     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1299       AU.addRequired<TargetData>();
1300     }
1301   };
1302   char SimplifyLibCalls::ID = 0;
1303 } // end anonymous namespace.
1304
1305 static RegisterPass<SimplifyLibCalls>
1306 X("simplify-libcalls", "Simplify well-known library calls");
1307
1308 // Public interface to the Simplify LibCalls pass.
1309 FunctionPass *llvm::createSimplifyLibCallsPass() {
1310   return new SimplifyLibCalls(); 
1311 }
1312
1313 /// Optimizations - Populate the Optimizations map with all the optimizations
1314 /// we know.
1315 void SimplifyLibCalls::InitOptimizations() {
1316   // Miscellaneous LibCall Optimizations
1317   Optimizations["exit"] = &Exit;
1318   
1319   // String and Memory LibCall Optimizations
1320   Optimizations["strcat"] = &StrCat;
1321   Optimizations["strchr"] = &StrChr;
1322   Optimizations["strcmp"] = &StrCmp;
1323   Optimizations["strncmp"] = &StrNCmp;
1324   Optimizations["strcpy"] = &StrCpy;
1325   Optimizations["strlen"] = &StrLen;
1326   Optimizations["memcmp"] = &MemCmp;
1327   Optimizations["memcpy"] = &MemCpy;
1328   Optimizations["memmove"] = &MemMove;
1329   Optimizations["memset"] = &MemSet;
1330   
1331   // Math Library Optimizations
1332   Optimizations["powf"] = &Pow;
1333   Optimizations["pow"] = &Pow;
1334   Optimizations["powl"] = &Pow;
1335   Optimizations["llvm.pow.f32"] = &Pow;
1336   Optimizations["llvm.pow.f64"] = &Pow;
1337   Optimizations["llvm.pow.f80"] = &Pow;
1338   Optimizations["llvm.pow.f128"] = &Pow;
1339   Optimizations["llvm.pow.ppcf128"] = &Pow;
1340   Optimizations["exp2l"] = &Exp2;
1341   Optimizations["exp2"] = &Exp2;
1342   Optimizations["exp2f"] = &Exp2;
1343   Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1344   Optimizations["llvm.exp2.f128"] = &Exp2;
1345   Optimizations["llvm.exp2.f80"] = &Exp2;
1346   Optimizations["llvm.exp2.f64"] = &Exp2;
1347   Optimizations["llvm.exp2.f32"] = &Exp2;
1348   
1349 #ifdef HAVE_FLOORF
1350   Optimizations["floor"] = &UnaryDoubleFP;
1351 #endif
1352 #ifdef HAVE_CEILF
1353   Optimizations["ceil"] = &UnaryDoubleFP;
1354 #endif
1355 #ifdef HAVE_ROUNDF
1356   Optimizations["round"] = &UnaryDoubleFP;
1357 #endif
1358 #ifdef HAVE_RINTF
1359   Optimizations["rint"] = &UnaryDoubleFP;
1360 #endif
1361 #ifdef HAVE_NEARBYINTF
1362   Optimizations["nearbyint"] = &UnaryDoubleFP;
1363 #endif
1364   
1365   // Integer Optimizations
1366   Optimizations["ffs"] = &FFS;
1367   Optimizations["ffsl"] = &FFS;
1368   Optimizations["ffsll"] = &FFS;
1369   Optimizations["abs"] = &Abs;
1370   Optimizations["labs"] = &Abs;
1371   Optimizations["llabs"] = &Abs;
1372   Optimizations["isdigit"] = &IsDigit;
1373   Optimizations["isascii"] = &IsAscii;
1374   Optimizations["toascii"] = &ToAscii;
1375   
1376   // Formatting and IO Optimizations
1377   Optimizations["sprintf"] = &SPrintF;
1378   Optimizations["printf"] = &PrintF;
1379   Optimizations["fwrite"] = &FWrite;
1380   Optimizations["fputs"] = &FPuts;
1381   Optimizations["fprintf"] = &FPrintF;
1382 }
1383
1384
1385 /// runOnFunction - Top level algorithm.
1386 ///
1387 bool SimplifyLibCalls::runOnFunction(Function &F) {
1388   if (Optimizations.empty())
1389     InitOptimizations();
1390   
1391   const TargetData &TD = getAnalysis<TargetData>();
1392   
1393   IRBuilder<> Builder;
1394
1395   bool Changed = false;
1396   for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1397     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1398       // Ignore non-calls.
1399       CallInst *CI = dyn_cast<CallInst>(I++);
1400       if (!CI) continue;
1401       
1402       // Ignore indirect calls and calls to non-external functions.
1403       Function *Callee = CI->getCalledFunction();
1404       if (Callee == 0 || !Callee->isDeclaration() ||
1405           !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1406         continue;
1407       
1408       // Ignore unknown calls.
1409       const char *CalleeName = Callee->getNameStart();
1410       StringMap<LibCallOptimization*>::iterator OMI =
1411         Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1412       if (OMI == Optimizations.end()) continue;
1413       
1414       // Set the builder to the instruction after the call.
1415       Builder.SetInsertPoint(BB, I);
1416       
1417       // Try to optimize this call.
1418       Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1419       if (Result == 0) continue;
1420
1421       DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1422             DOUT << "  into: " << *Result << "\n");
1423       
1424       // Something changed!
1425       Changed = true;
1426       ++NumSimplified;
1427       
1428       // Inspect the instruction after the call (which was potentially just
1429       // added) next.
1430       I = CI; ++I;
1431       
1432       if (CI != Result && !CI->use_empty()) {
1433         CI->replaceAllUsesWith(Result);
1434         if (!Result->hasName())
1435           Result->takeName(CI);
1436       }
1437       CI->eraseFromParent();
1438     }
1439   }
1440   return Changed;
1441 }
1442
1443
1444 // TODO:
1445 //   Additional cases that we need to add to this file:
1446 //
1447 // cbrt:
1448 //   * cbrt(expN(X))  -> expN(x/3)
1449 //   * cbrt(sqrt(x))  -> pow(x,1/6)
1450 //   * cbrt(sqrt(x))  -> pow(x,1/9)
1451 //
1452 // cos, cosf, cosl:
1453 //   * cos(-x)  -> cos(x)
1454 //
1455 // exp, expf, expl:
1456 //   * exp(log(x))  -> x
1457 //
1458 // log, logf, logl:
1459 //   * log(exp(x))   -> x
1460 //   * log(x**y)     -> y*log(x)
1461 //   * log(exp(y))   -> y*log(e)
1462 //   * log(exp2(y))  -> y*log(2)
1463 //   * log(exp10(y)) -> y*log(10)
1464 //   * log(sqrt(x))  -> 0.5*log(x)
1465 //   * log(pow(x,y)) -> y*log(x)
1466 //
1467 // lround, lroundf, lroundl:
1468 //   * lround(cnst) -> cnst'
1469 //
1470 // memcmp:
1471 //   * memcmp(x,y,l)   -> cnst
1472 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1473 //
1474 // pow, powf, powl:
1475 //   * pow(exp(x),y)  -> exp(x*y)
1476 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1477 //   * pow(pow(x,y),z)-> pow(x,y*z)
1478 //
1479 // puts:
1480 //   * puts("") -> putchar("\n")
1481 //
1482 // round, roundf, roundl:
1483 //   * round(cnst) -> cnst'
1484 //
1485 // signbit:
1486 //   * signbit(cnst) -> cnst'
1487 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1488 //
1489 // sqrt, sqrtf, sqrtl:
1490 //   * sqrt(expN(x))  -> expN(x*0.5)
1491 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1492 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1493 //
1494 // stpcpy:
1495 //   * stpcpy(str, "literal") ->
1496 //           llvm.memcpy(str,"literal",strlen("literal")+1,1)
1497 // strrchr:
1498 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
1499 //      (if c is a constant integer and s is a constant string)
1500 //   * strrchr(s1,0) -> strchr(s1,0)
1501 //
1502 // strncat:
1503 //   * strncat(x,y,0) -> x
1504 //   * strncat(x,y,0) -> x (if strlen(y) = 0)
1505 //   * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1506 //
1507 // strncpy:
1508 //   * strncpy(d,s,0) -> d
1509 //   * strncpy(d,s,l) -> memcpy(d,s,l,1)
1510 //      (if s and l are constants)
1511 //
1512 // strpbrk:
1513 //   * strpbrk(s,a) -> offset_in_for(s,a)
1514 //      (if s and a are both constant strings)
1515 //   * strpbrk(s,"") -> 0
1516 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1517 //
1518 // strspn, strcspn:
1519 //   * strspn(s,a)   -> const_int (if both args are constant)
1520 //   * strspn("",a)  -> 0
1521 //   * strspn(s,"")  -> 0
1522 //   * strcspn(s,a)  -> const_int (if both args are constant)
1523 //   * strcspn("",a) -> 0
1524 //   * strcspn(s,"") -> strlen(a)
1525 //
1526 // strstr:
1527 //   * strstr(x,x)  -> x
1528 //   * strstr(s1,s2) -> offset_of_s2_in(s1)
1529 //       (if s1 and s2 are constant strings)
1530 //
1531 // tan, tanf, tanl:
1532 //   * tan(atan(x)) -> x
1533 //
1534 // trunc, truncf, truncl:
1535 //   * trunc(cnst) -> cnst'
1536 //
1537 //