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