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