Implement the optimizations for "pow" and "fputs" 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     : func_name(fname)
70 #ifndef NDEBUG
71     , stat_name(std::string("simplify-libcalls:")+fname)
72     , stat_desc(std::string("Number of ")+fname+"(...) calls simplified")
73     , occurrences(stat_name.c_str(),stat_desc.c_str())
74 #endif
75   {
76     // Register this call optimizer in the optlist (a hash_map)
77     optlist[func_name] = this;
78   }
79
80   /// @brief Deregister from the optlist
81   virtual ~LibCallOptimization() { optlist.erase(func_name); }
82
83   /// The implementation of this function in subclasses should determine if
84   /// \p F is suitable for the optimization. This method is called by 
85   /// SimplifyLibCalls::runOnModule to short circuit visiting all the call 
86   /// sites of such a function if that function is not suitable in the first 
87   /// place.  If the called function is suitabe, this method should return true;
88   /// false, otherwise. This function should also perform any lazy 
89   /// initialization that the LibCallOptimization needs to do, if its to return 
90   /// true. This avoids doing initialization until the optimizer is actually
91   /// going to be called upon to do some optimization.
92   /// @brief Determine if the function is suitable for optimization
93   virtual bool ValidateCalledFunction(
94     const Function* F,    ///< The function that is the target of call sites
95     SimplifyLibCalls& SLC ///< The pass object invoking us
96   ) = 0;
97
98   /// The implementations of this function in subclasses is the heart of the 
99   /// SimplifyLibCalls algorithm. Sublcasses of this class implement 
100   /// OptimizeCall to determine if (a) the conditions are right for optimizing
101   /// the call and (b) to perform the optimization. If an action is taken 
102   /// against ci, the subclass is responsible for returning true and ensuring
103   /// that ci is erased from its parent.
104   /// @brief Optimize a call, if possible.
105   virtual bool OptimizeCall(
106     CallInst* ci,          ///< The call instruction that should be optimized.
107     SimplifyLibCalls& SLC  ///< The pass object invoking us
108   ) = 0;
109
110   /// @brief Get the name of the library call being optimized
111   const char * getFunctionName() const { return func_name; }
112
113 #ifndef NDEBUG
114   /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
115   void succeeded() { ++occurrences; }
116 #endif
117
118 private:
119   const char* func_name; ///< Name of the library call we optimize
120 #ifndef NDEBUG
121   std::string stat_name; ///< Holder for debug statistic name
122   std::string stat_desc; ///< Holder for debug statistic description
123   Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
124 #endif
125 };
126
127 /// This class is an LLVM Pass that applies each of the LibCallOptimization 
128 /// instances to all the call sites in a module, relatively efficiently. The
129 /// purpose of this pass is to provide optimizations for calls to well-known 
130 /// functions with well-known semantics, such as those in the c library. The
131 /// class provides the basic infrastructure for handling runOnModule.  Whenever /// this pass finds a function call, it asks the appropriate optimizer to 
132 /// validate the call (ValidateLibraryCall). If it is validated, then
133 /// the OptimizeCall method is also called.
134 /// @brief A ModulePass for optimizing well-known function calls.
135 class SimplifyLibCalls : public ModulePass 
136 {
137 public:
138   /// We need some target data for accurate signature details that are
139   /// target dependent. So we require target data in our AnalysisUsage.
140   /// @brief Require TargetData from AnalysisUsage.
141   virtual void getAnalysisUsage(AnalysisUsage& Info) const
142   {
143     // Ask that the TargetData analysis be performed before us so we can use
144     // the target data.
145     Info.addRequired<TargetData>();
146   }
147
148   /// For this pass, process all of the function calls in the module, calling
149   /// ValidateLibraryCall and OptimizeCall as appropriate.
150   /// @brief Run all the lib call optimizations on a Module.
151   virtual bool runOnModule(Module &M)
152   {
153     reset(M);
154
155     bool result = false;
156
157     // The call optimizations can be recursive. That is, the optimization might
158     // generate a call to another function which can also be optimized. This way
159     // we make the LibCallOptimization instances very specific to the case they 
160     // handle. It also means we need to keep running over the function calls in 
161     // the module until we don't get any more optimizations possible.
162     bool found_optimization = false;
163     do
164     {
165       found_optimization = false;
166       for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
167       {
168         // All the "well-known" functions are external and have external linkage
169         // because they live in a runtime library somewhere and were (probably) 
170         // not compiled by LLVM.  So, we only act on external functions that have 
171         // external linkage and non-empty uses.
172         if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
173           continue;
174
175         // Get the optimization class that pertains to this function
176         LibCallOptimization* CO = optlist[FI->getName().c_str()];
177         if (!CO)
178           continue;
179
180         // Make sure the called function is suitable for the optimization
181         if (!CO->ValidateCalledFunction(FI,*this))
182           continue;
183
184         // Loop over each of the uses of the function
185         for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end(); 
186              UI != UE ; )
187         {
188           // If the use of the function is a call instruction
189           if (CallInst* CI = dyn_cast<CallInst>(*UI++))
190           {
191             // Do the optimization on the LibCallOptimization.
192             if (CO->OptimizeCall(CI,*this))
193             {
194               ++SimplifiedLibCalls;
195               found_optimization = result = true;
196 #ifndef NDEBUG
197               CO->succeeded();
198 #endif
199             }
200           }
201         }
202       }
203     } while (found_optimization);
204     return result;
205   }
206
207   /// @brief Return the *current* module we're working on.
208   Module* getModule() const { return M; }
209
210   /// @brief Return the *current* target data for the module we're working on.
211   TargetData* getTargetData() const { return TD; }
212
213   /// @brief Return the size_t type -- syntactic shortcut
214   const Type* getIntPtrType() const { return TD->getIntPtrType(); }
215
216   /// @brief Return a Function* for the fputc libcall
217   Function* get_fputc()
218   {
219     if (!fputc_func)
220     {
221       std::vector<const Type*> args;
222       args.push_back(Type::IntTy);
223       const Type* FILE_type = M->getTypeByName("struct._IO_FILE");
224       if (!FILE_type)
225         FILE_type = M->getTypeByName("struct._FILE");
226       if (!FILE_type)
227         return 0;
228       args.push_back(PointerType::get(FILE_type));
229       FunctionType* fputc_type = 
230         FunctionType::get(Type::IntTy, args, false);
231       fputc_func = M->getOrInsertFunction("fputc",fputc_type);
232     }
233     return fputc_func;
234   }
235
236   /// @brief Return a Function* for the fwrite libcall
237   Function* get_fwrite()
238   {
239     if (!fwrite_func)
240     {
241       std::vector<const Type*> args;
242       args.push_back(PointerType::get(Type::SByteTy));
243       args.push_back(TD->getIntPtrType());
244       args.push_back(TD->getIntPtrType());
245       const Type* FILE_type = M->getTypeByName("struct._IO_FILE");
246       if (!FILE_type)
247         FILE_type = M->getTypeByName("struct._FILE");
248       if (!FILE_type)
249         return 0;
250       args.push_back(PointerType::get(FILE_type));
251       FunctionType* fwrite_type = 
252         FunctionType::get(TD->getIntPtrType(), args, false);
253       fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
254     }
255     return fwrite_func;
256   }
257
258   /// @brief Return a Function* for the sqrt libcall
259   Function* get_sqrt()
260   {
261     if (!sqrt_func)
262     {
263       std::vector<const Type*> args;
264       args.push_back(Type::DoubleTy);
265       FunctionType* sqrt_type = 
266         FunctionType::get(Type::DoubleTy, args, false);
267       sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
268     }
269     return sqrt_func;
270   }
271
272   /// @brief Return a Function* for the strlen libcall
273   Function* get_strlen()
274   {
275     if (!strlen_func)
276     {
277       std::vector<const Type*> args;
278       args.push_back(PointerType::get(Type::SByteTy));
279       FunctionType* strlen_type = 
280         FunctionType::get(TD->getIntPtrType(), args, false);
281       strlen_func = M->getOrInsertFunction("strlen",strlen_type);
282     }
283     return strlen_func;
284   }
285
286   /// @brief Return a Function* for the memcpy libcall
287   Function* get_memcpy()
288   {
289     if (!memcpy_func)
290     {
291       // Note: this is for llvm.memcpy intrinsic
292       std::vector<const Type*> args;
293       args.push_back(PointerType::get(Type::SByteTy));
294       args.push_back(PointerType::get(Type::SByteTy));
295       args.push_back(Type::IntTy);
296       args.push_back(Type::IntTy);
297       FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
298       memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
299     }
300     return memcpy_func;
301   }
302
303 private:
304   /// @brief Reset our cached data for a new Module
305   void reset(Module& mod)
306   {
307     M = &mod;
308     TD = &getAnalysis<TargetData>();
309     fputc_func = 0;
310     fwrite_func = 0;
311     memcpy_func = 0;
312     sqrt_func   = 0;
313     strlen_func = 0;
314   }
315
316 private:
317   Function* fputc_func;  ///< Cached fputc function
318   Function* fwrite_func; ///< Cached fwrite function
319   Function* memcpy_func; ///< Cached llvm.memcpy function
320   Function* sqrt_func;   ///< Cached sqrt function
321   Function* strlen_func; ///< Cached strlen function
322   Module* M;             ///< Cached Module
323   TargetData* TD;        ///< Cached TargetData
324 };
325
326 // Register the pass
327 RegisterOpt<SimplifyLibCalls> 
328 X("simplify-libcalls","Simplify well-known library calls");
329
330 } // anonymous namespace
331
332 // The only public symbol in this file which just instantiates the pass object
333 ModulePass *llvm::createSimplifyLibCallsPass() 
334
335   return new SimplifyLibCalls(); 
336 }
337
338 // Classes below here, in the anonymous namespace, are all subclasses of the
339 // LibCallOptimization class, each implementing all optimizations possible for a
340 // single well-known library call. Each has a static singleton instance that
341 // auto registers it into the "optlist" global above. 
342 namespace {
343
344 // Forward declare a utility function.
345 bool getConstantStringLength(Value* V, uint64_t& len );
346
347 /// This LibCallOptimization will find instances of a call to "exit" that occurs
348 /// within the "main" function and change it to a simple "ret" instruction with
349 /// the same value passed to the exit function. When this is done, it splits the
350 /// basic block at the exit(3) call and deletes the call instruction.
351 /// @brief Replace calls to exit in main with a simple return
352 struct ExitInMainOptimization : public LibCallOptimization
353 {
354   ExitInMainOptimization() : LibCallOptimization("exit") {}
355   virtual ~ExitInMainOptimization() {}
356
357   // Make sure the called function looks like exit (int argument, int return
358   // type, external linkage, not varargs). 
359   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
360   {
361     if (f->arg_size() >= 1)
362       if (f->arg_begin()->getType()->isInteger())
363         return true;
364     return false;
365   }
366
367   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
368   {
369     // To be careful, we check that the call to exit is coming from "main", that
370     // main has external linkage, and the return type of main and the argument
371     // to exit have the same type. 
372     Function *from = ci->getParent()->getParent();
373     if (from->hasExternalLinkage())
374       if (from->getReturnType() == ci->getOperand(1)->getType())
375         if (from->getName() == "main")
376         {
377           // Okay, time to actually do the optimization. First, get the basic 
378           // block of the call instruction
379           BasicBlock* bb = ci->getParent();
380
381           // Create a return instruction that we'll replace the call with. 
382           // Note that the argument of the return is the argument of the call 
383           // instruction.
384           ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
385
386           // Split the block at the call instruction which places it in a new
387           // basic block.
388           bb->splitBasicBlock(ci);
389
390           // The block split caused a branch instruction to be inserted into
391           // the end of the original block, right after the return instruction
392           // that we put there. That's not a valid block, so delete the branch
393           // instruction.
394           bb->getInstList().pop_back();
395
396           // Now we can finally get rid of the call instruction which now lives
397           // in the new basic block.
398           ci->eraseFromParent();
399
400           // Optimization succeeded, return true.
401           return true;
402         }
403     // We didn't pass the criteria for this optimization so return false
404     return false;
405   }
406 } ExitInMainOptimizer;
407
408 /// This LibCallOptimization will simplify a call to the strcat library 
409 /// function. The simplification is possible only if the string being 
410 /// concatenated is a constant array or a constant expression that results in 
411 /// a constant string. In this case we can replace it with strlen + llvm.memcpy 
412 /// of the constant string. Both of these calls are further reduced, if possible
413 /// on subsequent passes.
414 /// @brief Simplify the strcat library function.
415 struct StrCatOptimization : public LibCallOptimization
416 {
417 public:
418   /// @brief Default constructor
419   StrCatOptimization() : LibCallOptimization("strcat") {}
420
421 public:
422   /// @breif  Destructor
423   virtual ~StrCatOptimization() {}
424
425   /// @brief Make sure that the "strcat" function has the right prototype
426   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
427   {
428     if (f->getReturnType() == PointerType::get(Type::SByteTy))
429       if (f->arg_size() == 2) 
430       {
431         Function::const_arg_iterator AI = f->arg_begin();
432         if (AI++->getType() == PointerType::get(Type::SByteTy))
433           if (AI->getType() == PointerType::get(Type::SByteTy))
434           {
435             // Indicate this is a suitable call type.
436             return true;
437           }
438       }
439     return false;
440   }
441
442   /// @brief Optimize the strcat library function
443   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
444   {
445     // Extract some information from the instruction
446     Module* M = ci->getParent()->getParent()->getParent();
447     Value* dest = ci->getOperand(1);
448     Value* src  = ci->getOperand(2);
449
450     // Extract the initializer (while making numerous checks) from the 
451     // source operand of the call to strcat. If we get null back, one of
452     // a variety of checks in get_GVInitializer failed
453     uint64_t len = 0;
454     if (!getConstantStringLength(src,len))
455       return false;
456
457     // Handle the simple, do-nothing case
458     if (len == 0)
459     {
460       ci->replaceAllUsesWith(dest);
461       ci->eraseFromParent();
462       return true;
463     }
464
465     // Increment the length because we actually want to memcpy the null
466     // terminator as well.
467     len++;
468
469     // We need to find the end of the destination string.  That's where the 
470     // memory is to be moved to. We just generate a call to strlen (further 
471     // optimized in another pass).  Note that the SLC.get_strlen() call 
472     // caches the Function* for us.
473     CallInst* strlen_inst = 
474       new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
475
476     // Now that we have the destination's length, we must index into the 
477     // destination's pointer to get the actual memcpy destination (end of
478     // the string .. we're concatenating).
479     std::vector<Value*> idx;
480     idx.push_back(strlen_inst);
481     GetElementPtrInst* gep = 
482       new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
483
484     // We have enough information to now generate the memcpy call to
485     // do the concatenation for us.
486     std::vector<Value*> vals;
487     vals.push_back(gep); // destination
488     vals.push_back(ci->getOperand(2)); // source
489     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
490     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
491     new CallInst(SLC.get_memcpy(), vals, "", ci);
492
493     // Finally, substitute the first operand of the strcat call for the 
494     // strcat call itself since strcat returns its first operand; and, 
495     // kill the strcat CallInst.
496     ci->replaceAllUsesWith(dest);
497     ci->eraseFromParent();
498     return true;
499   }
500 } StrCatOptimizer;
501
502 /// This LibCallOptimization will simplify a call to the strcpy library 
503 /// function.  Two optimizations are possible: 
504 /// (1) If src and dest are the same and not volatile, just return dest
505 /// (2) If the src is a constant then we can convert to llvm.memmove
506 /// @brief Simplify the strcpy library function.
507 struct StrCpyOptimization : public LibCallOptimization
508 {
509 public:
510   StrCpyOptimization() : LibCallOptimization("strcpy") {}
511   virtual ~StrCpyOptimization() {}
512
513   /// @brief Make sure that the "strcpy" function has the right prototype
514   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
515   {
516     if (f->getReturnType() == PointerType::get(Type::SByteTy))
517       if (f->arg_size() == 2) 
518       {
519         Function::const_arg_iterator AI = f->arg_begin();
520         if (AI++->getType() == PointerType::get(Type::SByteTy))
521           if (AI->getType() == PointerType::get(Type::SByteTy))
522           {
523             // Indicate this is a suitable call type.
524             return true;
525           }
526       }
527     return false;
528   }
529
530   /// @brief Perform the strcpy optimization
531   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
532   {
533     // First, check to see if src and destination are the same. If they are,
534     // then the optimization is to replace the CallInst with the destination
535     // because the call is a no-op. Note that this corresponds to the 
536     // degenerate strcpy(X,X) case which should have "undefined" results
537     // according to the C specification. However, it occurs sometimes and
538     // we optimize it as a no-op.
539     Value* dest = ci->getOperand(1);
540     Value* src = ci->getOperand(2);
541     if (dest == src)
542     {
543       ci->replaceAllUsesWith(dest);
544       ci->eraseFromParent();
545       return true;
546     }
547     
548     // Get the length of the constant string referenced by the second operand,
549     // the "src" parameter. Fail the optimization if we can't get the length
550     // (note that getConstantStringLength does lots of checks to make sure this
551     // is valid).
552     uint64_t len = 0;
553     if (!getConstantStringLength(ci->getOperand(2),len))
554       return false;
555
556     // If the constant string's length is zero we can optimize this by just
557     // doing a store of 0 at the first byte of the destination
558     if (len == 0)
559     {
560       new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
561       ci->replaceAllUsesWith(dest);
562       ci->eraseFromParent();
563       return true;
564     }
565
566     // Increment the length because we actually want to memcpy the null
567     // terminator as well.
568     len++;
569
570     // Extract some information from the instruction
571     Module* M = ci->getParent()->getParent()->getParent();
572
573     // We have enough information to now generate the memcpy call to
574     // do the concatenation for us.
575     std::vector<Value*> vals;
576     vals.push_back(dest); // destination
577     vals.push_back(src); // source
578     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
579     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
580     new CallInst(SLC.get_memcpy(), vals, "", ci);
581
582     // Finally, substitute the first operand of the strcat call for the 
583     // strcat call itself since strcat returns its first operand; and, 
584     // kill the strcat CallInst.
585     ci->replaceAllUsesWith(dest);
586     ci->eraseFromParent();
587     return true;
588   }
589 } StrCpyOptimizer;
590
591 /// This LibCallOptimization will simplify a call to the strlen library 
592 /// function by replacing it with a constant value if the string provided to 
593 /// it is a constant array.
594 /// @brief Simplify the strlen library function.
595 struct StrLenOptimization : public LibCallOptimization
596 {
597   StrLenOptimization() : LibCallOptimization("strlen") {}
598   virtual ~StrLenOptimization() {}
599
600   /// @brief Make sure that the "strlen" function has the right prototype
601   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
602   {
603     if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
604       if (f->arg_size() == 1) 
605         if (Function::const_arg_iterator AI = f->arg_begin())
606           if (AI->getType() == PointerType::get(Type::SByteTy))
607             return true;
608     return false;
609   }
610
611   /// @brief Perform the strlen optimization
612   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
613   {
614     // Get the length of the string
615     uint64_t len = 0;
616     if (!getConstantStringLength(ci->getOperand(1),len))
617       return false;
618
619     ci->replaceAllUsesWith(
620         ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
621     ci->eraseFromParent();
622     return true;
623   }
624 } StrLenOptimizer;
625
626 /// This LibCallOptimization will simplify a call to the memcpy library 
627 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8 
628 /// bytes depending on the length of the string and the alignment. Additional
629 /// optimizations are possible in code generation (sequence of immediate store)
630 /// @brief Simplify the memcpy library function.
631 struct MemCpyOptimization : public LibCallOptimization
632 {
633   /// @brief Default Constructor
634   MemCpyOptimization() : LibCallOptimization("llvm.memcpy") {}
635 protected:
636   /// @brief Subclass Constructor 
637   MemCpyOptimization(const char* fname) : LibCallOptimization(fname) {}
638 public:
639   /// @brief Destructor
640   virtual ~MemCpyOptimization() {}
641
642   /// @brief Make sure that the "memcpy" function has the right prototype
643   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
644   {
645     // Just make sure this has 4 arguments per LLVM spec.
646     return (f->arg_size() == 4);
647   }
648
649   /// Because of alignment and instruction information that we don't have, we
650   /// leave the bulk of this to the code generators. The optimization here just
651   /// deals with a few degenerate cases where the length of the string and the
652   /// alignment match the sizes of our intrinsic types so we can do a load and
653   /// store instead of the memcpy call.
654   /// @brief Perform the memcpy optimization.
655   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
656   {
657     // Make sure we have constant int values to work with
658     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
659     if (!LEN)
660       return false;
661     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
662     if (!ALIGN)
663       return false;
664
665     // If the length is larger than the alignment, we can't optimize
666     uint64_t len = LEN->getRawValue();
667     uint64_t alignment = ALIGN->getRawValue();
668     if (len > alignment)
669       return false;
670
671     // Get the type we will cast to, based on size of the string
672     Value* dest = ci->getOperand(1);
673     Value* src = ci->getOperand(2);
674     Type* castType = 0;
675     switch (len)
676     {
677       case 0:
678         // memcpy(d,s,0,a) -> noop
679         ci->eraseFromParent();
680         return true;
681       case 1: castType = Type::SByteTy; break;
682       case 2: castType = Type::ShortTy; break;
683       case 4: castType = Type::IntTy; break;
684       case 8: castType = Type::LongTy; break;
685       default:
686         return false;
687     }
688
689     // Cast source and dest to the right sized primitive and then load/store
690     CastInst* SrcCast = 
691       new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
692     CastInst* DestCast = 
693       new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
694     LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
695     StoreInst* SI = new StoreInst(LI, DestCast, ci);
696     ci->eraseFromParent();
697     return true;
698   }
699 } MemCpyOptimizer;
700
701 /// This LibCallOptimization will simplify a call to the memmove library 
702 /// function. It is identical to MemCopyOptimization except for the name of 
703 /// the intrinsic.
704 /// @brief Simplify the memmove library function.
705 struct MemMoveOptimization : public MemCpyOptimization
706 {
707   /// @brief Default Constructor
708   MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
709
710 } MemMoveOptimizer;
711
712 /// This LibCallOptimization will simplify calls to the "pow" library 
713 /// function. It looks for cases where the result of pow is well known and 
714 /// substitutes the appropriate value.
715 /// @brief Simplify the pow library function.
716 struct PowOptimization : public LibCallOptimization
717 {
718 public:
719   /// @brief Default Constructor
720   PowOptimization() : LibCallOptimization("pow") {}
721   /// @brief Destructor
722   virtual ~PowOptimization() {}
723
724   /// @brief Make sure that the "pow" function has the right prototype
725   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
726   {
727     // Just make sure this has 2 arguments
728     return (f->arg_size() == 2);
729   }
730
731   /// @brief Perform the pow optimization.
732   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
733   {
734     const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
735     Value* base = ci->getOperand(1);
736     Value* expn = ci->getOperand(2);
737     if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
738       double Op1V = Op1->getValue();
739       if (Op1V == 1.0)
740       {
741         // pow(1.0,x) -> 1.0
742         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
743         ci->eraseFromParent();
744         return true;
745       }
746     } 
747     else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) 
748     {
749       double Op2V = Op2->getValue();
750       if (Op2V == 0.0)
751       {
752         // pow(x,0.0) -> 1.0
753         ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
754         ci->eraseFromParent();
755         return true;
756       }
757       else if (Op2V == 0.5)
758       {
759         // pow(x,0.5) -> sqrt(x)
760         CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
761             ci->getName()+".pow",ci);
762         ci->replaceAllUsesWith(sqrt_inst);
763         ci->eraseFromParent();
764         return true;
765       }
766       else if (Op2V == 1.0)
767       {
768         // pow(x,1.0) -> x
769         ci->replaceAllUsesWith(base);
770         ci->eraseFromParent();
771         return true;
772       }
773       else if (Op2V == -1.0)
774       {
775         // pow(x,-1.0)    -> 1.0/x
776         BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
777           ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
778         ci->replaceAllUsesWith(div_inst);
779         ci->eraseFromParent();
780         return true;
781       }
782     }
783     return false; // opt failed
784   }
785 } PowOptimizer;
786
787 /// This LibCallOptimization will simplify calls to the "fputs" library 
788 /// function. It looks for cases where the result of fputs is not used and the
789 /// operation can be reduced to something simpler.
790 /// @brief Simplify the pow library function.
791 struct PutsOptimization : public LibCallOptimization
792 {
793 public:
794   /// @brief Default Constructor
795   PutsOptimization() : LibCallOptimization("fputs") {}
796
797   /// @brief Destructor
798   virtual ~PutsOptimization() {}
799
800   /// @brief Make sure that the "fputs" function has the right prototype
801   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
802   {
803     // Just make sure this has 2 arguments
804     return (f->arg_size() == 2);
805   }
806
807   /// @brief Perform the fputs optimization.
808   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
809   {
810     // If the result is used, none of these optimizations work
811     if (!ci->hasNUses(0)) 
812       return false;
813
814     // All the optimizations depend on the length of the first argument and the
815     // fact that it is a constant string array. Check that now
816     uint64_t len = 0; 
817     if (!getConstantStringLength(ci->getOperand(1), len))
818       return false;
819
820     switch (len)
821     {
822       case 0:
823         // fputs("",F) -> noop
824         break;
825       case 1:
826       {
827         // fputs(s,F)  -> fputc(s[0],F)  (if s is constant and strlen(s) == 1)
828         Function* fputc_func = SLC.get_fputc();
829         if (!fputc_func)
830           return false;
831         LoadInst* loadi = new LoadInst(ci->getOperand(1),
832           ci->getOperand(1)->getName()+".byte",ci);
833         CastInst* casti = new CastInst(loadi,Type::IntTy,
834           loadi->getName()+".int",ci);
835         new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
836         break;
837       }
838       default:
839       {  
840         // fputs(s,F)  -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
841         Function* fwrite_func = SLC.get_fwrite();
842         if (!fwrite_func)
843           return false;
844         std::vector<Value*> parms;
845         parms.push_back(ci->getOperand(1));
846         parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
847         parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
848         parms.push_back(ci->getOperand(2));
849         new CallInst(fwrite_func,parms,"",ci);
850         break;
851       }
852     }
853     ci->eraseFromParent();
854     return true; // success
855   }
856 } PutsOptimizer;
857
858 /// A function to compute the length of a null-terminated constant array of
859 /// integers.  This function can't rely on the size of the constant array 
860 /// because there could be a null terminator in the middle of the array. 
861 /// We also have to bail out if we find a non-integer constant initializer 
862 /// of one of the elements or if there is no null-terminator. The logic 
863 /// below checks each of these conditions and will return true only if all
864 /// conditions are met. In that case, the \p len parameter is set to the length
865 /// of the null-terminated string. If false is returned, the conditions were
866 /// not met and len is set to 0.
867 /// @brief Get the length of a constant string (null-terminated array).
868 bool getConstantStringLength(Value* V, uint64_t& len )
869 {
870   assert(V != 0 && "Invalid args to getConstantStringLength");
871   len = 0; // make sure we initialize this 
872   User* GEP = 0;
873   // If the value is not a GEP instruction nor a constant expression with a 
874   // GEP instruction, then return false because ConstantArray can't occur 
875   // any other way
876   if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
877     GEP = GEPI;
878   else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
879     if (CE->getOpcode() == Instruction::GetElementPtr)
880       GEP = CE;
881     else
882       return false;
883   else
884     return false;
885
886   // Make sure the GEP has exactly three arguments.
887   if (GEP->getNumOperands() != 3)
888     return false;
889
890   // Check to make sure that the first operand of the GEP is an integer and
891   // has value 0 so that we are sure we're indexing into the initializer. 
892   if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
893   {
894     if (!op1->isNullValue())
895       return false;
896   }
897   else
898     return false;
899
900   // Ensure that the second operand is a ConstantInt. If it isn't then this
901   // GEP is wonky and we're not really sure what were referencing into and 
902   // better of not optimizing it. While we're at it, get the second index
903   // value. We'll need this later for indexing the ConstantArray.
904   uint64_t start_idx = 0;
905   if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
906     start_idx = CI->getRawValue();
907   else
908     return false;
909
910   // The GEP instruction, constant or instruction, must reference a global
911   // variable that is a constant and is initialized. The referenced constant
912   // initializer is the array that we'll use for optimization.
913   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
914   if (!GV || !GV->isConstant() || !GV->hasInitializer())
915     return false;
916
917   // Get the initializer.
918   Constant* INTLZR = GV->getInitializer();
919
920   // Handle the ConstantAggregateZero case
921   if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
922   {
923     // This is a degenerate case. The initializer is constant zero so the
924     // length of the string must be zero.
925     len = 0;
926     return true;
927   }
928
929   // Must be a Constant Array
930   ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
931   if (!A)
932     return false;
933
934   // Get the number of elements in the array
935   uint64_t max_elems = A->getType()->getNumElements();
936
937   // Traverse the constant array from start_idx (derived above) which is
938   // the place the GEP refers to in the array. 
939   for ( len = start_idx; len < max_elems; len++)
940   {
941     if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
942     {
943       // Check for the null terminator
944       if (CI->isNullValue())
945         break; // we found end of string
946     }
947     else
948       return false; // This array isn't suitable, non-int initializer
949   }
950   if (len >= max_elems)
951     return false; // This array isn't null terminated
952
953   // Subtract out the initial value from the length
954   len -= start_idx;
955   return true; // success!
956 }
957
958 // TODO: 
959 //   Additional cases that we need to add to this file:
960 //
961 // cbrt:
962 //   * cbrt(expN(X))  -> expN(x/3)
963 //   * cbrt(sqrt(x))  -> pow(x,1/6)
964 //   * cbrt(sqrt(x))  -> pow(x,1/9)
965 //
966 // cos, cosf, cosl:
967 //   * cos(-x)  -> cos(x)
968 //
969 // exp, expf, expl:
970 //   * exp(log(x))  -> x
971 //
972 // ffs, ffsl, ffsll:
973 //   * ffs(cnst)     -> cnst'
974 //
975 // fprintf:
976 //   * fprintf(file,fmt) -> fputs(fmt,file) 
977 //       (if fmt is constant and constains no % characters)
978 //   * fprintf(file,"%s",str) -> fputs(orig,str)
979 //       (only if the fprintf result is not used)
980 //   * fprintf(file,"%c",chr) -> fputc(chr,file)
981 //
982 // isascii:
983 //   * isascii(c)    -> ((c & ~0x7f) == 0)
984 //   
985 // isdigit:
986 //   * isdigit(c)    -> (unsigned)(c) - '0' <= 9
987 //
988 // log, logf, logl:
989 //   * log(exp(x))   -> x
990 //   * log(x**y)     -> y*log(x)
991 //   * log(exp(y))   -> y*log(e)
992 //   * log(exp2(y))  -> y*log(2)
993 //   * log(exp10(y)) -> y*log(10)
994 //   * log(sqrt(x))  -> 0.5*log(x)
995 //   * log(pow(x,y)) -> y*log(x)
996 //
997 // lround, lroundf, lroundl:
998 //   * lround(cnst) -> cnst'
999 //
1000 // memcmp:
1001 //   * memcmp(s1,s2,0) -> 0
1002 //   * memcmp(x,x,l)   -> 0
1003 //   * memcmp(x,y,l)   -> cnst
1004 //      (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1005 //   * memcpy(x,y,1)   -> *x - *y
1006 //
1007 // memmove:
1008 //   * memmove(d,s,l,a) -> memcpy(d,s,l,a) 
1009 //       (if s is a global constant array)
1010 //
1011 // memset:
1012 //   * memset(s,c,0) -> noop
1013 //   * memset(s,c,n) -> store s, c
1014 //      (for n=1,2,4,8)
1015 //
1016 // pow, powf, powl:
1017 //   * pow(exp(x),y)  -> exp(x*y)
1018 //   * pow(sqrt(x),y) -> pow(x,y*0.5)
1019 //   * pow(pow(x,y),z)-> pow(x,y*z)
1020 //
1021 // puts:
1022 //   * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1023 //
1024 // round, roundf, roundl:
1025 //   * round(cnst) -> cnst'
1026 //
1027 // signbit:
1028 //   * signbit(cnst) -> cnst'
1029 //   * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1030 //
1031 // sprintf:
1032 //   * sprintf(dest,fmt) -> strcpy(dest,fmt) 
1033 //       (if fmt is constant and constains no % characters)
1034 //   * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1035 //       (only if the sprintf result is not used)
1036 //
1037 // sqrt, sqrtf, sqrtl:
1038 //   * sqrt(expN(x))  -> expN(x*0.5)
1039 //   * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1040 //   * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1041 //
1042 // strchr, strrchr:
1043 //   * strchr(s,c)  -> offset_of_in(c,s)
1044 //      (if c is a constant integer and s is a constant string)
1045 //   * strrchr(s,c) -> reverse_offset_of_in(c,s)
1046 //      (if c is a constant integer and s is a constant string)
1047 //   * strrchr(s1,0) -> strchr(s1,0)
1048 //
1049 // strcmp:
1050 //   * strcmp(x,x)  -> 0
1051 //   * strcmp(x,"") -> *x
1052 //   * strcmp("",x) -> *x
1053 //   * strcmp(x,y)  -> cnst  (if both x and y are constant strings)
1054 //
1055 // strncat:
1056 //   * strncat(x,y,0) -> x
1057 //   * strncat(x,y,0) -> x (if strlen(y) = 0)
1058 //   * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1059 //
1060 // strncmp:
1061 //   * strncmp(x,y,0)   -> 0
1062 //   * strncmp(x,x,l)   -> 0
1063 //   * strncmp(x,"",l)  -> *x
1064 //   * strncmp("",x,l)  -> *x
1065 //   * strncmp(x,y,1)   -> *x - *y
1066 //
1067 // strncpy:
1068 //   * strncpy(d,s,0) -> d
1069 //   * strncpy(d,s,l) -> memcpy(d,s,l,1)
1070 //      (if s and l are constants)
1071 //
1072 // strpbrk:
1073 //   * strpbrk(s,a) -> offset_in_for(s,a)
1074 //      (if s and a are both constant strings)
1075 //   * strpbrk(s,"") -> 0
1076 //   * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1077 //
1078 // strspn, strcspn:
1079 //   * strspn(s,a)   -> const_int (if both args are constant)
1080 //   * strspn("",a)  -> 0
1081 //   * strspn(s,"")  -> 0
1082 //   * strcspn(s,a)  -> const_int (if both args are constant)
1083 //   * strcspn("",a) -> 0
1084 //   * strcspn(s,"") -> strlen(a)
1085 //
1086 // strstr:
1087 //   * strstr(x,x)  -> x
1088 //   * strstr(s1,s2) -> offset_of_s2_in(s1)  
1089 //       (if s1 and s2 are constant strings)
1090 //    
1091 // tan, tanf, tanl:
1092 //   * tan(atan(x)) -> x
1093 // 
1094 // toascii:
1095 //   * toascii(c)   -> (c & 0x7f)
1096 //
1097 // trunc, truncf, truncl:
1098 //   * trunc(cnst) -> cnst'
1099 //
1100 // 
1101 }