No, seriously folks, memcpy really does return void.
[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 #include "llvm/Transforms/IPO.h"
20 #include "llvm/Module.h"
21 #include "llvm/Pass.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Instructions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/hash_map"
27 #include "llvm/Target/TargetData.h"
28 #include <iostream>
29 using namespace llvm;
30
31 namespace {
32   Statistic<> SimplifiedLibCalls("simplified-lib-calls", 
33       "Number of well-known library calls simplified");
34
35   /// This class is the base class for a set of small but important 
36   /// optimizations of calls to well-known functions, such as those in the c
37   /// library. This class provides the basic infrastructure for handling 
38   /// runOnModule. Subclasses register themselves and provide two methods:
39   /// RecognizeCall and OptimizeCall. Whenever this class finds a function call,
40   /// it asks the subclasses to recognize the call. If it is recognized, then
41   /// the OptimizeCall method is called on that subclass instance. In this way
42   /// the subclasses implement the calling conditions on which they trigger and
43   /// the action to perform, making it easy to add new optimizations of this
44   /// form.
45   /// @brief A ModulePass for optimizing well-known function calls
46   struct SimplifyLibCalls : public ModulePass {
47
48     /// We need some target data for accurate signature details that are
49     /// target dependent. So we require target data in our AnalysisUsage.
50     virtual void getAnalysisUsage(AnalysisUsage& Info) const;
51
52     /// For this pass, process all of the function calls in the module, calling
53     /// RecognizeCall and OptimizeCall as appropriate.
54     virtual bool runOnModule(Module &M);
55
56   };
57
58   RegisterOpt<SimplifyLibCalls> 
59     X("simplify-libcalls","Simplify well-known library calls");
60
61   struct CallOptimizer
62   {
63     /// @brief Constructor that registers the optimization
64     CallOptimizer(const char * fname );
65
66     virtual ~CallOptimizer();
67
68     /// The implementation of this function in subclasses should determine if
69     /// \p F is suitable for the optimization. This method is called by 
70     /// runOnModule to short circuit visiting all the call sites of such a
71     /// function if that function is not suitable in the first place.
72     /// If the called function is suitabe, this method should return true;
73     /// false, otherwise. This function should also perform any lazy 
74     /// initialization that the CallOptimizer needs to do, if its to return 
75     /// true. This avoids doing initialization until the optimizer is actually
76     /// going to be called upon to do some optimization.
77     virtual bool ValidateCalledFunction(
78       const Function* F,   ///< The function that is the target of call sites
79       const TargetData& TD ///< Information about the target
80     ) = 0;
81
82     /// The implementations of this function in subclasses is the heart of the 
83     /// SimplifyLibCalls algorithm. Sublcasses of this class implement 
84     /// OptimizeCall to determine if (a) the conditions are right for optimizing
85     /// the call and (b) to perform the optimization. If an action is taken 
86     /// against ci, the subclass is responsible for returning true and ensuring
87     /// that ci is erased from its parent.
88     /// @param ci the call instruction under consideration
89     /// @param f the function that ci calls.
90     /// @brief Optimize a call, if possible.
91     virtual bool OptimizeCall(
92       CallInst* ci,         ///< The call instruction that should be optimized.
93       const TargetData& TD  ///< Information about the target
94     ) = 0;
95
96     const char * getFunctionName() const { return func_name; }
97   private:
98     const char* func_name;
99   };
100
101   /// @brief The list of optimizations deriving from CallOptimizer
102
103   hash_map<std::string,CallOptimizer*> optlist;
104
105   CallOptimizer::CallOptimizer(const char* fname)
106     : func_name(fname)
107   {
108     // Register this call optimizer
109     optlist[func_name] = this;
110   }
111
112   /// Make sure we get our virtual table in this file.
113   CallOptimizer::~CallOptimizer() { }
114
115 }
116
117 ModulePass *llvm::createSimplifyLibCallsPass() 
118
119   return new SimplifyLibCalls(); 
120 }
121
122 void SimplifyLibCalls::getAnalysisUsage(AnalysisUsage& Info) const
123 {
124   // Ask that the TargetData analysis be performed before us so we can use
125   // the target data.
126   Info.addRequired<TargetData>();
127 }
128
129 bool SimplifyLibCalls::runOnModule(Module &M) 
130 {
131   TargetData& TD = getAnalysis<TargetData>();
132
133   bool result = false;
134
135   // The call optimizations can be recursive. That is, the optimization might
136   // generate a call to another function which can also be optimized. This way
137   // we make the CallOptimizer instances very specific to the case they handle.
138   // It also means we need to keep running over the function calls in the module
139   // until we don't get any more optimizations possible.
140   bool found_optimization = false;
141   do
142   {
143     found_optimization = false;
144     for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
145     {
146       // All the "well-known" functions are external and have external linkage
147       // because they live in a runtime library somewhere and were (probably) 
148       // not compiled by LLVM.  So, we only act on external functions that have 
149       // external linkage and non-empty uses.
150       if (FI->isExternal() && FI->hasExternalLinkage() && !FI->use_empty())
151       {
152         // Get the optimization class that pertains to this function
153         if (CallOptimizer* CO = optlist[FI->getName().c_str()] )
154         {
155           // Make sure the called function is suitable for the optimization
156           if (CO->ValidateCalledFunction(FI,TD))
157           {
158             // Loop over each of the uses of the function
159             for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end(); 
160                  UI != UE ; )
161             {
162               // If the use of the function is a call instruction
163               if (CallInst* CI = dyn_cast<CallInst>(*UI++))
164               {
165                 // Do the optimization on the CallOptimizer.
166                 if (CO->OptimizeCall(CI,TD))
167                 {
168                   ++SimplifiedLibCalls;
169                   found_optimization = result = true;
170                 }
171               }
172             }
173           }
174         }
175       }
176     }
177   } while (found_optimization);
178   return result;
179 }
180
181 namespace {
182
183   /// Provide some functions for accessing standard library prototypes and
184   /// caching them so we don't have to keep recomputing them
185   FunctionType* get_strlen(const Type* IntPtrTy)
186   {
187     static FunctionType* strlen_type = 0;
188     if (!strlen_type)
189     {
190       std::vector<const Type*> args;
191       args.push_back(PointerType::get(Type::SByteTy));
192       strlen_type = FunctionType::get(IntPtrTy, args, false);
193     }
194     return strlen_type;
195   }
196
197   FunctionType* get_memcpy()
198   {
199     static FunctionType* memcpy_type = 0;
200     if (!memcpy_type)
201     {
202       // Note: this is for llvm.memcpy intrinsic
203       std::vector<const Type*> args;
204       args.push_back(PointerType::get(Type::SByteTy));
205       args.push_back(PointerType::get(Type::SByteTy));
206       args.push_back(Type::IntTy);
207       args.push_back(Type::IntTy);
208       memcpy_type = FunctionType::get(Type::VoidTy, args, false);
209     }
210     return memcpy_type;
211   }
212
213   /// A function to compute the length of a null-terminated string of integers.
214   /// This function can't rely on the size of the constant array because there 
215   /// could be a null terminator in the middle of the array. We also have to 
216   /// bail out if we find a non-integer constant initializer of one of the 
217   /// elements or if there is no null-terminator. The logic below checks
218   bool getConstantStringLength(Value* V, uint64_t& len )
219   {
220     assert(V != 0 && "Invalid args to getConstantStringLength");
221     len = 0; // make sure we initialize this 
222     User* GEP = 0;
223     // If the value is not a GEP instruction nor a constant expression with a 
224     // GEP instruction, then return false because ConstantArray can't occur 
225     // any other way
226     if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
227       GEP = GEPI;
228     else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
229       if (CE->getOpcode() == Instruction::GetElementPtr)
230         GEP = CE;
231       else
232         return false;
233     else
234       return false;
235
236     // Make sure the GEP has exactly three arguments.
237     if (GEP->getNumOperands() != 3)
238       return false;
239
240     // Check to make sure that the first operand of the GEP is an integer and
241     // has value 0 so that we are sure we're indexing into the initializer. 
242     if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
243     {
244       if (!op1->isNullValue())
245         return false;
246     }
247     else
248       return false;
249
250     // Ensure that the second operand is a ConstantInt. If it isn't then this
251     // GEP is wonky and we're not really sure what were referencing into and 
252     // better of not optimizing it. While we're at it, get the second index
253     // value. We'll need this later for indexing the ConstantArray.
254     uint64_t start_idx = 0;
255     if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
256       start_idx = CI->getRawValue();
257     else
258       return false;
259
260     // The GEP instruction, constant or instruction, must reference a global
261     // variable that is a constant and is initialized. The referenced constant
262     // initializer is the array that we'll use for optimization.
263     GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
264     if (!GV || !GV->isConstant() || !GV->hasInitializer())
265       return false;
266
267     // Get the initializer.
268     Constant* INTLZR = GV->getInitializer();
269
270     // Handle the ConstantAggregateZero case
271     if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
272     {
273       // This is a degenerate case. The initializer is constant zero so the
274       // length of the string must be zero.
275       len = 0;
276       return true;
277     }
278
279     // Must be a Constant Array
280     ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
281     if (!A)
282       return false;
283
284     // Get the number of elements in the array
285     uint64_t max_elems = A->getType()->getNumElements();
286
287     // Traverse the constant array from start_idx (derived above) which is
288     // the place the GEP refers to in the array. 
289     for ( len = start_idx; len < max_elems; len++)
290     {
291       if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
292       {
293         // Check for the null terminator
294         if (CI->isNullValue())
295           break; // we found end of string
296       }
297       else
298         return false; // This array isn't suitable, non-int initializer
299     }
300     if (len >= max_elems)
301       return false; // This array isn't null terminated
302
303     // Subtract out the initial value from the length
304     len -= start_idx;
305     return true; // success!
306   }
307
308 /// This CallOptimizer will find instances of a call to "exit" that occurs
309 /// within the "main" function and change it to a simple "ret" instruction with
310 /// the same value as passed to the exit function. It assumes that the 
311 /// instructions after the call to exit(3) can be deleted since they are 
312 /// unreachable anyway.
313 /// @brief Replace calls to exit in main with a simple return
314 struct ExitInMainOptimization : public CallOptimizer
315 {
316   ExitInMainOptimization() : CallOptimizer("exit") {}
317   virtual ~ExitInMainOptimization() {}
318
319   // Make sure the called function looks like exit (int argument, int return
320   // type, external linkage, not varargs). 
321   virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD)
322   {
323     if (f->arg_size() >= 1)
324       if (f->arg_begin()->getType()->isInteger())
325         return true;
326     return false;
327   }
328
329   virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
330   {
331     // To be careful, we check that the call to exit is coming from "main", that
332     // main has external linkage, and the return type of main and the argument
333     // to exit have the same type. 
334     Function *from = ci->getParent()->getParent();
335     if (from->hasExternalLinkage())
336       if (from->getReturnType() == ci->getOperand(1)->getType())
337         if (from->getName() == "main")
338         {
339           // Okay, time to actually do the optimization. First, get the basic 
340           // block of the call instruction
341           BasicBlock* bb = ci->getParent();
342
343           // Create a return instruction that we'll replace the call with. 
344           // Note that the argument of the return is the argument of the call 
345           // instruction.
346           ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
347
348           // Split the block at the call instruction which places it in a new
349           // basic block.
350           bb->splitBasicBlock(ci);
351
352           // The block split caused a branch instruction to be inserted into
353           // the end of the original block, right after the return instruction
354           // that we put there. That's not a valid block, so delete the branch
355           // instruction.
356           bb->getInstList().pop_back();
357
358           // Now we can finally get rid of the call instruction which now lives
359           // in the new basic block.
360           ci->eraseFromParent();
361
362           // Optimization succeeded, return true.
363           return true;
364         }
365     // We didn't pass the criteria for this optimization so return false
366     return false;
367   }
368 } ExitInMainOptimizer;
369
370 /// This CallOptimizer will simplify a call to the strcat library function. The
371 /// simplification is possible only if the string being concatenated is a 
372 /// constant array or a constant expression that results in a constant array. In
373 /// this case, if the array is small, we can generate a series of inline store
374 /// instructions to effect the concatenation without calling strcat.
375 /// @brief Simplify the strcat library function.
376 struct StrCatOptimization : public CallOptimizer
377 {
378 private:
379   Function* strlen_func;
380   Function* memcpy_func;
381 public:
382   StrCatOptimization() 
383     : CallOptimizer("strcat") 
384     , strlen_func(0)
385     , memcpy_func(0)
386     {}
387   virtual ~StrCatOptimization() {}
388
389   inline Function* get_strlen_func(Module*M,const Type* IntPtrTy)
390   {
391     if (strlen_func)
392       return strlen_func;
393     return strlen_func = M->getOrInsertFunction("strlen",get_strlen(IntPtrTy));
394   }
395
396   inline Function* get_memcpy_func(Module* M) 
397   {
398     if (memcpy_func)
399       return memcpy_func;
400     return memcpy_func = M->getOrInsertFunction("llvm.memcpy",get_memcpy());
401   }
402
403   /// @brief Make sure that the "strcat" function has the right prototype
404   virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD) 
405   {
406     if (f->getReturnType() == PointerType::get(Type::SByteTy))
407       if (f->arg_size() == 2) 
408       {
409         Function::const_arg_iterator AI = f->arg_begin();
410         if (AI++->getType() == PointerType::get(Type::SByteTy))
411           if (AI->getType() == PointerType::get(Type::SByteTy))
412           {
413             // Invalidate the pre-computed strlen_func and memcpy_func Functions
414             // because, by definition, this method is only called when a new
415             // Module is being traversed. Invalidation causes re-computation for
416             // the new Module (if necessary).
417             strlen_func = 0;
418             memcpy_func = 0;
419
420             // Indicate this is a suitable call type.
421             return true;
422           }
423       }
424     return false;
425   }
426
427   /// Perform the optimization if the length of the string concatenated
428   /// is reasonably short and it is a constant array.
429   virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
430   {
431     // Extract the initializer (while making numerous checks) from the 
432     // source operand of the call to strcat. If we get null back, one of
433     // a variety of checks in get_GVInitializer failed
434     uint64_t len = 0;
435     if (!getConstantStringLength(ci->getOperand(2),len))
436       return false;
437
438     // Handle the simple, do-nothing case
439     if (len == 0)
440     {
441       ci->replaceAllUsesWith(ci->getOperand(1));
442       ci->eraseFromParent();
443       return true;
444     }
445
446     // Increment the length because we actually want to memcpy the null
447     // terminator as well.
448     len++;
449
450     // Extract some information from the instruction
451     Module* M = ci->getParent()->getParent()->getParent();
452
453     // We need to find the end of the destination string.  That's where the 
454     // memory is to be moved to. We just generate a call to strlen (further 
455     // optimized in another pass). Note that the get_strlen_func() call 
456     // caches the Function* for us.
457     CallInst* strlen_inst = 
458       new CallInst(get_strlen_func(M,TD.getIntPtrType()),
459                    ci->getOperand(1),"",ci);
460
461     // Now that we have the destination's length, we must index into the 
462     // destination's pointer to get the actual memcpy destination (end of
463     // the string .. we're concatenating).
464     std::vector<Value*> idx;
465     idx.push_back(strlen_inst);
466     GetElementPtrInst* gep = 
467       new GetElementPtrInst(ci->getOperand(1),idx,"",ci);
468
469     // We have enough information to now generate the memcpy call to
470     // do the concatenation for us.
471     std::vector<Value*> vals;
472     vals.push_back(gep); // destination
473     vals.push_back(ci->getOperand(2)); // source
474     vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
475     vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
476     CallInst* memcpy_inst = new CallInst(get_memcpy_func(M), vals, "", ci);
477
478     // Finally, substitute the first operand of the strcat call for the 
479     // strcat call itself since strcat returns its first operand; and, 
480     // kill the strcat CallInst.
481     ci->replaceAllUsesWith(ci->getOperand(1));
482     ci->eraseFromParent();
483     return true;
484   }
485 } StrCatOptimizer;
486
487 /// This CallOptimizer will simplify a call to the strlen library function by
488 /// replacing it with a constant value if the string provided to it is a 
489 /// constant array.
490 /// @brief Simplify the strlen library function.
491 struct StrLenOptimization : public CallOptimizer
492 {
493   StrLenOptimization() : CallOptimizer("strlen") {}
494   virtual ~StrLenOptimization() {}
495
496   /// @brief Make sure that the "strlen" function has the right prototype
497   virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD)
498   {
499     if (f->getReturnType() == TD.getIntPtrType())
500       if (f->arg_size() == 1) 
501         if (Function::const_arg_iterator AI = f->arg_begin())
502           if (AI->getType() == PointerType::get(Type::SByteTy))
503             return true;
504     return false;
505   }
506
507   /// @brief Perform the strlen optimization
508   virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
509   {
510     // Get the length of the string
511     uint64_t len = 0;
512     if (!getConstantStringLength(ci->getOperand(1),len))
513       return false;
514
515     ci->replaceAllUsesWith(ConstantInt::get(TD.getIntPtrType(),len));
516     ci->eraseFromParent();
517     return true;
518   }
519 } StrLenOptimizer;
520
521 /// This CallOptimizer will simplify a call to the memcpy library function by
522 /// expanding it out to a small set of stores if the copy source is a constant
523 /// array. 
524 /// @brief Simplify the memcpy library function.
525 struct MemCpyOptimization : public CallOptimizer
526 {
527   MemCpyOptimization() : CallOptimizer("llvm.memcpy") {}
528 protected:
529   MemCpyOptimization(const char* fname) : CallOptimizer(fname) {}
530 public:
531   virtual ~MemCpyOptimization() {}
532
533   /// @brief Make sure that the "memcpy" function has the right prototype
534   virtual bool ValidateCalledFunction(const Function* f, const TargetData& TD)
535   {
536     // Just make sure this has 4 arguments per LLVM spec.
537     return (f->arg_size() == 4) && 
538            (f->getReturnType() == Type::VoidTy);
539   }
540
541   /// Because of alignment and instruction information that we don't have, we
542   /// leave the bulk of this to the code generators. The optimization here just
543   /// deals with a few degenerate cases where the length of the string and the
544   /// alignment match the sizes of our intrinsic types so we can do a load and
545   /// store instead of the memcpy call.
546   /// @brief Perform the memcpy optimization.
547   virtual bool OptimizeCall(CallInst* ci, const TargetData& TD)
548   {
549     // Make sure we have constant int values to work with
550     ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
551     if (!LEN)
552       return false;
553     ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
554     if (!ALIGN)
555       return false;
556
557     // If the length is larger than the alignment, we can't optimize
558     uint64_t len = LEN->getRawValue();
559     uint64_t alignment = ALIGN->getRawValue();
560     if (len > alignment)
561       return false;
562
563     Value* dest = ci->getOperand(1);
564     Value* src = ci->getOperand(2);
565     CastInst* SrcCast = 0;
566     CastInst* DestCast = 0;
567     switch (len)
568     {
569       case 0:
570         // The memcpy is a no-op so just dump its call.
571         ci->eraseFromParent();
572         return true;
573       case 1:
574         SrcCast = new CastInst(src,PointerType::get(Type::SByteTy),"",ci);
575         DestCast = new CastInst(dest,PointerType::get(Type::SByteTy),"",ci);
576         break;
577       case 2:
578         SrcCast = new CastInst(src,PointerType::get(Type::ShortTy),"",ci);
579         DestCast = new CastInst(dest,PointerType::get(Type::ShortTy),"",ci);
580         break;
581       case 4:
582         SrcCast = new CastInst(src,PointerType::get(Type::IntTy),"",ci);
583         DestCast = new CastInst(dest,PointerType::get(Type::IntTy),"",ci);
584         break;
585       case 8:
586         SrcCast = new CastInst(src,PointerType::get(Type::LongTy),"",ci);
587         DestCast = new CastInst(dest,PointerType::get(Type::LongTy),"",ci);
588         break;
589       default:
590         return false;
591     }
592     LoadInst* LI = new LoadInst(SrcCast,"",ci);
593     StoreInst* SI = new StoreInst(LI, DestCast, ci);
594     ci->eraseFromParent();
595     return true;
596   }
597 } MemCpyOptimizer;
598
599 /// This CallOptimizer will simplify a call to the memmove library function. It
600 /// is identical to MemCopyOptimization except for the name of the intrinsic.
601 /// @brief Simplify the memmove library function.
602 struct MemMoveOptimization : public MemCpyOptimization
603 {
604   MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
605
606 } MemMoveOptimizer;
607
608 }