Implement optimizations for the strchr and llvm.memset library calls.
[oota-llvm.git] / lib / Transforms / IPO / SimplifyLibCalls.cpp
1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Reid Spencer and is distributed under the 
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements a variety of small optimizations for calls to specific
11 // well-known (e.g. runtime library) function calls. For example, a call to the
12 // function "exit(3)" that occurs within the main() function can be transformed
13 // into a simple "return 3" instruction. Any optimization that takes this form
14 // (replace call to library function with simpler code that provides same 
15 // result) belongs in this file. 
16 //
17 //===----------------------------------------------------------------------===//
18
19 #define DEBUG_TYPE "simplify-libcalls"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/ADT/hash_map"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
30 #include <iostream>
31 using namespace llvm;
32
33 namespace {
34
35 /// This statistic keeps track of the total number of library calls that have
36 /// been simplified regardless of which call it is.
37 Statistic<> SimplifiedLibCalls("simplify-libcalls", 
38   "Number of well-known library calls simplified");
39
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
43
44 /// @brief The list of optimizations deriving from LibCallOptimization
45 hash_map<std::string,LibCallOptimization*> optlist;
46
47 /// This class is the abstract base class for the set of optimizations that
48 /// corresponds to one library call. The SimplifyLibCalls pass will call the
49 /// ValidateCalledFunction method to ask the optimization if a given Function
50 /// is the kind that the optimization can handle. If the subclass returns true,
51 /// then SImplifyLibCalls will also call the OptimizeCall method to perform, 
52 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
53 /// OptimizeCall won't be called. Subclasses are responsible for providing the
54 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
55 /// constructor. This is used to efficiently select which call instructions to
56 /// optimize. The criteria for a "lib call" is "anything with well known 
57 /// semantics", typically a library function that is defined by an international
58 /// standard. Because the semantics are well known, the optimizations can 
59 /// generally short-circuit actually calling the function if there's a simpler
60 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
61 /// @brief Base class for library call optimizations
62 class LibCallOptimization
63 {
64 public:
65   /// The \p fname argument must be the name of the library function being 
66   /// optimized by the subclass.
67   /// @brief Constructor that registers the optimization.
68   LibCallOptimization(const char* fname, 
69                       const char* stat_name, const char* description )
70     : func_name(fname)
71 #ifndef NDEBUG
72     , occurrences(stat_name,description)
73 #endif
74   {
75     // Register this call optimizer in the optlist (a hash_map)
76     optlist[fname] = this;
77   }
78
79   /// @brief Deregister from the optlist
80   virtual ~LibCallOptimization() { optlist.erase(func_name); }
81
82   /// The implementation of this function in subclasses should determine if
83   /// \p F is suitable for the optimization. This method is called by 
84   /// SimplifyLibCalls::runOnModule to short circuit visiting all the call 
85   /// sites of such a function if that function is not suitable in the first 
86   /// place.  If the called function is suitabe, this method should return true;
87   /// false, otherwise. This function should also perform any lazy 
88   /// initialization that the LibCallOptimization needs to do, if its to return 
89   /// true. This avoids doing initialization until the optimizer is actually
90   /// going to be called upon to do some optimization.
91   /// @brief Determine if the function is suitable for optimization
92   virtual bool ValidateCalledFunction(
93     const Function* F,    ///< The function that is the target of call sites
94     SimplifyLibCalls& SLC ///< The pass object invoking us
95   ) = 0;
96
97   /// The implementations of this function in subclasses is the heart of the 
98   /// SimplifyLibCalls algorithm. Sublcasses of this class implement 
99   /// OptimizeCall to determine if (a) the conditions are right for optimizing
100   /// the call and (b) to perform the optimization. If an action is taken 
101   /// against ci, the subclass is responsible for returning true and ensuring
102   /// that ci is erased from its parent.
103   /// @brief Optimize a call, if possible.
104   virtual bool OptimizeCall(
105     CallInst* ci,          ///< The call instruction that should be optimized.
106     SimplifyLibCalls& SLC  ///< The pass object invoking us
107   ) = 0;
108
109   /// @brief Get the name of the library call being optimized
110   const char * getFunctionName() const { return func_name; }
111
112 #ifndef NDEBUG
113   /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
114   void succeeded() { ++occurrences; }
115 #endif
116
117 private:
118   const char* func_name; ///< Name of the library call we optimize
119 #ifndef NDEBUG
120   Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
121 #endif
122 };
123
124 /// This class is an LLVM Pass that applies each of the LibCallOptimization 
125 /// instances to all the call sites in a module, relatively efficiently. The
126 /// purpose of this pass is to provide optimizations for calls to well-known 
127 /// functions with well-known semantics, such as those in the c library. The
128 /// class provides the basic infrastructure for handling runOnModule.  Whenever /// this pass finds a function call, it asks the appropriate optimizer to 
129 /// validate the call (ValidateLibraryCall). If it is validated, then
130 /// the OptimizeCall method is also called.
131 /// @brief A ModulePass for optimizing well-known function calls.
132 class SimplifyLibCalls : public ModulePass 
133 {
134 public:
135   /// We need some target data for accurate signature details that are
136   /// target dependent. So we require target data in our AnalysisUsage.
137   /// @brief Require TargetData from AnalysisUsage.
138   virtual void getAnalysisUsage(AnalysisUsage& Info) const
139   {
140     // Ask that the TargetData analysis be performed before us so we can use
141     // the target data.
142     Info.addRequired<TargetData>();
143   }
144
145   /// For this pass, process all of the function calls in the module, calling
146   /// ValidateLibraryCall and OptimizeCall as appropriate.
147   /// @brief Run all the lib call optimizations on a Module.
148   virtual bool runOnModule(Module &M)
149   {
150     reset(M);
151
152     bool result = false;
153
154     // The call optimizations can be recursive. That is, the optimization might
155     // generate a call to another function which can also be optimized. This way
156     // we make the LibCallOptimization instances very specific to the case they 
157     // handle. It also means we need to keep running over the function calls in 
158     // the module until we don't get any more optimizations possible.
159     bool found_optimization = false;
160     do
161     {
162       found_optimization = false;
163       for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
164       {
165         // All the "well-known" functions are external and have external linkage
166         // because they live in a runtime library somewhere and were (probably) 
167         // not compiled by LLVM.  So, we only act on external functions that 
168         // have external linkage and non-empty uses.
169         if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
170           continue;
171
172         // Get the optimization class that pertains to this function
173         LibCallOptimization* CO = optlist[FI->getName().c_str()];
174         if (!CO)
175           continue;
176
177         // Make sure the called function is suitable for the optimization
178         if (!CO->ValidateCalledFunction(FI,*this))
179           continue;
180
181         // Loop over each of the uses of the function
182         for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end(); 
183              UI != UE ; )
184         {
185           // If the use of the function is a call instruction
186           if (CallInst* CI = dyn_cast<CallInst>(*UI++))
187           {
188             // Do the optimization on the LibCallOptimization.
189             if (CO->OptimizeCall(CI,*this))
190             {
191               ++SimplifiedLibCalls;
192               found_optimization = result = true;
193 #ifndef NDEBUG
194               CO->succeeded();
195 #endif
196             }
197           }
198         }
199       }
200     } while (found_optimization);
201     return result;
202   }
203
204   /// @brief Return the *current* module we're working on.
205   Module* getModule() const { return M; }
206
207   /// @brief Return the *current* target data for the module we're working on.
208   TargetData* getTargetData() const { return TD; }
209
210   /// @brief Return the size_t type -- syntactic shortcut
211   const Type* getIntPtrType() const { return TD->getIntPtrType(); }
212
213   /// @brief Return a Function* for the fputc libcall
214   Function* get_fputc(const Type* FILEptr_type)
215   {
216     if (!fputc_func)
217     {
218       std::vector<const Type*> args;
219       args.push_back(Type::IntTy);
220       args.push_back(FILEptr_type);
221       FunctionType* fputc_type = 
222         FunctionType::get(Type::IntTy, args, false);
223       fputc_func = M->getOrInsertFunction("fputc",fputc_type);
224     }
225     return fputc_func;
226   }
227
228   /// @brief Return a Function* for the fwrite libcall
229   Function* get_fwrite(const Type* FILEptr_type)
230   {
231     if (!fwrite_func)
232     {
233       std::vector<const Type*> args;
234       args.push_back(PointerType::get(Type::SByteTy));
235       args.push_back(TD->getIntPtrType());
236       args.push_back(TD->getIntPtrType());
237       args.push_back(FILEptr_type);
238       FunctionType* fwrite_type = 
239         FunctionType::get(TD->getIntPtrType(), args, false);
240       fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
241     }
242     return fwrite_func;
243   }
244
245   /// @brief Return a Function* for the sqrt libcall
246   Function* get_sqrt()
247   {
248     if (!sqrt_func)
249     {
250       std::vector<const Type*> args;
251       args.push_back(Type::DoubleTy);
252       FunctionType* sqrt_type = 
253         FunctionType::get(Type::DoubleTy, args, false);
254       sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
255     }
256     return sqrt_func;
257   }
258
259   /// @brief Return a Function* for the strlen libcall
260   Function* get_strlen()
261   {
262     if (!strlen_func)
263     {
264       std::vector<const Type*> args;
265       args.push_back(PointerType::get(Type::SByteTy));
266       FunctionType* strlen_type = 
267         FunctionType::get(TD->getIntPtrType(), args, false);
268       strlen_func = M->getOrInsertFunction("strlen",strlen_type);
269     }
270     return strlen_func;
271   }
272
273   /// @brief Return a Function* for the memchr libcall
274   Function* get_memchr()
275   {
276     if (!memchr_func)
277     {
278       std::vector<const Type*> args;
279       args.push_back(PointerType::get(Type::SByteTy));
280       args.push_back(Type::IntTy);
281       args.push_back(TD->getIntPtrType());
282       FunctionType* memchr_type = FunctionType::get(
283           PointerType::get(Type::SByteTy), args, false);
284       memchr_func = M->getOrInsertFunction("memchr",memchr_type);
285     }
286     return memchr_func;
287   }
288
289   /// @brief Return a Function* for the memcpy libcall
290   Function* get_memcpy()
291   {
292     if (!memcpy_func)
293     {
294       // Note: this is for llvm.memcpy intrinsic
295       std::vector<const Type*> args;
296       args.push_back(PointerType::get(Type::SByteTy));
297       args.push_back(PointerType::get(Type::SByteTy));
298       args.push_back(Type::IntTy);
299       args.push_back(Type::IntTy);
300       FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
301       memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
302     }
303     return memcpy_func;
304   }
305
306 private:
307   /// @brief Reset our cached data for a new Module
308   void reset(Module& mod)
309   {
310     M = &mod;
311     TD = &getAnalysis<TargetData>();
312     fputc_func = 0;
313     fwrite_func = 0;
314     memcpy_func = 0;
315     memchr_func = 0;
316     sqrt_func   = 0;
317     strlen_func = 0;
318   }
319
320 private:
321   Function* fputc_func;  ///< Cached fputc function
322   Function* fwrite_func; ///< Cached fwrite function
323   Function* memcpy_func; ///< Cached llvm.memcpy function
324   Function* memchr_func; ///< Cached memchr function
325   Function* sqrt_func;   ///< Cached sqrt function
326   Function* strlen_func; ///< Cached strlen function
327   Module* M;             ///< Cached Module
328   TargetData* TD;        ///< Cached TargetData
329 };
330
331 // Register the pass
332 RegisterOpt<SimplifyLibCalls> 
333 X("simplify-libcalls","Simplify well-known library calls");
334
335 } // anonymous namespace
336
337 // The only public symbol in this file which just instantiates the pass object
338 ModulePass *llvm::createSimplifyLibCallsPass() 
339
340   return new SimplifyLibCalls(); 
341 }
342
343 // Classes below here, in the anonymous namespace, are all subclasses of the
344 // LibCallOptimization class, each implementing all optimizations possible for a
345 // single well-known library call. Each has a static singleton instance that
346 // auto registers it into the "optlist" global above. 
347 namespace {
348
349 // Forward declare a utility function.
350 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
351
352 /// This LibCallOptimization will find instances of a call to "exit" that occurs
353 /// within the "main" function and change it to a simple "ret" instruction with
354 /// the same value passed to the exit function. When this is done, it splits the
355 /// basic block at the exit(3) call and deletes the call instruction.
356 /// @brief Replace calls to exit in main with a simple return
357 struct ExitInMainOptimization : public LibCallOptimization
358 {
359   ExitInMainOptimization() : LibCallOptimization("exit",
360       "simplify-libcalls:exit","Number of 'exit' calls simplified") {}
361   virtual ~ExitInMainOptimization() {}
362
363   // Make sure the called function looks like exit (int argument, int return
364   // type, external linkage, not varargs). 
365   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
366   {
367     if (f->arg_size() >= 1)
368       if (f->arg_begin()->getType()->isInteger())
369         return true;
370     return false;
371   }
372
373   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
374   {
375     // To be careful, we check that the call to exit is coming from "main", that
376     // main has external linkage, and the return type of main and the argument
377     // to exit have the same type. 
378     Function *from = ci->getParent()->getParent();
379     if (from->hasExternalLinkage())
380       if (from->getReturnType() == ci->getOperand(1)->getType())
381         if (from->getName() == "main")
382         {
383           // Okay, time to actually do the optimization. First, get the basic 
384           // block of the call instruction
385           BasicBlock* bb = ci->getParent();
386
387           // Create a return instruction that we'll replace the call with. 
388           // Note that the argument of the return is the argument of the call 
389           // instruction.
390           ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
391
392           // Split the block at the call instruction which places it in a new
393           // basic block.
394           bb->splitBasicBlock(ci);
395
396           // The block split caused a branch instruction to be inserted into
397           // the end of the original block, right after the return instruction
398           // that we put there. That's not a valid block, so delete the branch
399           // instruction.
400           bb->getInstList().pop_back();
401
402           // Now we can finally get rid of the call instruction which now lives
403           // in the new basic block.
404           ci->eraseFromParent();
405
406           // Optimization succeeded, return true.
407           return true;
408         }
409     // We didn't pass the criteria for this optimization so return false
410     return false;
411   }
412 } ExitInMainOptimizer;
413
414 /// This LibCallOptimization will simplify a call to the strcat library 
415 /// function. The simplification is possible only if the string being 
416 /// concatenated is a constant array or a constant expression that results in 
417 /// a constant string. In this case we can replace it with strlen + llvm.memcpy 
418 /// of the constant string. Both of these calls are further reduced, if possible
419 /// on subsequent passes.
420 /// @brief Simplify the strcat library function.
421 struct StrCatOptimization : public LibCallOptimization
422 {
423 public:
424   /// @brief Default constructor
425   StrCatOptimization() : LibCallOptimization("strcat",
426       "simplify-libcalls:strcat","Number of 'strcat' calls simplified") {}
427
428 public:
429   /// @breif  Destructor
430   virtual ~StrCatOptimization() {}
431
432   /// @brief Make sure that the "strcat" function has the right prototype
433   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
434   {
435     if (f->getReturnType() == PointerType::get(Type::SByteTy))
436       if (f->arg_size() == 2) 
437       {
438         Function::const_arg_iterator AI = f->arg_begin();
439         if (AI++->getType() == PointerType::get(Type::SByteTy))
440           if (AI->getType() == PointerType::get(Type::SByteTy))
441           {
442             // Indicate this is a suitable call type.
443             return true;
444           }
445       }
446     return false;
447   }
448
449   /// @brief Optimize the strcat library function
450   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
451   {
452     // Extract some information from the instruction
453     Module* M = ci->getParent()->getParent()->getParent();
454     Value* dest = ci->getOperand(1);
455     Value* src  = ci->getOperand(2);
456
457     // Extract the initializer (while making numerous checks) from the 
458     // source operand of the call to strcat. If we get null back, one of
459     // a variety of checks in get_GVInitializer failed
460     uint64_t len = 0;
461     if (!getConstantStringLength(src,len))
462       return false;
463
464     // Handle the simple, do-nothing case
465     if (len == 0)
466     {
467       ci->replaceAllUsesWith(dest);
468       ci->eraseFromParent();
469       return true;
470     }
471
472     // Increment the length because we actually want to memcpy the null
473     // terminator as well.
474     len++;
475
476     // We need to find the end of the destination string.  That's where the 
477     // memory is to be moved to. We just generate a call to strlen (further 
478     // optimized in another pass).  Note that the SLC.get_strlen() call 
479     // caches the Function* for us.
480     CallInst* strlen_inst = 
481       new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
482
483     // Now that we have the destination's length, we must index into the 
484     // destination's pointer to get the actual memcpy destination (end of
485     // the string .. we're concatenating).
486     std::vector<Value*> idx;
487     idx.push_back(strlen_inst);
488     GetElementPtrInst* gep = 
489       new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
490
491     // We have enough information to now generate the memcpy call to
492     // do the concatenation for us.
493     std::vector<Value*> vals;
494     vals.push_back(gep); // destination
495     vals.push_back(ci->getOperand(2)); // source
496     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
497     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
498     new CallInst(SLC.get_memcpy(), vals, "", ci);
499
500     // Finally, substitute the first operand of the strcat call for the 
501     // strcat call itself since strcat returns its first operand; and, 
502     // kill the strcat CallInst.
503     ci->replaceAllUsesWith(dest);
504     ci->eraseFromParent();
505     return true;
506   }
507 } StrCatOptimizer;
508
509 /// This LibCallOptimization will simplify a call to the strchr library 
510 /// function.  It optimizes out cases where the arguments are both constant
511 /// and the result can be determined statically.
512 /// @brief Simplify the strcmp library function.
513 struct StrChrOptimization : public LibCallOptimization
514 {
515 public:
516   StrChrOptimization() : LibCallOptimization("strchr",
517       "simplify-libcalls:strchr","Number of 'strchr' calls simplified") {}
518   virtual ~StrChrOptimization() {}
519
520   /// @brief Make sure that the "strchr" function has the right prototype
521   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
522   {
523     if (f->getReturnType() == PointerType::get(Type::SByteTy) && 
524         f->arg_size() == 2)
525       return true;
526     return false;
527   }
528
529   /// @brief Perform the strcpy optimization
530   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
531   {
532     // If there aren't three operands, bail
533     if (ci->getNumOperands() != 3)
534       return false;
535
536     // Check that the first argument to strchr is a constant array of sbyte.
537     // If it is, get the length and data, otherwise return false.
538     uint64_t len = 0;
539     ConstantArray* CA;
540     if (!getConstantStringLength(ci->getOperand(1),len,&CA))
541       return false;
542
543     // Check that the second argument to strchr is a constant int, return false
544     // if it isn't
545     ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
546     if (!CSI)
547     {
548       // Just lower this to memchr since we know the length of the string as
549       // it is constant.
550       Function* f = SLC.get_memchr();
551       std::vector<Value*> args;
552       args.push_back(ci->getOperand(1));
553       args.push_back(ci->getOperand(2));
554       args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
555       ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
556       ci->eraseFromParent();
557       return true;
558     }
559
560     // Get the character we're looking for
561     int64_t chr = CSI->getValue();
562
563     // Compute the offset
564     uint64_t offset = 0;
565     bool char_found = false;
566     for (uint64_t i = 0; i < len; ++i)
567     {
568       if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
569       {
570         // Check for the null terminator
571         if (CI->isNullValue())
572           break; // we found end of string
573         else if (CI->getValue() == chr)
574         {
575           char_found = true;
576           offset = i;
577           break;
578         }
579       }
580     }
581
582     // strchr(s,c)  -> offset_of_in(c,s)
583     //    (if c is a constant integer and s is a constant string)
584     if (char_found)
585     {
586       std::vector<Value*> indices;
587       indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
588       GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
589           ci->getOperand(1)->getName()+".strchr",ci);
590       ci->replaceAllUsesWith(GEP);
591     }
592     else
593       ci->replaceAllUsesWith(
594           ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
595
596     ci->eraseFromParent();
597     return true;
598   }
599 } StrChrOptimizer;
600
601 /// This LibCallOptimization will simplify a call to the strcmp library 
602 /// function.  It optimizes out cases where one or both arguments are constant
603 /// and the result can be determined statically.
604 /// @brief Simplify the strcmp library function.
605 struct StrCmpOptimization : public LibCallOptimization
606 {
607 public:
608   StrCmpOptimization() : LibCallOptimization("strcmp",
609       "simplify-libcalls:strcmp","Number of 'strcmp' calls simplified") {}
610   virtual ~StrCmpOptimization() {}
611
612   /// @brief Make sure that the "strcpy" function has the right prototype
613   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
614   {
615     if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
616       return true;
617     return false;
618   }
619
620   /// @brief Perform the strcpy optimization
621   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
622   {
623     // First, check to see if src and destination are the same. If they are,
624     // then the optimization is to replace the CallInst with a constant 0
625     // because the call is a no-op. 
626     Value* s1 = ci->getOperand(1);
627     Value* s2 = ci->getOperand(2);
628     if (s1 == s2)
629     {
630       // strcmp(x,x)  -> 0
631       ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
632       ci->eraseFromParent();
633       return true;
634     }
635
636     bool isstr_1 = false;
637     uint64_t len_1 = 0;
638     ConstantArray* A1;
639     if (getConstantStringLength(s1,len_1,&A1))
640     {
641       isstr_1 = true;
642       if (len_1 == 0)
643       {
644         // strcmp("",x) -> *x
645         LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
646         CastInst* cast = 
647           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
648         ci->replaceAllUsesWith(cast);
649         ci->eraseFromParent();
650         return true;
651       }
652     }
653
654     bool isstr_2 = false;
655     uint64_t len_2 = 0;
656     ConstantArray* A2;
657     if (getConstantStringLength(s2,len_2,&A2))
658     {
659       isstr_2 = true;
660       if (len_2 == 0)
661       {
662         // strcmp(x,"") -> *x
663         LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
664         CastInst* cast = 
665           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
666         ci->replaceAllUsesWith(cast);
667         ci->eraseFromParent();
668         return true;
669       }
670     }
671
672     if (isstr_1 && isstr_2)
673     {
674       // strcmp(x,y)  -> cnst  (if both x and y are constant strings)
675       std::string str1 = A1->getAsString();
676       std::string str2 = A2->getAsString();
677       int result = strcmp(str1.c_str(), str2.c_str());
678       ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
679       ci->eraseFromParent();
680       return true;
681     }
682     return false;
683   }
684 } StrCmpOptimizer;
685
686 /// This LibCallOptimization will simplify a call to the strncmp library 
687 /// function.  It optimizes out cases where one or both arguments are constant
688 /// and the result can be determined statically.
689 /// @brief Simplify the strncmp library function.
690 struct StrNCmpOptimization : public LibCallOptimization
691 {
692 public:
693   StrNCmpOptimization() : LibCallOptimization("strncmp",
694       "simplify-libcalls:strncmp","Number of 'strncmp' calls simplified") {}
695   virtual ~StrNCmpOptimization() {}
696
697   /// @brief Make sure that the "strcpy" function has the right prototype
698   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
699   {
700     if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
701       return true;
702     return false;
703   }
704
705   /// @brief Perform the strncpy optimization
706   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
707   {
708     // First, check to see if src and destination are the same. If they are,
709     // then the optimization is to replace the CallInst with a constant 0
710     // because the call is a no-op. 
711     Value* s1 = ci->getOperand(1);
712     Value* s2 = ci->getOperand(2);
713     if (s1 == s2)
714     {
715       // strncmp(x,x,l)  -> 0
716       ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
717       ci->eraseFromParent();
718       return true;
719     }
720
721     // Check the length argument, if it is Constant zero then the strings are
722     // considered equal.
723     uint64_t len_arg = 0;
724     bool len_arg_is_const = false;
725     if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
726     {
727       len_arg_is_const = true;
728       len_arg = len_CI->getRawValue();
729       if (len_arg == 0)
730       {
731         // strncmp(x,y,0)   -> 0
732         ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
733         ci->eraseFromParent();
734         return true;
735       } 
736     }
737
738     bool isstr_1 = false;
739     uint64_t len_1 = 0;
740     ConstantArray* A1;
741     if (getConstantStringLength(s1,len_1,&A1))
742     {
743       isstr_1 = true;
744       if (len_1 == 0)
745       {
746         // strncmp("",x) -> *x
747         LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
748         CastInst* cast = 
749           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
750         ci->replaceAllUsesWith(cast);
751         ci->eraseFromParent();
752         return true;
753       }
754     }
755
756     bool isstr_2 = false;
757     uint64_t len_2 = 0;
758     ConstantArray* A2;
759     if (getConstantStringLength(s2,len_2,&A2))
760     {
761       isstr_2 = true;
762       if (len_2 == 0)
763       {
764         // strncmp(x,"") -> *x
765         LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
766         CastInst* cast = 
767           new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
768         ci->replaceAllUsesWith(cast);
769         ci->eraseFromParent();
770         return true;
771       }
772     }
773
774     if (isstr_1 && isstr_2 && len_arg_is_const)
775     {
776       // strncmp(x,y,const) -> constant
777       std::string str1 = A1->getAsString();
778       std::string str2 = A2->getAsString();
779       int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
780       ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
781       ci->eraseFromParent();
782       return true;
783     }
784     return false;
785   }
786 } StrNCmpOptimizer;
787
788 /// This LibCallOptimization will simplify a call to the strcpy library 
789 /// function.  Two optimizations are possible: 
790 /// (1) If src and dest are the same and not volatile, just return dest
791 /// (2) If the src is a constant then we can convert to llvm.memmove
792 /// @brief Simplify the strcpy library function.
793 struct StrCpyOptimization : public LibCallOptimization
794 {
795 public:
796   StrCpyOptimization() : LibCallOptimization("strcpy",
797       "simplify-libcalls:strcpy","Number of 'strcpy' calls simplified") {}
798   virtual ~StrCpyOptimization() {}
799
800   /// @brief Make sure that the "strcpy" function has the right prototype
801   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
802   {
803     if (f->getReturnType() == PointerType::get(Type::SByteTy))
804       if (f->arg_size() == 2) 
805       {
806         Function::const_arg_iterator AI = f->arg_begin();
807         if (AI++->getType() == PointerType::get(Type::SByteTy))
808           if (AI->getType() == PointerType::get(Type::SByteTy))
809           {
810             // Indicate this is a suitable call type.
811             return true;
812           }
813       }
814     return false;
815   }
816
817   /// @brief Perform the strcpy optimization
818   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
819   {
820     // First, check to see if src and destination are the same. If they are,
821     // then the optimization is to replace the CallInst with the destination
822     // because the call is a no-op. Note that this corresponds to the 
823     // degenerate strcpy(X,X) case which should have "undefined" results
824     // according to the C specification. However, it occurs sometimes and
825     // we optimize it as a no-op.
826     Value* dest = ci->getOperand(1);
827     Value* src = ci->getOperand(2);
828     if (dest == src)
829     {
830       ci->replaceAllUsesWith(dest);
831       ci->eraseFromParent();
832       return true;
833     }
834     
835     // Get the length of the constant string referenced by the second operand,
836     // the "src" parameter. Fail the optimization if we can't get the length
837     // (note that getConstantStringLength does lots of checks to make sure this
838     // is valid).
839     uint64_t len = 0;
840     if (!getConstantStringLength(ci->getOperand(2),len))
841       return false;
842
843     // If the constant string's length is zero we can optimize this by just
844     // doing a store of 0 at the first byte of the destination
845     if (len == 0)
846     {
847       new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
848       ci->replaceAllUsesWith(dest);
849       ci->eraseFromParent();
850       return true;
851     }
852
853     // Increment the length because we actually want to memcpy the null
854     // terminator as well.
855     len++;
856
857     // Extract some information from the instruction
858     Module* M = ci->getParent()->getParent()->getParent();
859
860     // We have enough information to now generate the memcpy call to
861     // do the concatenation for us.
862     std::vector<Value*> vals;
863     vals.push_back(dest); // destination
864     vals.push_back(src); // source
865     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
866     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
867     new CallInst(SLC.get_memcpy(), vals, "", ci);
868
869     // Finally, substitute the first operand of the strcat call for the 
870     // strcat call itself since strcat returns its first operand; and, 
871     // kill the strcat CallInst.
872     ci->replaceAllUsesWith(dest);
873     ci->eraseFromParent();
874     return true;
875   }
876 } StrCpyOptimizer;
877
878 /// This LibCallOptimization will simplify a call to the strlen library 
879 /// function by replacing it with a constant value if the string provided to 
880 /// it is a constant array.
881 /// @brief Simplify the strlen library function.
882 struct StrLenOptimization : public LibCallOptimization
883 {
884   StrLenOptimization() : LibCallOptimization("strlen",
885       "simplify-libcalls:strlen","Number of 'strlen' calls simplified") {}
886   virtual ~StrLenOptimization() {}
887
888   /// @brief Make sure that the "strlen" function has the right prototype
889   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
890   {
891     if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
892       if (f->arg_size() == 1) 
893         if (Function::const_arg_iterator AI = f->arg_begin())
894           if (AI->getType() == PointerType::get(Type::SByteTy))
895             return true;
896     return false;
897   }
898
899   /// @brief Perform the strlen optimization
900   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
901   {
902     // Get the length of the string
903     uint64_t len = 0;
904     if (!getConstantStringLength(ci->getOperand(1),len))
905       return false;
906
907     ci->replaceAllUsesWith(
908         ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
909     ci->eraseFromParent();
910     return true;
911   }
912 } StrLenOptimizer;
913
914 /// This LibCallOptimization will simplify a call to the memcpy library 
915 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8 
916 /// bytes depending on the length of the string and the alignment. Additional
917 /// optimizations are possible in code generation (sequence of immediate store)
918 /// @brief Simplify the memcpy library function.
919 struct LLVMMemCpyOptimization : public LibCallOptimization
920 {
921   /// @brief Default Constructor
922   LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
923       "simplify-libcalls:llvm.memcpy",
924       "Number of 'llvm.memcpy' calls simplified") {}
925
926 protected:
927   /// @brief Subclass Constructor 
928   LLVMMemCpyOptimization(const char* fname, const char* sname, const char* desc)
929     : LibCallOptimization(fname, sname, desc) {}
930 public:
931   /// @brief Destructor
932   virtual ~LLVMMemCpyOptimization() {}
933
934   /// @brief Make sure that the "memcpy" function has the right prototype
935   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
936   {
937     // Just make sure this has 4 arguments per LLVM spec.
938     return (f->arg_size() == 4);
939   }
940
941   /// Because of alignment and instruction information that we don't have, we
942   /// leave the bulk of this to the code generators. The optimization here just
943   /// deals with a few degenerate cases where the length of the string and the
944   /// alignment match the sizes of our intrinsic types so we can do a load and
945   /// store instead of the memcpy call.
946   /// @brief Perform the memcpy optimization.
947   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
948   {
949     // Make sure we have constant int values to work with
950     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
951     if (!LEN)
952       return false;
953     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
954     if (!ALIGN)
955       return false;
956
957     // If the length is larger than the alignment, we can't optimize
958     uint64_t len = LEN->getRawValue();
959     uint64_t alignment = ALIGN->getRawValue();
960     if (alignment == 0)
961       alignment = 1; // Alignment 0 is identity for alignment 1
962     if (len > alignment)
963       return false;
964
965     // Get the type we will cast to, based on size of the string
966     Value* dest = ci->getOperand(1);
967     Value* src = ci->getOperand(2);
968     Type* castType = 0;
969     switch (len)
970     {
971       case 0:
972         // memcpy(d,s,0,a) -> noop
973         ci->eraseFromParent();
974         return true;
975       case 1: castType = Type::SByteTy; break;
976       case 2: castType = Type::ShortTy; break;
977       case 4: castType = Type::IntTy; break;
978       case 8: castType = Type::LongTy; break;
979       default:
980         return false;
981     }
982
983     // Cast source and dest to the right sized primitive and then load/store
984     CastInst* SrcCast = 
985       new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
986     CastInst* DestCast = 
987       new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
988     LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
989     StoreInst* SI = new StoreInst(LI, DestCast, ci);
990     ci->eraseFromParent();
991     return true;
992   }
993 } LLVMMemCpyOptimizer;
994
995 /// This LibCallOptimization will simplify a call to the memmove library 
996 /// function. It is identical to MemCopyOptimization except for the name of 
997 /// the intrinsic.
998 /// @brief Simplify the memmove library function.
999 struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
1000 {
1001   /// @brief Default Constructor
1002   LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
1003       "simplify-libcalls:llvm.memmove",
1004       "Number of 'llvm.memmove' calls simplified") {}
1005
1006 } LLVMMemMoveOptimizer;
1007
1008 /// This LibCallOptimization will simplify a call to the memset library 
1009 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8 
1010 /// bytes depending on the length argument. 
1011 struct LLVMMemSetOptimization : public LibCallOptimization
1012 {
1013   /// @brief Default Constructor
1014   LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
1015       "simplify-libcalls:llvm.memset",
1016       "Number of 'llvm.memset' calls simplified") {}
1017
1018 public:
1019   /// @brief Destructor
1020   virtual ~LLVMMemSetOptimization() {}
1021
1022   /// @brief Make sure that the "memset" function has the right prototype
1023   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1024   {
1025     // Just make sure this has 3 arguments per LLVM spec.
1026     return (f->arg_size() == 4);
1027   }
1028
1029   /// Because of alignment and instruction information that we don't have, we
1030   /// leave the bulk of this to the code generators. The optimization here just
1031   /// deals with a few degenerate cases where the length parameter is constant
1032   /// and the alignment matches the sizes of our intrinsic types so we can do 
1033   /// store instead of the memcpy call. Other calls are transformed into the
1034   /// llvm.memset intrinsic.
1035   /// @brief Perform the memset optimization.
1036   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1037   {
1038     // Make sure we have constant int values to work with
1039     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1040     if (!LEN)
1041       return false;
1042     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1043     if (!ALIGN)
1044       return false;
1045
1046     // Extract the length and alignment
1047     uint64_t len = LEN->getRawValue();
1048     uint64_t alignment = ALIGN->getRawValue();
1049
1050     // Alignment 0 is identity for alignment 1
1051     if (alignment == 0)
1052       alignment = 1;
1053
1054     // If the length is zero, this is a no-op
1055     if (len == 0)
1056     {
1057       // memset(d,c,0,a) -> noop
1058       ci->eraseFromParent();
1059       return true;
1060     }
1061
1062     // If the length is larger than the alignment, we can't optimize
1063     if (len > alignment)
1064       return false;
1065
1066     // Make sure we have a constant ubyte to work with so we can extract
1067     // the value to be filled.
1068     ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1069     if (!FILL)
1070       return false;
1071     if (FILL->getType() != Type::UByteTy)
1072       return false;
1073
1074     // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1075     
1076     // Extract the fill character
1077     uint64_t fill_char = FILL->getValue();
1078     uint64_t fill_value = fill_char;
1079
1080     // Get the type we will cast to, based on size of memory area to fill, and
1081     // and the value we will store there.
1082     Value* dest = ci->getOperand(1);
1083     Type* castType = 0;
1084     switch (len)
1085     {
1086       case 1: 
1087         castType = Type::UByteTy; 
1088         break;
1089       case 2: 
1090         castType = Type::UShortTy; 
1091         fill_value |= fill_char << 8;
1092         break;
1093       case 4: 
1094         castType = Type::UIntTy;
1095         fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1096         break;
1097       case 8: 
1098         castType = Type::ULongTy;
1099         fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1100         fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1101         fill_value |= fill_char << 56;
1102         break;
1103       default:
1104         return false;
1105     }
1106
1107     // Cast dest to the right sized primitive and then load/store
1108     CastInst* DestCast = 
1109       new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1110     new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1111     ci->eraseFromParent();
1112     return true;
1113   }
1114 } LLVMMemSetOptimizer;
1115
1116 /// This LibCallOptimization will simplify calls to the "pow" library 
1117 /// function. It looks for cases where the result of pow is well known and 
1118 /// substitutes the appropriate value.
1119 /// @brief Simplify the pow library function.
1120 struct PowOptimization : public LibCallOptimization
1121 {
1122 public:
1123   /// @brief Default Constructor
1124   PowOptimization() : LibCallOptimization("pow",
1125       "simplify-libcalls:pow", "Number of 'pow' calls simplified") {}
1126
1127   /// @brief Destructor
1128   virtual ~PowOptimization() {}
1129
1130   /// @brief Make sure that the "pow" function has the right prototype
1131   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1132   {
1133     // Just make sure this has 2 arguments
1134     return (f->arg_size() == 2);
1135   }
1136
1137   /// @brief Perform the pow optimization.
1138   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1139   {
1140     const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1141     Value* base = ci->getOperand(1);
1142     Value* expn = ci->getOperand(2);
1143     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1144       double Op1V = Op1->getValue();
1145       if (Op1V == 1.0)
1146       {
1147         // pow(1.0,x) -> 1.0
1148         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1149         ci->eraseFromParent();
1150         return true;
1151       }
1152     } 
1153     else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) 
1154     {
1155       double Op2V = Op2->getValue();
1156       if (Op2V == 0.0)
1157       {
1158         // pow(x,0.0) -> 1.0
1159         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1160         ci->eraseFromParent();
1161         return true;
1162       }
1163       else if (Op2V == 0.5)
1164       {
1165         // pow(x,0.5) -> sqrt(x)
1166         CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1167             ci->getName()+".pow",ci);
1168         ci->replaceAllUsesWith(sqrt_inst);
1169         ci->eraseFromParent();
1170         return true;
1171       }
1172       else if (Op2V == 1.0)
1173       {
1174         // pow(x,1.0) -> x
1175         ci->replaceAllUsesWith(base);
1176         ci->eraseFromParent();
1177         return true;
1178       }
1179       else if (Op2V == -1.0)
1180       {
1181         // pow(x,-1.0)    -> 1.0/x
1182         BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
1183           ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1184         ci->replaceAllUsesWith(div_inst);
1185         ci->eraseFromParent();
1186         return true;
1187       }
1188     }
1189     return false; // opt failed
1190   }
1191 } PowOptimizer;
1192
1193 /// This LibCallOptimization will simplify calls to the "fprintf" library 
1194 /// function. It looks for cases where the result of fprintf is not used and the
1195 /// operation can be reduced to something simpler.
1196 /// @brief Simplify the pow library function.
1197 struct FPrintFOptimization : public LibCallOptimization
1198 {
1199 public:
1200   /// @brief Default Constructor
1201   FPrintFOptimization() : LibCallOptimization("fprintf",
1202       "simplify-libcalls:fprintf", "Number of 'fprintf' calls simplified") {}
1203
1204   /// @brief Destructor
1205   virtual ~FPrintFOptimization() {}
1206
1207   /// @brief Make sure that the "fprintf" function has the right prototype
1208   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1209   {
1210     // Just make sure this has at least 2 arguments
1211     return (f->arg_size() >= 2);
1212   }
1213
1214   /// @brief Perform the fprintf optimization.
1215   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1216   {
1217     // If the call has more than 3 operands, we can't optimize it
1218     if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1219       return false;
1220
1221     // If the result of the fprintf call is used, none of these optimizations 
1222     // can be made.
1223     if (!ci->hasNUses(0)) 
1224       return false;
1225
1226     // All the optimizations depend on the length of the second argument and the
1227     // fact that it is a constant string array. Check that now
1228     uint64_t len = 0; 
1229     ConstantArray* CA = 0;
1230     if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1231       return false;
1232
1233     if (ci->getNumOperands() == 3)
1234     {
1235       // Make sure there's no % in the constant array
1236       for (unsigned i = 0; i < len; ++i)
1237       {
1238         if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1239         {
1240           // Check for the null terminator
1241           if (CI->getRawValue() == '%')
1242             return false; // we found end of string
1243         }
1244         else 
1245           return false;
1246       }
1247
1248       // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1file) 
1249       const Type* FILEptr_type = ci->getOperand(1)->getType();
1250       Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1251       if (!fwrite_func)
1252         return false;
1253       std::vector<Value*> args;
1254       args.push_back(ci->getOperand(2));
1255       args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1256       args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1257       args.push_back(ci->getOperand(1));
1258       new CallInst(fwrite_func,args,"",ci);
1259       ci->eraseFromParent();
1260       return true;
1261     }
1262
1263     // The remaining optimizations require the format string to be length 2
1264     // "%s" or "%c".
1265     if (len != 2)
1266       return false;
1267
1268     // The first character has to be a %
1269     if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1270       if (CI->getRawValue() != '%')
1271         return false;
1272
1273     // Get the second character and switch on its value
1274     ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1275     switch (CI->getRawValue())
1276     {
1277       case 's':
1278       {
1279         uint64_t len = 0; 
1280         ConstantArray* CA = 0;
1281         if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1282           return false;
1283
1284         // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1,file) 
1285         const Type* FILEptr_type = ci->getOperand(1)->getType();
1286         Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1287         if (!fwrite_func)
1288           return false;
1289         std::vector<Value*> args;
1290         args.push_back(ci->getOperand(3));
1291         args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1292         args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1293         args.push_back(ci->getOperand(1));
1294         new CallInst(fwrite_func,args,"",ci);
1295         break;
1296       }
1297       case 'c':
1298       {
1299         ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1300         if (!CI)
1301           return false;
1302
1303         const Type* FILEptr_type = ci->getOperand(1)->getType();
1304         Function* fputc_func = SLC.get_fputc(FILEptr_type);
1305         if (!fputc_func)
1306           return false;
1307         CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1308         new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1309         break;
1310       }
1311       default:
1312         return false;
1313     }
1314     ci->eraseFromParent();
1315     return true;
1316   }
1317 } FPrintFOptimizer;
1318
1319
1320 /// This LibCallOptimization will simplify calls to the "fputs" library 
1321 /// function. It looks for cases where the result of fputs is not used and the
1322 /// operation can be reduced to something simpler.
1323 /// @brief Simplify the pow library function.
1324 struct PutsOptimization : public LibCallOptimization
1325 {
1326 public:
1327   /// @brief Default Constructor
1328   PutsOptimization() : LibCallOptimization("fputs",
1329       "simplify-libcalls:fputs", "Number of 'fputs' calls simplified") {}
1330
1331   /// @brief Destructor
1332   virtual ~PutsOptimization() {}
1333
1334   /// @brief Make sure that the "fputs" function has the right prototype
1335   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1336   {
1337     // Just make sure this has 2 arguments
1338     return (f->arg_size() == 2);
1339   }
1340
1341   /// @brief Perform the fputs optimization.
1342   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1343   {
1344     // If the result is used, none of these optimizations work
1345     if (!ci->hasNUses(0)) 
1346       return false;
1347
1348     // All the optimizations depend on the length of the first argument and the
1349     // fact that it is a constant string array. Check that now
1350     uint64_t len = 0; 
1351     if (!getConstantStringLength(ci->getOperand(1), len))
1352       return false;
1353
1354     switch (len)
1355     {
1356       case 0:
1357         // fputs("",F) -> noop
1358         break;
1359       case 1:
1360       {
1361         // fputs(s,F)  -> fputc(s[0],F)  (if s is constant and strlen(s) == 1)
1362         const Type* FILEptr_type = ci->getOperand(2)->getType();
1363         Function* fputc_func = SLC.get_fputc(FILEptr_type);
1364         if (!fputc_func)
1365           return false;
1366         LoadInst* loadi = new LoadInst(ci->getOperand(1),
1367           ci->getOperand(1)->getName()+".byte",ci);
1368         CastInst* casti = new CastInst(loadi,Type::IntTy,
1369           loadi->getName()+".int",ci);
1370         new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1371         break;
1372       }
1373       default:
1374       {  
1375         // fputs(s,F)  -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1376         const Type* FILEptr_type = ci->getOperand(2)->getType();
1377         Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1378         if (!fwrite_func)
1379           return false;
1380         std::vector<Value*> parms;
1381         parms.push_back(ci->getOperand(1));
1382         parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1383         parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1384         parms.push_back(ci->getOperand(2));
1385         new CallInst(fwrite_func,parms,"",ci);
1386         break;
1387       }
1388     }
1389     ci->eraseFromParent();
1390     return true; // success
1391   }
1392 } PutsOptimizer;
1393
1394 /// This LibCallOptimization will simplify calls to the "toascii" library 
1395 /// function. It simply does the corresponding and operation to restrict the
1396 /// range of values to the ASCII character set (0-127).
1397 /// @brief Simplify the toascii library function.
1398 struct ToAsciiOptimization : public LibCallOptimization
1399 {
1400 public:
1401   /// @brief Default Constructor
1402   ToAsciiOptimization() : LibCallOptimization("toascii",
1403       "simplify-libcalls:toascii", "Number of 'toascii' calls simplified") {}
1404
1405   /// @brief Destructor
1406   virtual ~ToAsciiOptimization() {}
1407
1408   /// @brief Make sure that the "fputs" function has the right prototype
1409   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1410   {
1411     // Just make sure this has 2 arguments
1412     return (f->arg_size() == 1);
1413   }
1414
1415   /// @brief Perform the toascii optimization.
1416   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1417   {
1418     // toascii(c)   -> (c & 0x7f)
1419     Value* chr = ci->getOperand(1);
1420     BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1421         ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1422     ci->replaceAllUsesWith(and_inst);
1423     ci->eraseFromParent();
1424     return true;
1425   }
1426 } ToAsciiOptimizer;
1427
1428 /// A function to compute the length of a null-terminated constant array of
1429 /// integers.  This function can't rely on the size of the constant array 
1430 /// because there could be a null terminator in the middle of the array. 
1431 /// We also have to bail out if we find a non-integer constant initializer 
1432 /// of one of the elements or if there is no null-terminator. The logic 
1433 /// below checks each of these conditions and will return true only if all
1434 /// conditions are met. In that case, the \p len parameter is set to the length
1435 /// of the null-terminated string. If false is returned, the conditions were
1436 /// not met and len is set to 0.
1437 /// @brief Get the length of a constant string (null-terminated array).
1438 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1439 {
1440   assert(V != 0 && "Invalid args to getConstantStringLength");
1441   len = 0; // make sure we initialize this 
1442   User* GEP = 0;
1443   // If the value is not a GEP instruction nor a constant expression with a 
1444   // GEP instruction, then return false because ConstantArray can't occur 
1445   // any other way
1446   if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1447     GEP = GEPI;
1448   else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1449     if (CE->getOpcode() == Instruction::GetElementPtr)
1450       GEP = CE;
1451     else
1452       return false;
1453   else
1454     return false;
1455
1456   // Make sure the GEP has exactly three arguments.
1457   if (GEP->getNumOperands() != 3)
1458     return false;
1459
1460   // Check to make sure that the first operand of the GEP is an integer and
1461   // has value 0 so that we are sure we're indexing into the initializer. 
1462   if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1463   {
1464     if (!op1->isNullValue())
1465       return false;
1466   }
1467   else
1468     return false;
1469
1470   // Ensure that the second operand is a ConstantInt. If it isn't then this
1471   // GEP is wonky and we're not really sure what were referencing into and 
1472   // better of not optimizing it. While we're at it, get the second index
1473   // value. We'll need this later for indexing the ConstantArray.
1474   uint64_t start_idx = 0;
1475   if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1476     start_idx = CI->getRawValue();
1477   else
1478     return false;
1479
1480   // The GEP instruction, constant or instruction, must reference a global
1481   // variable that is a constant and is initialized. The referenced constant
1482   // initializer is the array that we'll use for optimization.
1483   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1484   if (!GV || !GV->isConstant() || !GV->hasInitializer())
1485     return false;
1486
1487   // Get the initializer.
1488   Constant* INTLZR = GV->getInitializer();
1489
1490   // Handle the ConstantAggregateZero case
1491   if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1492   {
1493     // This is a degenerate case. The initializer is constant zero so the
1494     // length of the string must be zero.
1495     len = 0;
1496     return true;
1497   }
1498
1499   // Must be a Constant Array
1500   ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1501   if (!A)
1502     return false;
1503
1504   // Get the number of elements in the array
1505   uint64_t max_elems = A->getType()->getNumElements();
1506
1507   // Traverse the constant array from start_idx (derived above) which is
1508   // the place the GEP refers to in the array. 
1509   for ( len = start_idx; len < max_elems; len++)
1510   {
1511     if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1512     {
1513       // Check for the null terminator
1514       if (CI->isNullValue())
1515         break; // we found end of string
1516     }
1517     else
1518       return false; // This array isn't suitable, non-int initializer
1519   }
1520   if (len >= max_elems)
1521     return false; // This array isn't null terminated
1522
1523   // Subtract out the initial value from the length
1524   len -= start_idx;
1525   if (CA)
1526     *CA = A;
1527   return true; // success!
1528 }
1529
1530 // TODO: 
1531 //   Additional cases that we need to add to this file:
1532 //
1533 // cbrt:
1534 //   * cbrt(expN(X))  -> expN(x/3)
1535 //   * cbrt(sqrt(x))  -> pow(x,1/6)
1536 //   * cbrt(sqrt(x))  -> pow(x,1/9)
1537 //
1538 // cos, cosf, cosl:
1539 //   * cos(-x)  -> cos(x)
1540 //
1541 // exp, expf, expl:
1542 //   * exp(log(x))  -> x
1543 //
1544 // ffs, ffsl, ffsll:
1545 //   * ffs(cnst)     -> cnst'
1546 //
1547 // isascii:
1548 //   * isascii(c)    -> ((c & ~0x7f) == 0)
1549 //   
1550 // isdigit:
1551 //   * isdigit(c)    -> (unsigned)(c) - '0' <= 9
1552 //
1553 // log, logf, logl:
1554 //   * log(exp(x))   -> x
1555 //   * log(x**y)     -> y*log(x)
1556 //   * log(exp(y))   -> y*log(e)
1557 //   * log(exp2(y))  -> y*log(2)
1558 //   * log(exp10(y)) -> y*log(10)
1559 //   * log(sqrt(x))  -> 0.5*log(x)
1560 //   * log(pow(x,y)) -> y*log(x)
1561 //
1562 // lround, lroundf, lroundl:
1563 //   * lround(cnst) -> cnst'
1564 //
1565 // memcmp:
1566 //   * memcmp(s1,s2,0) -> 0
1567 //   * memcmp(x,x,l)   -> 0
1568 //   * memcmp(x,y,l)   -> cnst
1569 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1570 //   * memcmp(x,y,1)   -> *x - *y
1571 //
1572 // memmove:
1573 //   * memmove(d,s,l,a) -> memcpy(d,s,l,a) 
1574 //       (if s is a global constant array)
1575 //
1576 // pow, powf, powl:
1577 //   * pow(exp(x),y)  -> exp(x*y)
1578 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1579 //   * pow(pow(x,y),z)-> pow(x,y*z)
1580 //
1581 // puts:
1582 //   * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1583 //
1584 // round, roundf, roundl:
1585 //   * round(cnst) -> cnst'
1586 //
1587 // signbit:
1588 //   * signbit(cnst) -> cnst'
1589 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1590 //
1591 // sprintf:
1592 //   * sprintf(dest,fmt) -> strcpy(dest,fmt) 
1593 //       (if fmt is constant and constains no % characters)
1594 //   * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1595 //       (only if the sprintf result is not used)
1596 //
1597 // sqrt, sqrtf, sqrtl:
1598 //   * sqrt(expN(x))  -> expN(x*0.5)
1599 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1600 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1601 //
1602 // strrchr:
1603 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
1604 //      (if c is a constant integer and s is a constant string)
1605 //   * strrchr(s1,0) -> strchr(s1,0)
1606 //
1607 // strncat:
1608 //   * strncat(x,y,0) -> x
1609 //   * strncat(x,y,0) -> x (if strlen(y) = 0)
1610 //   * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1611 //
1612 // strncpy:
1613 //   * strncpy(d,s,0) -> d
1614 //   * strncpy(d,s,l) -> memcpy(d,s,l,1)
1615 //      (if s and l are constants)
1616 //
1617 // strpbrk:
1618 //   * strpbrk(s,a) -> offset_in_for(s,a)
1619 //      (if s and a are both constant strings)
1620 //   * strpbrk(s,"") -> 0
1621 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1622 //
1623 // strspn, strcspn:
1624 //   * strspn(s,a)   -> const_int (if both args are constant)
1625 //   * strspn("",a)  -> 0
1626 //   * strspn(s,"")  -> 0
1627 //   * strcspn(s,a)  -> const_int (if both args are constant)
1628 //   * strcspn("",a) -> 0
1629 //   * strcspn(s,"") -> strlen(a)
1630 //
1631 // strstr:
1632 //   * strstr(x,x)  -> x
1633 //   * strstr(s1,s2) -> offset_of_s2_in(s1)  
1634 //       (if s1 and s2 are constant strings)
1635 //    
1636 // tan, tanf, tanl:
1637 //   * tan(atan(x)) -> x
1638 // 
1639 // trunc, truncf, truncl:
1640 //   * trunc(cnst) -> cnst'
1641 //
1642 // 
1643 }