Doxygenate.
[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 struct LibCallOptimization
63 {
64   /// The \p fname argument must be the name of the library function being 
65   /// optimized by the subclass.
66   /// @brief Constructor that registers the optimization.
67   LibCallOptimization(const char * fname )
68     : func_name(fname)
69 #ifndef NDEBUG
70     , stat_name(std::string("simplify-libcalls:")+fname)
71     , occurrences(stat_name.c_str(),"Number of calls simplified") 
72 #endif
73   {
74     // Register this call optimizer in the optlist (a hash_map)
75     optlist[func_name] = this;
76   }
77
78   /// @brief Deregister from the optlist
79   virtual ~LibCallOptimization() { optlist.erase(func_name); }
80
81   /// The implementation of this function in subclasses should determine if
82   /// \p F is suitable for the optimization. This method is called by 
83   /// SimplifyLibCalls::runOnModule to short circuit visiting all the call 
84   /// sites of such a function if that function is not suitable in the first 
85   /// place.  If the called function is suitabe, this method should return true;
86   /// false, otherwise. This function should also perform any lazy 
87   /// initialization that the LibCallOptimization needs to do, if its to return 
88   /// true. This avoids doing initialization until the optimizer is actually
89   /// going to be called upon to do some optimization.
90   /// @brief Determine if the function is suitable for optimization
91   virtual bool ValidateCalledFunction(
92     const Function* F,    ///< The function that is the target of call sites
93     SimplifyLibCalls& SLC ///< The pass object invoking us
94   ) = 0;
95
96   /// The implementations of this function in subclasses is the heart of the 
97   /// SimplifyLibCalls algorithm. Sublcasses of this class implement 
98   /// OptimizeCall to determine if (a) the conditions are right for optimizing
99   /// the call and (b) to perform the optimization. If an action is taken 
100   /// against ci, the subclass is responsible for returning true and ensuring
101   /// that ci is erased from its parent.
102   /// @brief Optimize a call, if possible.
103   virtual bool OptimizeCall(
104     CallInst* ci,          ///< The call instruction that should be optimized.
105     SimplifyLibCalls& SLC  ///< The pass object invoking us
106   ) = 0;
107
108   /// @brief Get the name of the library call being optimized
109   const char * getFunctionName() const { return func_name; }
110
111 #ifndef NDEBUG
112   /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
113   void succeeded() { ++occurrences; }
114 #endif
115
116 private:
117   const char* func_name; ///< Name of the library call we optimize
118 #ifndef NDEBUG
119   std::string stat_name; ///< Holder for debug statistic name
120   Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
121 #endif
122 };
123
124 /// This class is an LLVM Pass that applies each of the LibCallOptimization 
125 /// instances to all the call sites in a module, relatively efficiently. The
126 /// purpose of this pass is to provide optimizations for calls to well-known 
127 /// functions with well-known semantics, such as those in the c library. The
128 /// class provides the basic infrastructure for handling runOnModule.  Whenever /// this pass finds a function call, it asks the appropriate optimizer to 
129 /// validate the call (ValidateLibraryCall). If it is validated, then
130 /// the OptimizeCall method is also called.
131 /// @brief A ModulePass for optimizing well-known function calls.
132 struct SimplifyLibCalls : public ModulePass 
133 {
134   /// We need some target data for accurate signature details that are
135   /// target dependent. So we require target data in our AnalysisUsage.
136   /// @brief Require TargetData from AnalysisUsage.
137   virtual void getAnalysisUsage(AnalysisUsage& Info) const
138   {
139     // Ask that the TargetData analysis be performed before us so we can use
140     // the target data.
141     Info.addRequired<TargetData>();
142   }
143
144   /// For this pass, process all of the function calls in the module, calling
145   /// ValidateLibraryCall and OptimizeCall as appropriate.
146   /// @brief Run all the lib call optimizations on a Module.
147   virtual bool runOnModule(Module &M)
148   {
149     reset(M);
150
151     bool result = false;
152
153     // The call optimizations can be recursive. That is, the optimization might
154     // generate a call to another function which can also be optimized. This way
155     // we make the LibCallOptimization instances very specific to the case they 
156     // handle. It also means we need to keep running over the function calls in 
157     // the module until we don't get any more optimizations possible.
158     bool found_optimization = false;
159     do
160     {
161       found_optimization = false;
162       for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
163       {
164         // All the "well-known" functions are external and have external linkage
165         // because they live in a runtime library somewhere and were (probably) 
166         // not compiled by LLVM.  So, we only act on external functions that have 
167         // external linkage and non-empty uses.
168         if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
169           continue;
170
171         // Get the optimization class that pertains to this function
172         LibCallOptimization* CO = optlist[FI->getName().c_str()];
173         if (!CO)
174           continue;
175
176         // Make sure the called function is suitable for the optimization
177         if (!CO->ValidateCalledFunction(FI,*this))
178           continue;
179
180         // Loop over each of the uses of the function
181         for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end(); 
182              UI != UE ; )
183         {
184           // If the use of the function is a call instruction
185           if (CallInst* CI = dyn_cast<CallInst>(*UI++))
186           {
187             // Do the optimization on the LibCallOptimization.
188             if (CO->OptimizeCall(CI,*this))
189             {
190               ++SimplifiedLibCalls;
191               found_optimization = result = true;
192 #ifndef NDEBUG
193               CO->succeeded();
194 #endif
195             }
196           }
197         }
198       }
199     } while (found_optimization);
200     return result;
201   }
202
203   /// @brief Return the *current* module we're working on.
204   Module* getModule() { return M; }
205
206   /// @brief Return the *current* target data for the module we're working on.
207   TargetData* getTargetData() { return TD; }
208
209   /// @brief Return a Function* for the strlen libcall
210   Function* get_strlen()
211   {
212     if (!strlen_func)
213     {
214       std::vector<const Type*> args;
215       args.push_back(PointerType::get(Type::SByteTy));
216       FunctionType* strlen_type = 
217         FunctionType::get(TD->getIntPtrType(), args, false);
218       strlen_func = M->getOrInsertFunction("strlen",strlen_type);
219     }
220     return strlen_func;
221   }
222
223   /// @brief Return a Function* for the memcpy libcall
224   Function* get_memcpy()
225   {
226     if (!memcpy_func)
227     {
228       // Note: this is for llvm.memcpy intrinsic
229       std::vector<const Type*> args;
230       args.push_back(PointerType::get(Type::SByteTy));
231       args.push_back(PointerType::get(Type::SByteTy));
232       args.push_back(Type::IntTy);
233       args.push_back(Type::IntTy);
234       FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
235       memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
236     }
237     return memcpy_func;
238   }
239
240 private:
241   /// @brief Reset our cached data for a new Module
242   void reset(Module& mod)
243   {
244     M = &mod;
245     TD = &getAnalysis<TargetData>();
246     memcpy_func = 0;
247     strlen_func = 0;
248   }
249
250 private:
251   Function* memcpy_func; ///< Cached llvm.memcpy function
252   Function* strlen_func; ///< Cached strlen function
253   Module* M;             ///< Cached Module
254   TargetData* TD;        ///< Cached TargetData
255 };
256
257 // Register the pass
258 RegisterOpt<SimplifyLibCalls> 
259 X("simplify-libcalls","Simplify well-known library calls");
260
261 } // anonymous namespace
262
263 // The only public symbol in this file which just instantiates the pass object
264 ModulePass *llvm::createSimplifyLibCallsPass() 
265
266   return new SimplifyLibCalls(); 
267 }
268
269 // Classes below here, in the anonymous namespace, are all subclasses of the
270 // LibCallOptimization class, each implementing all optimizations possible for a
271 // single well-known library call. Each has a static singleton instance that
272 // auto registers it into the "optlist" global above. 
273 namespace {
274
275 // Forward declare a utility function.
276 bool getConstantStringLength(Value* V, uint64_t& len );
277
278 /// This LibCallOptimization will find instances of a call to "exit" that occurs
279 /// within the "main" function and change it to a simple "ret" instruction with
280 /// the same value passed to the exit function. When this is done, it splits the
281 /// basic block at the exit(3) call and deletes the call instruction.
282 /// @brief Replace calls to exit in main with a simple return
283 struct ExitInMainOptimization : public LibCallOptimization
284 {
285   ExitInMainOptimization() : LibCallOptimization("exit") {}
286   virtual ~ExitInMainOptimization() {}
287
288   // Make sure the called function looks like exit (int argument, int return
289   // type, external linkage, not varargs). 
290   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
291   {
292     if (f->arg_size() >= 1)
293       if (f->arg_begin()->getType()->isInteger())
294         return true;
295     return false;
296   }
297
298   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
299   {
300     // To be careful, we check that the call to exit is coming from "main", that
301     // main has external linkage, and the return type of main and the argument
302     // to exit have the same type. 
303     Function *from = ci->getParent()->getParent();
304     if (from->hasExternalLinkage())
305       if (from->getReturnType() == ci->getOperand(1)->getType())
306         if (from->getName() == "main")
307         {
308           // Okay, time to actually do the optimization. First, get the basic 
309           // block of the call instruction
310           BasicBlock* bb = ci->getParent();
311
312           // Create a return instruction that we'll replace the call with. 
313           // Note that the argument of the return is the argument of the call 
314           // instruction.
315           ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
316
317           // Split the block at the call instruction which places it in a new
318           // basic block.
319           bb->splitBasicBlock(ci);
320
321           // The block split caused a branch instruction to be inserted into
322           // the end of the original block, right after the return instruction
323           // that we put there. That's not a valid block, so delete the branch
324           // instruction.
325           bb->getInstList().pop_back();
326
327           // Now we can finally get rid of the call instruction which now lives
328           // in the new basic block.
329           ci->eraseFromParent();
330
331           // Optimization succeeded, return true.
332           return true;
333         }
334     // We didn't pass the criteria for this optimization so return false
335     return false;
336   }
337 } ExitInMainOptimizer;
338
339 /// This LibCallOptimization will simplify a call to the strcat library 
340 /// function. The simplification is possible only if the string being 
341 /// concatenated is a constant array or a constant expression that results in 
342 /// a constant string. In this case we can replace it with strlen + llvm.memcpy 
343 /// of the constant string. Both of these calls are further reduced, if possible
344 /// on subsequent passes.
345 /// @brief Simplify the strcat library function.
346 struct StrCatOptimization : public LibCallOptimization
347 {
348 public:
349   /// @brief Default constructor
350   StrCatOptimization() : LibCallOptimization("strcat") {}
351
352 public:
353   /// @breif  Destructor
354   virtual ~StrCatOptimization() {}
355
356   /// @brief Make sure that the "strcat" function has the right prototype
357   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
358   {
359     if (f->getReturnType() == PointerType::get(Type::SByteTy))
360       if (f->arg_size() == 2) 
361       {
362         Function::const_arg_iterator AI = f->arg_begin();
363         if (AI++->getType() == PointerType::get(Type::SByteTy))
364           if (AI->getType() == PointerType::get(Type::SByteTy))
365           {
366             // Indicate this is a suitable call type.
367             return true;
368           }
369       }
370     return false;
371   }
372
373   /// @brief Optimize the strcat library function
374   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
375   {
376     // Extract some information from the instruction
377     Module* M = ci->getParent()->getParent()->getParent();
378     Value* dest = ci->getOperand(1);
379     Value* src  = ci->getOperand(2);
380
381     // Extract the initializer (while making numerous checks) from the 
382     // source operand of the call to strcat. If we get null back, one of
383     // a variety of checks in get_GVInitializer failed
384     uint64_t len = 0;
385     if (!getConstantStringLength(src,len))
386       return false;
387
388     // Handle the simple, do-nothing case
389     if (len == 0)
390     {
391       ci->replaceAllUsesWith(dest);
392       ci->eraseFromParent();
393       return true;
394     }
395
396     // Increment the length because we actually want to memcpy the null
397     // terminator as well.
398     len++;
399
400
401     // We need to find the end of the destination string.  That's where the 
402     // memory is to be moved to. We just generate a call to strlen (further 
403     // optimized in another pass).  Note that the SLC.get_strlen() call 
404     // caches the Function* for us.
405     CallInst* strlen_inst = 
406       new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
407
408     // Now that we have the destination's length, we must index into the 
409     // destination's pointer to get the actual memcpy destination (end of
410     // the string .. we're concatenating).
411     std::vector<Value*> idx;
412     idx.push_back(strlen_inst);
413     GetElementPtrInst* gep = 
414       new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
415
416     // We have enough information to now generate the memcpy call to
417     // do the concatenation for us.
418     std::vector<Value*> vals;
419     vals.push_back(gep); // destination
420     vals.push_back(ci->getOperand(2)); // source
421     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
422     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
423     new CallInst(SLC.get_memcpy(), vals, "", ci);
424
425     // Finally, substitute the first operand of the strcat call for the 
426     // strcat call itself since strcat returns its first operand; and, 
427     // kill the strcat CallInst.
428     ci->replaceAllUsesWith(dest);
429     ci->eraseFromParent();
430     return true;
431   }
432 } StrCatOptimizer;
433
434 /// This LibCallOptimization will simplify a call to the strcpy library 
435 /// function.  Two optimizations are possible: 
436 /// (1) If src and dest are the same and not volatile, just return dest
437 /// (2) If the src is a constant then we can convert to llvm.memmove
438 /// @brief Simplify the strcpy library function.
439 struct StrCpyOptimization : public LibCallOptimization
440 {
441 public:
442   StrCpyOptimization() : LibCallOptimization("strcpy") {}
443   virtual ~StrCpyOptimization() {}
444
445   /// @brief Make sure that the "strcpy" function has the right prototype
446   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC) 
447   {
448     if (f->getReturnType() == PointerType::get(Type::SByteTy))
449       if (f->arg_size() == 2) 
450       {
451         Function::const_arg_iterator AI = f->arg_begin();
452         if (AI++->getType() == PointerType::get(Type::SByteTy))
453           if (AI->getType() == PointerType::get(Type::SByteTy))
454           {
455             // Indicate this is a suitable call type.
456             return true;
457           }
458       }
459     return false;
460   }
461
462   /// @brief Perform the strcpy optimization
463   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
464   {
465     // First, check to see if src and destination are the same. If they are,
466     // then the optimization is to replace the CallInst with the destination
467     // because the call is a no-op. Note that this corresponds to the 
468     // degenerate strcpy(X,X) case which should have "undefined" results
469     // according to the C specification. However, it occurs sometimes and
470     // we optimize it as a no-op.
471     Value* dest = ci->getOperand(1);
472     Value* src = ci->getOperand(2);
473     if (dest == src)
474     {
475       ci->replaceAllUsesWith(dest);
476       ci->eraseFromParent();
477       return true;
478     }
479     
480     // Get the length of the constant string referenced by the second operand,
481     // the "src" parameter. Fail the optimization if we can't get the length
482     // (note that getConstantStringLength does lots of checks to make sure this
483     // is valid).
484     uint64_t len = 0;
485     if (!getConstantStringLength(ci->getOperand(2),len))
486       return false;
487
488     // If the constant string's length is zero we can optimize this by just
489     // doing a store of 0 at the first byte of the destination
490     if (len == 0)
491     {
492       new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
493       ci->replaceAllUsesWith(dest);
494       ci->eraseFromParent();
495       return true;
496     }
497
498     // Increment the length because we actually want to memcpy the null
499     // terminator as well.
500     len++;
501
502     // Extract some information from the instruction
503     Module* M = ci->getParent()->getParent()->getParent();
504
505     // We have enough information to now generate the memcpy call to
506     // do the concatenation for us.
507     std::vector<Value*> vals;
508     vals.push_back(dest); // destination
509     vals.push_back(src); // source
510     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
511     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
512     new CallInst(SLC.get_memcpy(), vals, "", ci);
513
514     // Finally, substitute the first operand of the strcat call for the 
515     // strcat call itself since strcat returns its first operand; and, 
516     // kill the strcat CallInst.
517     ci->replaceAllUsesWith(dest);
518     ci->eraseFromParent();
519     return true;
520   }
521 } StrCpyOptimizer;
522
523 /// This LibCallOptimization will simplify a call to the strlen library 
524 /// function by replacing it with a constant value if the string provided to 
525 /// it is a constant array.
526 /// @brief Simplify the strlen library function.
527 struct StrLenOptimization : public LibCallOptimization
528 {
529   StrLenOptimization() : LibCallOptimization("strlen") {}
530   virtual ~StrLenOptimization() {}
531
532   /// @brief Make sure that the "strlen" function has the right prototype
533   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
534   {
535     if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
536       if (f->arg_size() == 1) 
537         if (Function::const_arg_iterator AI = f->arg_begin())
538           if (AI->getType() == PointerType::get(Type::SByteTy))
539             return true;
540     return false;
541   }
542
543   /// @brief Perform the strlen optimization
544   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
545   {
546     // Get the length of the string
547     uint64_t len = 0;
548     if (!getConstantStringLength(ci->getOperand(1),len))
549       return false;
550
551     ci->replaceAllUsesWith(
552         ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
553     ci->eraseFromParent();
554     return true;
555   }
556 } StrLenOptimizer;
557
558 /// This LibCallOptimization will simplify a call to the memcpy library 
559 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8 
560 /// bytes depending on the length of the string and the alignment. Additional
561 /// optimizations are possible in code generation (sequence of immediate store)
562 /// @brief Simplify the memcpy library function.
563 struct MemCpyOptimization : public LibCallOptimization
564 {
565   /// @brief Default Constructor
566   MemCpyOptimization() : LibCallOptimization("llvm.memcpy") {}
567 protected:
568   /// @brief Subclass Constructor 
569   MemCpyOptimization(const char* fname) : LibCallOptimization(fname) {}
570 public:
571   /// @brief Destructor
572   virtual ~MemCpyOptimization() {}
573
574   /// @brief Make sure that the "memcpy" function has the right prototype
575   virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
576   {
577     // Just make sure this has 4 arguments per LLVM spec.
578     return (f->arg_size() == 4);
579   }
580
581   /// Because of alignment and instruction information that we don't have, we
582   /// leave the bulk of this to the code generators. The optimization here just
583   /// deals with a few degenerate cases where the length of the string and the
584   /// alignment match the sizes of our intrinsic types so we can do a load and
585   /// store instead of the memcpy call.
586   /// @brief Perform the memcpy optimization.
587   virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
588   {
589     // Make sure we have constant int values to work with
590     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
591     if (!LEN)
592       return false;
593     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
594     if (!ALIGN)
595       return false;
596
597     // If the length is larger than the alignment, we can't optimize
598     uint64_t len = LEN->getRawValue();
599     uint64_t alignment = ALIGN->getRawValue();
600     if (len > alignment)
601       return false;
602
603     // Get the type we will cast to, based on size of the string
604     Value* dest = ci->getOperand(1);
605     Value* src = ci->getOperand(2);
606     Type* castType = 0;
607     switch (len)
608     {
609       case 0:
610         // The memcpy is a no-op so just dump its call.
611         ci->eraseFromParent();
612         return true;
613       case 1: castType = Type::SByteTy; break;
614       case 2: castType = Type::ShortTy; break;
615       case 4: castType = Type::IntTy; break;
616       case 8: castType = Type::LongTy; break;
617       default:
618         return false;
619     }
620
621     // Cast source and dest to the right sized primitive and then load/store
622     CastInst* SrcCast = 
623       new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
624     CastInst* DestCast = 
625       new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
626     LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
627     StoreInst* SI = new StoreInst(LI, DestCast, ci);
628     ci->eraseFromParent();
629     return true;
630   }
631 } MemCpyOptimizer;
632
633 /// This LibCallOptimization will simplify a call to the memmove library 
634 /// function. It is identical to MemCopyOptimization except for the name of 
635 /// the intrinsic.
636 /// @brief Simplify the memmove library function.
637 struct MemMoveOptimization : public MemCpyOptimization
638 {
639   /// @brief Default Constructor
640   MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
641
642 } MemMoveOptimizer;
643
644 /// A function to compute the length of a null-terminated constant array of
645 /// integers.  This function can't rely on the size of the constant array 
646 /// because there could be a null terminator in the middle of the array. 
647 /// We also have to bail out if we find a non-integer constant initializer 
648 /// of one of the elements or if there is no null-terminator. The logic 
649 /// below checks each of these conditions and will return true only if all
650 /// conditions are met. In that case, the \p len parameter is set to the length
651 /// of the null-terminated string. If false is returned, the conditions were
652 /// not met and len is set to 0.
653 /// @brief Get the length of a constant string (null-terminated array).
654 bool getConstantStringLength(Value* V, uint64_t& len )
655 {
656   assert(V != 0 && "Invalid args to getConstantStringLength");
657   len = 0; // make sure we initialize this 
658   User* GEP = 0;
659   // If the value is not a GEP instruction nor a constant expression with a 
660   // GEP instruction, then return false because ConstantArray can't occur 
661   // any other way
662   if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
663     GEP = GEPI;
664   else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
665     if (CE->getOpcode() == Instruction::GetElementPtr)
666       GEP = CE;
667     else
668       return false;
669   else
670     return false;
671
672   // Make sure the GEP has exactly three arguments.
673   if (GEP->getNumOperands() != 3)
674     return false;
675
676   // Check to make sure that the first operand of the GEP is an integer and
677   // has value 0 so that we are sure we're indexing into the initializer. 
678   if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
679   {
680     if (!op1->isNullValue())
681       return false;
682   }
683   else
684     return false;
685
686   // Ensure that the second operand is a ConstantInt. If it isn't then this
687   // GEP is wonky and we're not really sure what were referencing into and 
688   // better of not optimizing it. While we're at it, get the second index
689   // value. We'll need this later for indexing the ConstantArray.
690   uint64_t start_idx = 0;
691   if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
692     start_idx = CI->getRawValue();
693   else
694     return false;
695
696   // The GEP instruction, constant or instruction, must reference a global
697   // variable that is a constant and is initialized. The referenced constant
698   // initializer is the array that we'll use for optimization.
699   GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
700   if (!GV || !GV->isConstant() || !GV->hasInitializer())
701     return false;
702
703   // Get the initializer.
704   Constant* INTLZR = GV->getInitializer();
705
706   // Handle the ConstantAggregateZero case
707   if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
708   {
709     // This is a degenerate case. The initializer is constant zero so the
710     // length of the string must be zero.
711     len = 0;
712     return true;
713   }
714
715   // Must be a Constant Array
716   ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
717   if (!A)
718     return false;
719
720   // Get the number of elements in the array
721   uint64_t max_elems = A->getType()->getNumElements();
722
723   // Traverse the constant array from start_idx (derived above) which is
724   // the place the GEP refers to in the array. 
725   for ( len = start_idx; len < max_elems; len++)
726   {
727     if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
728     {
729       // Check for the null terminator
730       if (CI->isNullValue())
731         break; // we found end of string
732     }
733     else
734       return false; // This array isn't suitable, non-int initializer
735   }
736   if (len >= max_elems)
737     return false; // This array isn't null terminated
738
739   // Subtract out the initial value from the length
740   len -= start_idx;
741   return true; // success!
742 }
743
744 // TODO: Additional cases that we need to add to this file:
745 // 1. memmove -> memcpy if src is a global constant array
746 }