1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // This file implements a module pass that applies a variety of small
11 // optimizations for calls to specific well-known function calls (e.g. runtime
12 // library functions). For example, a call to the function "exit(3)" that
13 // occurs within the main() function can be transformed into a simple "return 3"
14 // instruction. Any optimization that takes this form (replace call to library
15 // function with simpler code that provides the same result) belongs in this
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "simplify-libcalls"
21 #include "llvm/Constants.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/Instructions.h"
24 #include "llvm/Module.h"
25 #include "llvm/Pass.h"
26 #include "llvm/ADT/hash_map"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Config/config.h"
29 #include "llvm/Support/Compiler.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Target/TargetData.h"
32 #include "llvm/Transforms/IPO.h"
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, "Number of library calls simplified");
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
44 /// This list is populated by the constructor for LibCallOptimization class.
45 /// Therefore all subclasses are registered here at static initialization time
46 /// and this list is what the SimplifyLibCalls pass uses to apply the individual
47 /// optimizations to the call sites.
48 /// @brief The list of optimizations deriving from LibCallOptimization
49 static LibCallOptimization *OptList = 0;
51 /// This class is the abstract base class for the set of optimizations that
52 /// corresponds to one library call. The SimplifyLibCalls pass will call the
53 /// ValidateCalledFunction method to ask the optimization if a given Function
54 /// is the kind that the optimization can handle. If the subclass returns true,
55 /// then SImplifyLibCalls will also call the OptimizeCall method to perform,
56 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
57 /// OptimizeCall won't be called. Subclasses are responsible for providing the
58 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
59 /// constructor. This is used to efficiently select which call instructions to
60 /// optimize. The criteria for a "lib call" is "anything with well known
61 /// semantics", typically a library function that is defined by an international
62 /// standard. Because the semantics are well known, the optimizations can
63 /// generally short-circuit actually calling the function if there's a simpler
64 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
65 /// @brief Base class for library call optimizations
66 class VISIBILITY_HIDDEN LibCallOptimization {
67 LibCallOptimization **Prev, *Next;
68 const char *FunctionName; ///< Name of the library call we optimize
70 Statistic occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
73 /// The \p fname argument must be the name of the library function being
74 /// optimized by the subclass.
75 /// @brief Constructor that registers the optimization.
76 LibCallOptimization(const char *FName, const char *Description)
77 : FunctionName(FName) {
80 occurrences.construct("simplify-libcalls", Description);
82 // Register this optimizer in the list of optimizations.
86 if (Next) Next->Prev = &Next;
89 /// getNext - All libcall optimizations are chained together into a list,
90 /// return the next one in the list.
91 LibCallOptimization *getNext() { return Next; }
93 /// @brief Deregister from the optlist
94 virtual ~LibCallOptimization() {
96 if (Next) Next->Prev = Prev;
99 /// The implementation of this function in subclasses should determine if
100 /// \p F is suitable for the optimization. This method is called by
101 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
102 /// sites of such a function if that function is not suitable in the first
103 /// place. If the called function is suitabe, this method should return true;
104 /// false, otherwise. This function should also perform any lazy
105 /// initialization that the LibCallOptimization needs to do, if its to return
106 /// true. This avoids doing initialization until the optimizer is actually
107 /// going to be called upon to do some optimization.
108 /// @brief Determine if the function is suitable for optimization
109 virtual bool ValidateCalledFunction(
110 const Function* F, ///< The function that is the target of call sites
111 SimplifyLibCalls& SLC ///< The pass object invoking us
114 /// The implementations of this function in subclasses is the heart of the
115 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
116 /// OptimizeCall to determine if (a) the conditions are right for optimizing
117 /// the call and (b) to perform the optimization. If an action is taken
118 /// against ci, the subclass is responsible for returning true and ensuring
119 /// that ci is erased from its parent.
120 /// @brief Optimize a call, if possible.
121 virtual bool OptimizeCall(
122 CallInst* ci, ///< The call instruction that should be optimized.
123 SimplifyLibCalls& SLC ///< The pass object invoking us
126 /// @brief Get the name of the library call being optimized
127 const char *getFunctionName() const { return FunctionName; }
129 bool ReplaceCallWith(CallInst *CI, Value *V) {
130 if (!CI->use_empty())
131 CI->replaceAllUsesWith(V);
132 CI->eraseFromParent();
136 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
139 DEBUG(++occurrences);
144 /// This class is an LLVM Pass that applies each of the LibCallOptimization
145 /// instances to all the call sites in a module, relatively efficiently. The
146 /// purpose of this pass is to provide optimizations for calls to well-known
147 /// functions with well-known semantics, such as those in the c library. The
148 /// class provides the basic infrastructure for handling runOnModule. Whenever
149 /// this pass finds a function call, it asks the appropriate optimizer to
150 /// validate the call (ValidateLibraryCall). If it is validated, then
151 /// the OptimizeCall method is also called.
152 /// @brief A ModulePass for optimizing well-known function calls.
153 class VISIBILITY_HIDDEN SimplifyLibCalls : public ModulePass {
155 /// We need some target data for accurate signature details that are
156 /// target dependent. So we require target data in our AnalysisUsage.
157 /// @brief Require TargetData from AnalysisUsage.
158 virtual void getAnalysisUsage(AnalysisUsage& Info) const {
159 // Ask that the TargetData analysis be performed before us so we can use
161 Info.addRequired<TargetData>();
164 /// For this pass, process all of the function calls in the module, calling
165 /// ValidateLibraryCall and OptimizeCall as appropriate.
166 /// @brief Run all the lib call optimizations on a Module.
167 virtual bool runOnModule(Module &M) {
171 hash_map<std::string, LibCallOptimization*> OptznMap;
172 for (LibCallOptimization *Optzn = OptList; Optzn; Optzn = Optzn->getNext())
173 OptznMap[Optzn->getFunctionName()] = Optzn;
175 // The call optimizations can be recursive. That is, the optimization might
176 // generate a call to another function which can also be optimized. This way
177 // we make the LibCallOptimization instances very specific to the case they
178 // handle. It also means we need to keep running over the function calls in
179 // the module until we don't get any more optimizations possible.
180 bool found_optimization = false;
182 found_optimization = false;
183 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
184 // All the "well-known" functions are external and have external linkage
185 // because they live in a runtime library somewhere and were (probably)
186 // not compiled by LLVM. So, we only act on external functions that
187 // have external or dllimport linkage and non-empty uses.
188 if (!FI->isDeclaration() ||
189 !(FI->hasExternalLinkage() || FI->hasDLLImportLinkage()) ||
193 // Get the optimization class that pertains to this function
194 hash_map<std::string, LibCallOptimization*>::iterator OMI =
195 OptznMap.find(FI->getName());
196 if (OMI == OptznMap.end()) continue;
198 LibCallOptimization *CO = OMI->second;
200 // Make sure the called function is suitable for the optimization
201 if (!CO->ValidateCalledFunction(FI, *this))
204 // Loop over each of the uses of the function
205 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
207 // If the use of the function is a call instruction
208 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
209 // Do the optimization on the LibCallOptimization.
210 if (CO->OptimizeCall(CI, *this)) {
211 ++SimplifiedLibCalls;
212 found_optimization = result = true;
218 } while (found_optimization);
223 /// @brief Return the *current* module we're working on.
224 Module* getModule() const { return M; }
226 /// @brief Return the *current* target data for the module we're working on.
227 TargetData* getTargetData() const { return TD; }
229 /// @brief Return the size_t type -- syntactic shortcut
230 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
232 /// @brief Return a Function* for the putchar libcall
233 Constant *get_putchar() {
236 M->getOrInsertFunction("putchar", Type::Int32Ty, Type::Int32Ty, NULL);
240 /// @brief Return a Function* for the puts libcall
241 Constant *get_puts() {
243 puts_func = M->getOrInsertFunction("puts", Type::Int32Ty,
244 PointerType::get(Type::Int8Ty),
249 /// @brief Return a Function* for the fputc libcall
250 Constant *get_fputc(const Type* FILEptr_type) {
252 fputc_func = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
257 /// @brief Return a Function* for the fputs libcall
258 Constant *get_fputs(const Type* FILEptr_type) {
260 fputs_func = M->getOrInsertFunction("fputs", Type::Int32Ty,
261 PointerType::get(Type::Int8Ty),
266 /// @brief Return a Function* for the fwrite libcall
267 Constant *get_fwrite(const Type* FILEptr_type) {
269 fwrite_func = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
270 PointerType::get(Type::Int8Ty),
277 /// @brief Return a Function* for the sqrt libcall
278 Constant *get_sqrt() {
280 sqrt_func = M->getOrInsertFunction("sqrt", Type::DoubleTy,
281 Type::DoubleTy, NULL);
285 /// @brief Return a Function* for the strcpy libcall
286 Constant *get_strcpy() {
288 strcpy_func = M->getOrInsertFunction("strcpy",
289 PointerType::get(Type::Int8Ty),
290 PointerType::get(Type::Int8Ty),
291 PointerType::get(Type::Int8Ty),
296 /// @brief Return a Function* for the strlen libcall
297 Constant *get_strlen() {
299 strlen_func = M->getOrInsertFunction("strlen", TD->getIntPtrType(),
300 PointerType::get(Type::Int8Ty),
305 /// @brief Return a Function* for the memchr libcall
306 Constant *get_memchr() {
308 memchr_func = M->getOrInsertFunction("memchr",
309 PointerType::get(Type::Int8Ty),
310 PointerType::get(Type::Int8Ty),
311 Type::Int32Ty, TD->getIntPtrType(),
316 /// @brief Return a Function* for the memcpy libcall
317 Constant *get_memcpy() {
319 const Type *SBP = PointerType::get(Type::Int8Ty);
320 const char *N = TD->getIntPtrType() == Type::Int32Ty ?
321 "llvm.memcpy.i32" : "llvm.memcpy.i64";
322 memcpy_func = M->getOrInsertFunction(N, Type::VoidTy, SBP, SBP,
323 TD->getIntPtrType(), Type::Int32Ty,
329 Constant *getUnaryFloatFunction(const char *Name, Constant *&Cache) {
331 Cache = M->getOrInsertFunction(Name, Type::FloatTy, Type::FloatTy, NULL);
335 Constant *get_floorf() { return getUnaryFloatFunction("floorf", floorf_func);}
336 Constant *get_ceilf() { return getUnaryFloatFunction( "ceilf", ceilf_func);}
337 Constant *get_roundf() { return getUnaryFloatFunction("roundf", roundf_func);}
338 Constant *get_rintf() { return getUnaryFloatFunction( "rintf", rintf_func);}
339 Constant *get_nearbyintf() { return getUnaryFloatFunction("nearbyintf",
342 /// @brief Reset our cached data for a new Module
343 void reset(Module& mod) {
345 TD = &getAnalysis<TargetData>();
364 /// Caches for function pointers.
365 Constant *putchar_func, *puts_func;
366 Constant *fputc_func, *fputs_func, *fwrite_func;
367 Constant *memcpy_func, *memchr_func;
369 Constant *strcpy_func, *strlen_func;
370 Constant *floorf_func, *ceilf_func, *roundf_func;
371 Constant *rintf_func, *nearbyintf_func;
372 Module *M; ///< Cached Module
373 TargetData *TD; ///< Cached TargetData
377 RegisterPass<SimplifyLibCalls>
378 X("simplify-libcalls", "Simplify well-known library calls");
380 } // anonymous namespace
382 // The only public symbol in this file which just instantiates the pass object
383 ModulePass *llvm::createSimplifyLibCallsPass() {
384 return new SimplifyLibCalls();
387 // Classes below here, in the anonymous namespace, are all subclasses of the
388 // LibCallOptimization class, each implementing all optimizations possible for a
389 // single well-known library call. Each has a static singleton instance that
390 // auto registers it into the "optlist" global above.
393 // Forward declare utility functions.
394 static bool GetConstantStringInfo(Value *V, ConstantArray *&Array,
395 uint64_t &Length, uint64_t &StartIdx);
396 static Value *CastToCStr(Value *V, Instruction *IP);
398 /// This LibCallOptimization will find instances of a call to "exit" that occurs
399 /// within the "main" function and change it to a simple "ret" instruction with
400 /// the same value passed to the exit function. When this is done, it splits the
401 /// basic block at the exit(3) call and deletes the call instruction.
402 /// @brief Replace calls to exit in main with a simple return
403 struct VISIBILITY_HIDDEN ExitInMainOptimization : public LibCallOptimization {
404 ExitInMainOptimization() : LibCallOptimization("exit",
405 "Number of 'exit' calls simplified") {}
407 // Make sure the called function looks like exit (int argument, int return
408 // type, external linkage, not varargs).
409 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
410 return F->arg_size() >= 1 && F->arg_begin()->getType()->isInteger();
413 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
414 // To be careful, we check that the call to exit is coming from "main", that
415 // main has external linkage, and the return type of main and the argument
416 // to exit have the same type.
417 Function *from = ci->getParent()->getParent();
418 if (from->hasExternalLinkage())
419 if (from->getReturnType() == ci->getOperand(1)->getType())
420 if (from->getName() == "main") {
421 // Okay, time to actually do the optimization. First, get the basic
422 // block of the call instruction
423 BasicBlock* bb = ci->getParent();
425 // Create a return instruction that we'll replace the call with.
426 // Note that the argument of the return is the argument of the call
428 new ReturnInst(ci->getOperand(1), ci);
430 // Split the block at the call instruction which places it in a new
432 bb->splitBasicBlock(ci);
434 // The block split caused a branch instruction to be inserted into
435 // the end of the original block, right after the return instruction
436 // that we put there. That's not a valid block, so delete the branch
438 bb->getInstList().pop_back();
440 // Now we can finally get rid of the call instruction which now lives
441 // in the new basic block.
442 ci->eraseFromParent();
444 // Optimization succeeded, return true.
447 // We didn't pass the criteria for this optimization so return false
450 } ExitInMainOptimizer;
452 /// This LibCallOptimization will simplify a call to the strcat library
453 /// function. The simplification is possible only if the string being
454 /// concatenated is a constant array or a constant expression that results in
455 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
456 /// of the constant string. Both of these calls are further reduced, if possible
457 /// on subsequent passes.
458 /// @brief Simplify the strcat library function.
459 struct VISIBILITY_HIDDEN StrCatOptimization : public LibCallOptimization {
461 /// @brief Default constructor
462 StrCatOptimization() : LibCallOptimization("strcat",
463 "Number of 'strcat' calls simplified") {}
467 /// @brief Make sure that the "strcat" function has the right prototype
468 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
469 if (f->getReturnType() == PointerType::get(Type::Int8Ty))
470 if (f->arg_size() == 2)
472 Function::const_arg_iterator AI = f->arg_begin();
473 if (AI++->getType() == PointerType::get(Type::Int8Ty))
474 if (AI->getType() == PointerType::get(Type::Int8Ty))
476 // Indicate this is a suitable call type.
483 /// @brief Optimize the strcat library function
484 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
485 // Extract some information from the instruction
486 Value *Dst = CI->getOperand(1);
487 Value *Src = CI->getOperand(2);
489 // Extract the initializer (while making numerous checks) from the
490 // source operand of the call to strcat.
491 uint64_t SrcLength, StartIdx;
493 if (!GetConstantStringInfo(Src, Arr, SrcLength, StartIdx))
496 // Handle the simple, do-nothing case
498 return ReplaceCallWith(CI, Dst);
500 // We need to find the end of the destination string. That's where the
501 // memory is to be moved to. We just generate a call to strlen (further
502 // optimized in another pass).
503 CallInst *DstLen = new CallInst(SLC.get_strlen(), Dst,
504 Dst->getName()+".len", CI);
506 // Now that we have the destination's length, we must index into the
507 // destination's pointer to get the actual memcpy destination (end of
508 // the string .. we're concatenating).
509 Dst = new GetElementPtrInst(Dst, DstLen, Dst->getName()+".indexed", CI);
511 // We have enough information to now generate the memcpy call to
512 // do the concatenation for us.
515 ConstantInt::get(SLC.getIntPtrType(), SrcLength+1), // copy nul term.
516 ConstantInt::get(Type::Int32Ty, 1) // alignment
518 new CallInst(SLC.get_memcpy(), Vals, 4, "", CI);
520 return ReplaceCallWith(CI, Dst);
524 /// This LibCallOptimization will simplify a call to the strchr library
525 /// function. It optimizes out cases where the arguments are both constant
526 /// and the result can be determined statically.
527 /// @brief Simplify the strcmp library function.
528 struct VISIBILITY_HIDDEN StrChrOptimization : public LibCallOptimization {
530 StrChrOptimization() : LibCallOptimization("strchr",
531 "Number of 'strchr' calls simplified") {}
533 /// @brief Make sure that the "strchr" function has the right prototype
534 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
535 const FunctionType *FT = F->getFunctionType();
536 return FT->getNumParams() == 2 &&
537 FT->getReturnType() == PointerType::get(Type::Int8Ty) &&
538 FT->getParamType(0) == FT->getReturnType() &&
539 isa<IntegerType>(FT->getParamType(1));
542 /// @brief Perform the strchr optimizations
543 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
544 // Check that the first argument to strchr is a constant array of sbyte.
545 // If it is, get the length and data, otherwise return false.
546 uint64_t StrLength, StartIdx;
547 ConstantArray *CA = 0;
548 if (!GetConstantStringInfo(CI->getOperand(1), CA, StrLength, StartIdx))
551 // If the second operand is not constant, just lower this to memchr since we
552 // know the length of the input string.
553 ConstantInt *CSI = dyn_cast<ConstantInt>(CI->getOperand(2));
558 ConstantInt::get(SLC.getIntPtrType(), StrLength+1)
560 return ReplaceCallWith(CI, new CallInst(SLC.get_memchr(), Args, 3,
564 // Get the character we're looking for
565 int64_t CharValue = CSI->getSExtValue();
567 if (StrLength == 0) {
568 // If the length of the string is zero, and we are searching for zero,
569 // return the input pointer.
571 return ReplaceCallWith(CI, CI->getOperand(1));
572 // Otherwise, char wasn't found.
573 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
576 // Compute the offset
579 assert(i <= StrLength && "Didn't find null terminator?");
580 if (ConstantInt *C = dyn_cast<ConstantInt>(CA->getOperand(i+StartIdx))) {
581 // Did we find our match?
582 if (C->getSExtValue() == CharValue)
584 if (C->isZero()) // We found the end of the string. strchr returns null.
585 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
590 // strchr(s+n,c) -> gep(s+n+i,c)
591 // (if c is a constant integer and s is a constant string)
592 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
593 Value *GEP = new GetElementPtrInst(CI->getOperand(1), Idx,
594 CI->getOperand(1)->getName() +
596 return ReplaceCallWith(CI, GEP);
600 /// This LibCallOptimization will simplify a call to the strcmp library
601 /// function. It optimizes out cases where one or both arguments are constant
602 /// and the result can be determined statically.
603 /// @brief Simplify the strcmp library function.
604 struct VISIBILITY_HIDDEN StrCmpOptimization : public LibCallOptimization {
606 StrCmpOptimization() : LibCallOptimization("strcmp",
607 "Number of 'strcmp' calls simplified") {}
609 /// @brief Make sure that the "strcmp" function has the right prototype
610 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
611 const FunctionType *FT = F->getFunctionType();
612 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 2 &&
613 FT->getParamType(0) == FT->getParamType(1) &&
614 FT->getParamType(0) == PointerType::get(Type::Int8Ty);
617 /// @brief Perform the strcmp optimization
618 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
619 // First, check to see if src and destination are the same. If they are,
620 // then the optimization is to replace the CallInst with a constant 0
621 // because the call is a no-op.
622 Value *Str1P = CI->getOperand(1);
623 Value *Str2P = CI->getOperand(2);
624 if (Str1P == Str2P) // strcmp(x,x) -> 0
625 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
627 uint64_t Str1Len, Str1StartIdx;
629 bool Str1IsCst = GetConstantStringInfo(Str1P, A1, Str1Len, Str1StartIdx);
630 if (Str1IsCst && Str1Len == 0) {
631 // strcmp("", x) -> *x
632 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
633 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
634 return ReplaceCallWith(CI, V);
637 uint64_t Str2Len, Str2StartIdx;
639 bool Str2IsCst = GetConstantStringInfo(Str2P, A2, Str2Len, Str2StartIdx);
640 if (Str2IsCst && Str2Len == 0) {
641 // strcmp(x,"") -> *x
642 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
643 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
644 return ReplaceCallWith(CI, V);
647 if (Str1IsCst && Str2IsCst && A1->isCString() && A2->isCString()) {
648 // strcmp(x, y) -> cnst (if both x and y are constant strings)
649 std::string S1 = A1->getAsString();
650 std::string S2 = A2->getAsString();
651 int R = strcmp(S1.c_str()+Str1StartIdx, S2.c_str()+Str2StartIdx);
652 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
658 /// This LibCallOptimization will simplify a call to the strncmp library
659 /// function. It optimizes out cases where one or both arguments are constant
660 /// and the result can be determined statically.
661 /// @brief Simplify the strncmp library function.
662 struct VISIBILITY_HIDDEN StrNCmpOptimization : public LibCallOptimization {
664 StrNCmpOptimization() : LibCallOptimization("strncmp",
665 "Number of 'strncmp' calls simplified") {}
667 /// @brief Make sure that the "strncmp" function has the right prototype
668 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
669 const FunctionType *FT = F->getFunctionType();
670 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 3 &&
671 FT->getParamType(0) == FT->getParamType(1) &&
672 FT->getParamType(0) == PointerType::get(Type::Int8Ty) &&
673 isa<IntegerType>(FT->getParamType(2));
677 /// @brief Perform the strncmp optimization
678 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
679 // First, check to see if src and destination are the same. If they are,
680 // then the optimization is to replace the CallInst with a constant 0
681 // because the call is a no-op.
682 Value *Str1P = CI->getOperand(1);
683 Value *Str2P = CI->getOperand(2);
684 if (Str1P == Str2P) // strncmp(x,x) -> 0
685 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
687 // Check the length argument, if it is Constant zero then the strings are
690 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
691 Length = LengthArg->getZExtValue();
696 // strncmp(x,y,0) -> 0
697 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
700 uint64_t Str1Len, Str1StartIdx;
702 bool Str1IsCst = GetConstantStringInfo(Str1P, A1, Str1Len, Str1StartIdx);
703 if (Str1IsCst && Str1Len == 0) {
704 // strncmp("", x) -> *x
705 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
706 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
707 return ReplaceCallWith(CI, V);
710 uint64_t Str2Len, Str2StartIdx;
712 bool Str2IsCst = GetConstantStringInfo(Str2P, A2, Str2Len, Str2StartIdx);
713 if (Str2IsCst && Str2Len == 0) {
714 // strncmp(x,"") -> *x
715 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
716 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
717 return ReplaceCallWith(CI, V);
720 if (Str1IsCst && Str2IsCst && A1->isCString() &&
722 // strncmp(x, y) -> cnst (if both x and y are constant strings)
723 std::string S1 = A1->getAsString();
724 std::string S2 = A2->getAsString();
725 int R = strncmp(S1.c_str()+Str1StartIdx, S2.c_str()+Str2StartIdx, Length);
726 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
732 /// This LibCallOptimization will simplify a call to the strcpy library
733 /// function. Two optimizations are possible:
734 /// (1) If src and dest are the same and not volatile, just return dest
735 /// (2) If the src is a constant then we can convert to llvm.memmove
736 /// @brief Simplify the strcpy library function.
737 struct VISIBILITY_HIDDEN StrCpyOptimization : public LibCallOptimization {
739 StrCpyOptimization() : LibCallOptimization("strcpy",
740 "Number of 'strcpy' calls simplified") {}
742 /// @brief Make sure that the "strcpy" function has the right prototype
743 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
744 const FunctionType *FT = F->getFunctionType();
745 return FT->getNumParams() == 2 &&
746 FT->getParamType(0) == FT->getParamType(1) &&
747 FT->getReturnType() == FT->getParamType(0) &&
748 FT->getParamType(0) == PointerType::get(Type::Int8Ty);
751 /// @brief Perform the strcpy optimization
752 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
753 // First, check to see if src and destination are the same. If they are,
754 // then the optimization is to replace the CallInst with the destination
755 // because the call is a no-op. Note that this corresponds to the
756 // degenerate strcpy(X,X) case which should have "undefined" results
757 // according to the C specification. However, it occurs sometimes and
758 // we optimize it as a no-op.
759 Value *Dst = CI->getOperand(1);
760 Value *Src = CI->getOperand(2);
763 return ReplaceCallWith(CI, Dst);
766 // Get the length of the constant string referenced by the Src operand.
767 uint64_t SrcLen, SrcStartIdx;
768 ConstantArray *SrcArr;
769 if (!GetConstantStringInfo(Src, SrcArr, SrcLen, SrcStartIdx))
772 // If the constant string's length is zero we can optimize this by just
773 // doing a store of 0 at the first byte of the destination
775 new StoreInst(ConstantInt::get(Type::Int8Ty, 0), Dst, CI);
776 return ReplaceCallWith(CI, Dst);
779 // We have enough information to now generate the memcpy call to
780 // do the concatenation for us.
781 Value *MemcpyOps[] = {
783 ConstantInt::get(SLC.getIntPtrType(), SrcLen+1), // length including nul.
784 ConstantInt::get(Type::Int32Ty, 1) // alignment
786 new CallInst(SLC.get_memcpy(), MemcpyOps, 4, "", CI);
788 return ReplaceCallWith(CI, Dst);
792 /// This LibCallOptimization will simplify a call to the strlen library
793 /// function by replacing it with a constant value if the string provided to
794 /// it is a constant array.
795 /// @brief Simplify the strlen library function.
796 struct VISIBILITY_HIDDEN StrLenOptimization : public LibCallOptimization {
797 StrLenOptimization() : LibCallOptimization("strlen",
798 "Number of 'strlen' calls simplified") {}
800 /// @brief Make sure that the "strlen" function has the right prototype
801 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
802 const FunctionType *FT = F->getFunctionType();
803 return FT->getNumParams() == 1 &&
804 FT->getParamType(0) == PointerType::get(Type::Int8Ty) &&
805 isa<IntegerType>(FT->getReturnType());
808 /// @brief Perform the strlen optimization
809 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
810 // Make sure we're dealing with an sbyte* here.
811 Value *Str = CI->getOperand(1);
813 // Does the call to strlen have exactly one use?
814 if (CI->hasOneUse()) {
815 // Is that single use a icmp operator?
816 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CI->use_back()))
817 // Is it compared against a constant integer?
818 if (ConstantInt *Cst = dyn_cast<ConstantInt>(Cmp->getOperand(1))) {
819 // If its compared against length 0 with == or !=
820 if (Cst->getZExtValue() == 0 && Cmp->isEquality()) {
821 // strlen(x) != 0 -> *x != 0
822 // strlen(x) == 0 -> *x == 0
823 Value *V = new LoadInst(Str, Str->getName()+".first", CI);
824 V = new ICmpInst(Cmp->getPredicate(), V,
825 ConstantInt::get(Type::Int8Ty, 0),
826 Cmp->getName()+".strlen", CI);
827 Cmp->replaceAllUsesWith(V);
828 Cmp->eraseFromParent();
829 return ReplaceCallWith(CI, 0); // no uses.
834 // Get the length of the constant string operand
835 uint64_t StrLen = 0, StartIdx;
837 if (!GetConstantStringInfo(CI->getOperand(1), A, StrLen, StartIdx))
840 // strlen("xyz") -> 3 (for example)
841 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), StrLen));
845 /// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
846 /// is equal or not-equal to zero.
847 static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
848 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
850 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
851 if (IC->isEquality())
852 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
853 if (C->isNullValue())
855 // Unknown instruction.
861 /// This memcmpOptimization will simplify a call to the memcmp library
863 struct VISIBILITY_HIDDEN memcmpOptimization : public LibCallOptimization {
864 /// @brief Default Constructor
866 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
868 /// @brief Make sure that the "memcmp" function has the right prototype
869 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
870 Function::const_arg_iterator AI = F->arg_begin();
871 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
872 if (!isa<PointerType>((++AI)->getType())) return false;
873 if (!(++AI)->getType()->isInteger()) return false;
874 if (!F->getReturnType()->isInteger()) return false;
878 /// Because of alignment and instruction information that we don't have, we
879 /// leave the bulk of this to the code generators.
881 /// Note that we could do much more if we could force alignment on otherwise
882 /// small aligned allocas, or if we could indicate that loads have a small
884 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
885 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
887 // If the two operands are the same, return zero.
889 // memcmp(s,s,x) -> 0
890 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
893 // Make sure we have a constant length.
894 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
895 if (!LenC) return false;
896 uint64_t Len = LenC->getZExtValue();
898 // If the length is zero, this returns 0.
901 // memcmp(s1,s2,0) -> 0
902 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
904 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
905 const Type *UCharPtr = PointerType::get(Type::Int8Ty);
906 CastInst *Op1Cast = CastInst::create(
907 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
908 CastInst *Op2Cast = CastInst::create(
909 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
910 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
911 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
912 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
913 if (RV->getType() != CI->getType())
914 RV = CastInst::createIntegerCast(RV, CI->getType(), false,
916 return ReplaceCallWith(CI, RV);
919 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
920 // TODO: IF both are aligned, use a short load/compare.
922 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
923 const Type *UCharPtr = PointerType::get(Type::Int8Ty);
924 CastInst *Op1Cast = CastInst::create(
925 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
926 CastInst *Op2Cast = CastInst::create(
927 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
928 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
929 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
930 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
931 CI->getName()+".d1", CI);
932 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
933 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
934 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
935 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
936 Value *S2V2 = new LoadInst(G2, RHS->getName()+".val2", CI);
937 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
938 CI->getName()+".d1", CI);
939 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
940 if (Or->getType() != CI->getType())
941 Or = CastInst::createIntegerCast(Or, CI->getType(), false /*ZExt*/,
943 return ReplaceCallWith(CI, Or);
955 /// This LibCallOptimization will simplify a call to the memcpy library
956 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
957 /// bytes depending on the length of the string and the alignment. Additional
958 /// optimizations are possible in code generation (sequence of immediate store)
959 /// @brief Simplify the memcpy library function.
960 struct VISIBILITY_HIDDEN LLVMMemCpyMoveOptzn : public LibCallOptimization {
961 LLVMMemCpyMoveOptzn(const char* fname, const char* desc)
962 : LibCallOptimization(fname, desc) {}
964 /// @brief Make sure that the "memcpy" function has the right prototype
965 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD) {
966 // Just make sure this has 4 arguments per LLVM spec.
967 return (f->arg_size() == 4);
970 /// Because of alignment and instruction information that we don't have, we
971 /// leave the bulk of this to the code generators. The optimization here just
972 /// deals with a few degenerate cases where the length of the string and the
973 /// alignment match the sizes of our intrinsic types so we can do a load and
974 /// store instead of the memcpy call.
975 /// @brief Perform the memcpy optimization.
976 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD) {
977 // Make sure we have constant int values to work with
978 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
981 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
985 // If the length is larger than the alignment, we can't optimize
986 uint64_t len = LEN->getZExtValue();
987 uint64_t alignment = ALIGN->getZExtValue();
989 alignment = 1; // Alignment 0 is identity for alignment 1
993 // Get the type we will cast to, based on size of the string
994 Value* dest = ci->getOperand(1);
995 Value* src = ci->getOperand(2);
996 const Type* castType = 0;
999 // memcpy(d,s,0,a) -> d
1000 return ReplaceCallWith(ci, 0);
1001 case 1: castType = Type::Int8Ty; break;
1002 case 2: castType = Type::Int16Ty; break;
1003 case 4: castType = Type::Int32Ty; break;
1004 case 8: castType = Type::Int64Ty; break;
1009 // Cast source and dest to the right sized primitive and then load/store
1010 CastInst* SrcCast = CastInst::create(Instruction::BitCast,
1011 src, PointerType::get(castType), src->getName()+".cast", ci);
1012 CastInst* DestCast = CastInst::create(Instruction::BitCast,
1013 dest, PointerType::get(castType),dest->getName()+".cast", ci);
1014 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
1015 new StoreInst(LI, DestCast, ci);
1016 return ReplaceCallWith(ci, 0);
1020 /// This LibCallOptimization will simplify a call to the memcpy/memmove library
1022 LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer32("llvm.memcpy.i32",
1023 "Number of 'llvm.memcpy' calls simplified");
1024 LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer64("llvm.memcpy.i64",
1025 "Number of 'llvm.memcpy' calls simplified");
1026 LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer32("llvm.memmove.i32",
1027 "Number of 'llvm.memmove' calls simplified");
1028 LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer64("llvm.memmove.i64",
1029 "Number of 'llvm.memmove' calls simplified");
1031 /// This LibCallOptimization will simplify a call to the memset library
1032 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1033 /// bytes depending on the length argument.
1034 struct VISIBILITY_HIDDEN LLVMMemSetOptimization : public LibCallOptimization {
1035 /// @brief Default Constructor
1036 LLVMMemSetOptimization(const char *Name) : LibCallOptimization(Name,
1037 "Number of 'llvm.memset' calls simplified") {}
1039 /// @brief Make sure that the "memset" function has the right prototype
1040 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
1041 // Just make sure this has 3 arguments per LLVM spec.
1042 return F->arg_size() == 4;
1045 /// Because of alignment and instruction information that we don't have, we
1046 /// leave the bulk of this to the code generators. The optimization here just
1047 /// deals with a few degenerate cases where the length parameter is constant
1048 /// and the alignment matches the sizes of our intrinsic types so we can do
1049 /// store instead of the memcpy call. Other calls are transformed into the
1050 /// llvm.memset intrinsic.
1051 /// @brief Perform the memset optimization.
1052 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &TD) {
1053 // Make sure we have constant int values to work with
1054 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1057 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1061 // Extract the length and alignment
1062 uint64_t len = LEN->getZExtValue();
1063 uint64_t alignment = ALIGN->getZExtValue();
1065 // Alignment 0 is identity for alignment 1
1069 // If the length is zero, this is a no-op
1071 // memset(d,c,0,a) -> noop
1072 return ReplaceCallWith(ci, 0);
1075 // If the length is larger than the alignment, we can't optimize
1076 if (len > alignment)
1079 // Make sure we have a constant ubyte to work with so we can extract
1080 // the value to be filled.
1081 ConstantInt* FILL = dyn_cast<ConstantInt>(ci->getOperand(2));
1084 if (FILL->getType() != Type::Int8Ty)
1087 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1089 // Extract the fill character
1090 uint64_t fill_char = FILL->getZExtValue();
1091 uint64_t fill_value = fill_char;
1093 // Get the type we will cast to, based on size of memory area to fill, and
1094 // and the value we will store there.
1095 Value* dest = ci->getOperand(1);
1096 const Type* castType = 0;
1099 castType = Type::Int8Ty;
1102 castType = Type::Int16Ty;
1103 fill_value |= fill_char << 8;
1106 castType = Type::Int32Ty;
1107 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1110 castType = Type::Int64Ty;
1111 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1112 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1113 fill_value |= fill_char << 56;
1119 // Cast dest to the right sized primitive and then load/store
1120 CastInst* DestCast = new BitCastInst(dest, PointerType::get(castType),
1121 dest->getName()+".cast", ci);
1122 new StoreInst(ConstantInt::get(castType,fill_value),DestCast, ci);
1123 return ReplaceCallWith(ci, 0);
1127 LLVMMemSetOptimization MemSet32Optimizer("llvm.memset.i32");
1128 LLVMMemSetOptimization MemSet64Optimizer("llvm.memset.i64");
1131 /// This LibCallOptimization will simplify calls to the "pow" library
1132 /// function. It looks for cases where the result of pow is well known and
1133 /// substitutes the appropriate value.
1134 /// @brief Simplify the pow library function.
1135 struct VISIBILITY_HIDDEN PowOptimization : public LibCallOptimization {
1137 /// @brief Default Constructor
1138 PowOptimization() : LibCallOptimization("pow",
1139 "Number of 'pow' calls simplified") {}
1141 /// @brief Make sure that the "pow" function has the right prototype
1142 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1143 // Just make sure this has 2 arguments
1144 return (f->arg_size() == 2);
1147 /// @brief Perform the pow optimization.
1148 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1149 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1150 Value* base = ci->getOperand(1);
1151 Value* expn = ci->getOperand(2);
1152 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1153 double Op1V = Op1->getValue();
1154 if (Op1V == 1.0) // pow(1.0,x) -> 1.0
1155 return ReplaceCallWith(ci, ConstantFP::get(Ty, 1.0));
1156 } else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) {
1157 double Op2V = Op2->getValue();
1159 // pow(x,0.0) -> 1.0
1160 return ReplaceCallWith(ci, ConstantFP::get(Ty,1.0));
1161 } else if (Op2V == 0.5) {
1162 // pow(x,0.5) -> sqrt(x)
1163 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1164 ci->getName()+".pow",ci);
1165 return ReplaceCallWith(ci, sqrt_inst);
1166 } else if (Op2V == 1.0) {
1168 return ReplaceCallWith(ci, base);
1169 } else if (Op2V == -1.0) {
1170 // pow(x,-1.0) -> 1.0/x
1172 BinaryOperator::createFDiv(ConstantFP::get(Ty, 1.0), base,
1173 ci->getName()+".pow", ci);
1174 return ReplaceCallWith(ci, div_inst);
1177 return false; // opt failed
1181 /// This LibCallOptimization will simplify calls to the "printf" library
1182 /// function. It looks for cases where the result of printf is not used and the
1183 /// operation can be reduced to something simpler.
1184 /// @brief Simplify the printf library function.
1185 struct VISIBILITY_HIDDEN PrintfOptimization : public LibCallOptimization {
1187 /// @brief Default Constructor
1188 PrintfOptimization() : LibCallOptimization("printf",
1189 "Number of 'printf' calls simplified") {}
1191 /// @brief Make sure that the "printf" function has the right prototype
1192 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1193 // Just make sure this has at least 1 arguments
1194 return F->arg_size() >= 1;
1197 /// @brief Perform the printf optimization.
1198 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1199 // If the call has more than 2 operands, we can't optimize it
1200 if (CI->getNumOperands() != 3)
1203 // If the result of the printf call is used, none of these optimizations
1205 if (!CI->use_empty())
1208 // All the optimizations depend on the length of the first argument and the
1209 // fact that it is a constant string array. Check that now
1210 uint64_t FormatLen, FormatIdx;
1211 ConstantArray *CA = 0;
1212 if (!GetConstantStringInfo(CI->getOperand(1), CA, FormatLen, FormatIdx))
1215 if (FormatLen != 2 && FormatLen != 3)
1218 // The first character has to be a %
1219 if (cast<ConstantInt>(CA->getOperand(FormatIdx))->getZExtValue() != '%')
1222 // Get the second character and switch on its value
1223 switch (cast<ConstantInt>(CA->getOperand(FormatIdx+1))->getZExtValue()) {
1224 default: return false;
1226 if (FormatLen != 3 ||
1227 cast<ConstantInt>(CA->getOperand(FormatIdx+2))->getZExtValue() !='\n')
1230 // printf("%s\n",str) -> puts(str)
1231 new CallInst(SLC.get_puts(), CastToCStr(CI->getOperand(2), CI),
1233 return ReplaceCallWith(CI, 0);
1236 // printf("%c",c) -> putchar(c)
1240 Value *V = CI->getOperand(2);
1241 if (!isa<IntegerType>(V->getType()) ||
1242 cast<IntegerType>(V->getType())->getBitWidth() < 32)
1245 V = CastInst::createSExtOrBitCast(V, Type::Int32Ty, CI->getName()+".int",
1247 new CallInst(SLC.get_putchar(), V, "", CI);
1248 return ReplaceCallWith(CI, 0);
1254 /// This LibCallOptimization will simplify calls to the "fprintf" library
1255 /// function. It looks for cases where the result of fprintf is not used and the
1256 /// operation can be reduced to something simpler.
1257 /// @brief Simplify the fprintf library function.
1258 struct VISIBILITY_HIDDEN FPrintFOptimization : public LibCallOptimization {
1260 /// @brief Default Constructor
1261 FPrintFOptimization() : LibCallOptimization("fprintf",
1262 "Number of 'fprintf' calls simplified") {}
1264 /// @brief Make sure that the "fprintf" function has the right prototype
1265 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1266 const FunctionType *FT = F->getFunctionType();
1267 return FT->getNumParams() == 2 && // two fixed arguments.
1268 FT->getParamType(1) == PointerType::get(Type::Int8Ty) &&
1269 isa<PointerType>(FT->getParamType(0)) &&
1270 isa<IntegerType>(FT->getReturnType());
1273 /// @brief Perform the fprintf optimization.
1274 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1275 // If the call has more than 3 operands, we can't optimize it
1276 if (CI->getNumOperands() != 3 && CI->getNumOperands() != 4)
1279 // All the optimizations depend on the length of the second argument and the
1280 // fact that it is a constant string array. Check that now
1281 uint64_t FormatLen, FormatStartIdx;
1282 ConstantArray *CA = 0;
1283 if (!GetConstantStringInfo(CI->getOperand(2), CA, FormatLen,FormatStartIdx))
1286 // IF fthis is just a format string, turn it into fwrite.
1287 if (CI->getNumOperands() == 3) {
1288 if (!CA->isCString()) return false;
1290 // Make sure there's no % in the constant array
1291 std::string S = CA->getAsString();
1293 for (unsigned i = FormatStartIdx, e = S.size(); i != e; ++i)
1295 return false; // we found a format specifier
1297 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
1298 const Type *FILEty = CI->getOperand(1)->getType();
1300 Value *FWriteArgs[] = {
1302 ConstantInt::get(SLC.getIntPtrType(), FormatLen),
1303 ConstantInt::get(SLC.getIntPtrType(), 1),
1306 new CallInst(SLC.get_fwrite(FILEty), FWriteArgs, 4, CI->getName(), CI);
1307 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), FormatLen));
1310 // The remaining optimizations require the format string to be length 2:
1315 // The first character has to be a % for us to handle it.
1316 if (cast<ConstantInt>(CA->getOperand(FormatStartIdx))->getZExtValue() !='%')
1319 // Get the second character and switch on its value
1320 switch(cast<ConstantInt>(CA->getOperand(FormatStartIdx+1))->getZExtValue()){
1322 // fprintf(file,"%c",c) -> fputc(c,file)
1323 const Type *FILETy = CI->getOperand(1)->getType();
1324 Value *C = CastInst::createZExtOrBitCast(CI->getOperand(3), Type::Int32Ty,
1325 CI->getName()+".int", CI);
1326 new CallInst(SLC.get_fputc(FILETy), C, CI->getOperand(1), "", CI);
1327 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1330 const Type *FILETy = CI->getOperand(1)->getType();
1331 uint64_t LitStrLen, LitStartIdx;
1332 ConstantArray *CA = 0;
1333 if (GetConstantStringInfo(CI->getOperand(3), CA, LitStrLen, LitStartIdx)){
1334 // fprintf(file,"%s",str) -> fwrite(str,strlen(str),1,file)
1335 Value *FWriteArgs[] = {
1336 CastToCStr(CI->getOperand(3), CI),
1337 ConstantInt::get(SLC.getIntPtrType(), LitStrLen),
1338 ConstantInt::get(SLC.getIntPtrType(), 1),
1341 new CallInst(SLC.get_fwrite(FILETy), FWriteArgs, 4, CI->getName(), CI);
1342 return ReplaceCallWith(CI, ConstantInt::get(Type::Int32Ty, LitStrLen));
1345 // If the result of the fprintf call is used, we can't do this.
1346 // TODO: we could insert a strlen call.
1347 if (!CI->use_empty())
1350 // fprintf(file,"%s",str) -> fputs(str,file)
1351 new CallInst(SLC.get_fputs(FILETy), CastToCStr(CI->getOperand(3), CI),
1352 CI->getOperand(1), CI->getName(), CI);
1353 return ReplaceCallWith(CI, 0);
1361 /// This LibCallOptimization will simplify calls to the "sprintf" library
1362 /// function. It looks for cases where the result of sprintf is not used and the
1363 /// operation can be reduced to something simpler.
1364 /// @brief Simplify the sprintf library function.
1365 struct VISIBILITY_HIDDEN SPrintFOptimization : public LibCallOptimization {
1367 /// @brief Default Constructor
1368 SPrintFOptimization() : LibCallOptimization("sprintf",
1369 "Number of 'sprintf' calls simplified") {}
1371 /// @brief Make sure that the "fprintf" function has the right prototype
1372 virtual bool ValidateCalledFunction(const Function *f, SimplifyLibCalls &SLC){
1373 // Just make sure this has at least 2 arguments
1374 return (f->getReturnType() == Type::Int32Ty && f->arg_size() >= 2);
1377 /// @brief Perform the sprintf optimization.
1378 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1379 // If the call has more than 3 operands, we can't optimize it
1380 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1383 // All the optimizations depend on the length of the second argument and the
1384 // fact that it is a constant string array. Check that now
1385 uint64_t len, StartIdx;
1386 ConstantArray* CA = 0;
1387 if (!GetConstantStringInfo(ci->getOperand(2), CA, len, StartIdx))
1390 if (ci->getNumOperands() == 3) {
1392 // If the length is 0, we just need to store a null byte
1393 new StoreInst(ConstantInt::get(Type::Int8Ty,0),ci->getOperand(1),ci);
1394 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty,0));
1397 // Make sure there's no % in the constant array
1398 for (unsigned i = 0; i < len; ++i) {
1399 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i))) {
1400 // Check for the null terminator
1401 if (CI->getZExtValue() == '%')
1402 return false; // we found a %, can't optimize
1404 return false; // initializer is not constant int, can't optimize
1408 // Increment length because we want to copy the null byte too
1411 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
1415 ConstantInt::get(SLC.getIntPtrType(),len),
1416 ConstantInt::get(Type::Int32Ty, 1)
1418 new CallInst(SLC.get_memcpy(), args, 4, "", ci);
1419 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty,len));
1422 // The remaining optimizations require the format string to be length 2
1427 // The first character has to be a %
1428 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1429 if (CI->getZExtValue() != '%')
1432 // Get the second character and switch on its value
1433 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1434 switch (CI->getZExtValue()) {
1436 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1437 Value *Len = new CallInst(SLC.get_strlen(),
1438 CastToCStr(ci->getOperand(3), ci),
1439 ci->getOperand(3)->getName()+".len", ci);
1440 Value *Len1 = BinaryOperator::createAdd(Len,
1441 ConstantInt::get(Len->getType(), 1),
1442 Len->getName()+"1", ci);
1443 if (Len1->getType() != SLC.getIntPtrType())
1444 Len1 = CastInst::createIntegerCast(Len1, SLC.getIntPtrType(), false,
1445 Len1->getName(), ci);
1447 CastToCStr(ci->getOperand(1), ci),
1448 CastToCStr(ci->getOperand(3), ci),
1450 ConstantInt::get(Type::Int32Ty,1)
1452 new CallInst(SLC.get_memcpy(), args, 4, "", ci);
1454 // The strlen result is the unincremented number of bytes in the string.
1455 if (!ci->use_empty()) {
1456 if (Len->getType() != ci->getType())
1457 Len = CastInst::createIntegerCast(Len, ci->getType(), false,
1458 Len->getName(), ci);
1459 ci->replaceAllUsesWith(Len);
1461 return ReplaceCallWith(ci, 0);
1464 // sprintf(dest,"%c",chr) -> store chr, dest
1465 CastInst* cast = CastInst::createTruncOrBitCast(
1466 ci->getOperand(3), Type::Int8Ty, "char", ci);
1467 new StoreInst(cast, ci->getOperand(1), ci);
1468 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1469 ConstantInt::get(Type::Int32Ty,1),ci->getOperand(1)->getName()+".end",
1471 new StoreInst(ConstantInt::get(Type::Int8Ty,0),gep,ci);
1472 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
1479 /// This LibCallOptimization will simplify calls to the "fputs" library
1480 /// function. It looks for cases where the result of fputs is not used and the
1481 /// operation can be reduced to something simpler.
1482 /// @brief Simplify the puts library function.
1483 struct VISIBILITY_HIDDEN PutsOptimization : public LibCallOptimization {
1485 /// @brief Default Constructor
1486 PutsOptimization() : LibCallOptimization("fputs",
1487 "Number of 'fputs' calls simplified") {}
1489 /// @brief Make sure that the "fputs" function has the right prototype
1490 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1491 // Just make sure this has 2 arguments
1492 return F->arg_size() == 2;
1495 /// @brief Perform the fputs optimization.
1496 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
1497 // If the result is used, none of these optimizations work
1498 if (!ci->use_empty())
1501 // All the optimizations depend on the length of the first argument and the
1502 // fact that it is a constant string array. Check that now
1503 uint64_t len, StartIdx;
1505 if (!GetConstantStringInfo(ci->getOperand(1), CA, len, StartIdx))
1510 // fputs("",F) -> noop
1514 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
1515 const Type* FILEptr_type = ci->getOperand(2)->getType();
1516 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1517 ci->getOperand(1)->getName()+".byte",ci);
1518 CastInst* casti = new SExtInst(loadi, Type::Int32Ty,
1519 loadi->getName()+".int", ci);
1520 new CallInst(SLC.get_fputc(FILEptr_type), casti,
1521 ci->getOperand(2), "", ci);
1526 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1527 const Type* FILEptr_type = ci->getOperand(2)->getType();
1530 ConstantInt::get(SLC.getIntPtrType(),len),
1531 ConstantInt::get(SLC.getIntPtrType(),1),
1534 new CallInst(SLC.get_fwrite(FILEptr_type), parms, 4, "", ci);
1538 return ReplaceCallWith(ci, 0); // Known to have no uses (see above).
1542 /// This LibCallOptimization will simplify calls to the "isdigit" library
1543 /// function. It simply does range checks the parameter explicitly.
1544 /// @brief Simplify the isdigit library function.
1545 struct VISIBILITY_HIDDEN isdigitOptimization : public LibCallOptimization {
1547 isdigitOptimization() : LibCallOptimization("isdigit",
1548 "Number of 'isdigit' calls simplified") {}
1550 /// @brief Make sure that the "isdigit" function has the right prototype
1551 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1552 // Just make sure this has 1 argument
1553 return (f->arg_size() == 1);
1556 /// @brief Perform the toascii optimization.
1557 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1558 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1))) {
1559 // isdigit(c) -> 0 or 1, if 'c' is constant
1560 uint64_t val = CI->getZExtValue();
1561 if (val >= '0' && val <= '9')
1562 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
1564 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 0));
1567 // isdigit(c) -> (unsigned)c - '0' <= 9
1568 CastInst* cast = CastInst::createIntegerCast(ci->getOperand(1),
1569 Type::Int32Ty, false/*ZExt*/, ci->getOperand(1)->getName()+".uint", ci);
1570 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
1571 ConstantInt::get(Type::Int32Ty,0x30),
1572 ci->getOperand(1)->getName()+".sub",ci);
1573 ICmpInst* setcond_inst = new ICmpInst(ICmpInst::ICMP_ULE,sub_inst,
1574 ConstantInt::get(Type::Int32Ty,9),
1575 ci->getOperand(1)->getName()+".cmp",ci);
1576 CastInst* c2 = new ZExtInst(setcond_inst, Type::Int32Ty,
1577 ci->getOperand(1)->getName()+".isdigit", ci);
1578 return ReplaceCallWith(ci, c2);
1582 struct VISIBILITY_HIDDEN isasciiOptimization : public LibCallOptimization {
1584 isasciiOptimization()
1585 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1587 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1588 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1589 F->getReturnType()->isInteger();
1592 /// @brief Perform the isascii optimization.
1593 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1594 // isascii(c) -> (unsigned)c < 128
1595 Value *V = CI->getOperand(1);
1596 Value *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, V,
1597 ConstantInt::get(V->getType(), 128),
1598 V->getName()+".isascii", CI);
1599 if (Cmp->getType() != CI->getType())
1600 Cmp = new BitCastInst(Cmp, CI->getType(), Cmp->getName(), CI);
1601 return ReplaceCallWith(CI, Cmp);
1606 /// This LibCallOptimization will simplify calls to the "toascii" library
1607 /// function. It simply does the corresponding and operation to restrict the
1608 /// range of values to the ASCII character set (0-127).
1609 /// @brief Simplify the toascii library function.
1610 struct VISIBILITY_HIDDEN ToAsciiOptimization : public LibCallOptimization {
1612 /// @brief Default Constructor
1613 ToAsciiOptimization() : LibCallOptimization("toascii",
1614 "Number of 'toascii' calls simplified") {}
1616 /// @brief Make sure that the "fputs" function has the right prototype
1617 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
1618 // Just make sure this has 2 arguments
1619 return (f->arg_size() == 1);
1622 /// @brief Perform the toascii optimization.
1623 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1624 // toascii(c) -> (c & 0x7f)
1625 Value *chr = ci->getOperand(1);
1626 Value *and_inst = BinaryOperator::createAnd(chr,
1627 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1628 return ReplaceCallWith(ci, and_inst);
1632 /// This LibCallOptimization will simplify calls to the "ffs" library
1633 /// calls which find the first set bit in an int, long, or long long. The
1634 /// optimization is to compute the result at compile time if the argument is
1636 /// @brief Simplify the ffs library function.
1637 struct VISIBILITY_HIDDEN FFSOptimization : public LibCallOptimization {
1639 /// @brief Subclass Constructor
1640 FFSOptimization(const char* funcName, const char* description)
1641 : LibCallOptimization(funcName, description) {}
1644 /// @brief Default Constructor
1645 FFSOptimization() : LibCallOptimization("ffs",
1646 "Number of 'ffs' calls simplified") {}
1648 /// @brief Make sure that the "ffs" function has the right prototype
1649 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1650 // Just make sure this has 2 arguments
1651 return F->arg_size() == 1 && F->getReturnType() == Type::Int32Ty;
1654 /// @brief Perform the ffs optimization.
1655 virtual bool OptimizeCall(CallInst *TheCall, SimplifyLibCalls &SLC) {
1656 if (ConstantInt *CI = dyn_cast<ConstantInt>(TheCall->getOperand(1))) {
1657 // ffs(cnst) -> bit#
1658 // ffsl(cnst) -> bit#
1659 // ffsll(cnst) -> bit#
1660 uint64_t val = CI->getZExtValue();
1664 while ((val & 1) == 0) {
1669 return ReplaceCallWith(TheCall, ConstantInt::get(Type::Int32Ty, result));
1672 // ffs(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1673 // ffsl(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1674 // ffsll(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1675 const Type *ArgType = TheCall->getOperand(1)->getType();
1676 const char *CTTZName;
1677 assert(ArgType->getTypeID() == Type::IntegerTyID &&
1678 "llvm.cttz argument is not an integer?");
1679 unsigned BitWidth = cast<IntegerType>(ArgType)->getBitWidth();
1681 CTTZName = "llvm.cttz.i8";
1682 else if (BitWidth == 16)
1683 CTTZName = "llvm.cttz.i16";
1684 else if (BitWidth == 32)
1685 CTTZName = "llvm.cttz.i32";
1687 assert(BitWidth == 64 && "Unknown bitwidth");
1688 CTTZName = "llvm.cttz.i64";
1691 Constant *F = SLC.getModule()->getOrInsertFunction(CTTZName, ArgType,
1693 Value *V = CastInst::createIntegerCast(TheCall->getOperand(1), ArgType,
1694 false/*ZExt*/, "tmp", TheCall);
1695 Value *V2 = new CallInst(F, V, "tmp", TheCall);
1696 V2 = CastInst::createIntegerCast(V2, Type::Int32Ty, false/*ZExt*/,
1698 V2 = BinaryOperator::createAdd(V2, ConstantInt::get(Type::Int32Ty, 1),
1700 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, V,
1701 Constant::getNullValue(V->getType()), "tmp",
1703 V2 = new SelectInst(Cond, ConstantInt::get(Type::Int32Ty, 0), V2,
1704 TheCall->getName(), TheCall);
1705 return ReplaceCallWith(TheCall, V2);
1709 /// This LibCallOptimization will simplify calls to the "ffsl" library
1710 /// calls. It simply uses FFSOptimization for which the transformation is
1712 /// @brief Simplify the ffsl library function.
1713 struct VISIBILITY_HIDDEN FFSLOptimization : public FFSOptimization {
1715 /// @brief Default Constructor
1716 FFSLOptimization() : FFSOptimization("ffsl",
1717 "Number of 'ffsl' calls simplified") {}
1721 /// This LibCallOptimization will simplify calls to the "ffsll" library
1722 /// calls. It simply uses FFSOptimization for which the transformation is
1724 /// @brief Simplify the ffsl library function.
1725 struct VISIBILITY_HIDDEN FFSLLOptimization : public FFSOptimization {
1727 /// @brief Default Constructor
1728 FFSLLOptimization() : FFSOptimization("ffsll",
1729 "Number of 'ffsll' calls simplified") {}
1733 /// This optimizes unary functions that take and return doubles.
1734 struct UnaryDoubleFPOptimizer : public LibCallOptimization {
1735 UnaryDoubleFPOptimizer(const char *Fn, const char *Desc)
1736 : LibCallOptimization(Fn, Desc) {}
1738 // Make sure that this function has the right prototype
1739 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1740 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1741 F->getReturnType() == Type::DoubleTy;
1744 /// ShrinkFunctionToFloatVersion - If the input to this function is really a
1745 /// float, strength reduce this to a float version of the function,
1746 /// e.g. floor((double)FLT) -> (double)floorf(FLT). This can only be called
1747 /// when the target supports the destination function and where there can be
1748 /// no precision loss.
1749 static bool ShrinkFunctionToFloatVersion(CallInst *CI, SimplifyLibCalls &SLC,
1750 Constant *(SimplifyLibCalls::*FP)()){
1751 if (FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1)))
1752 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
1753 Value *New = new CallInst((SLC.*FP)(), Cast->getOperand(0),
1755 New = new FPExtInst(New, Type::DoubleTy, CI->getName(), CI);
1756 CI->replaceAllUsesWith(New);
1757 CI->eraseFromParent();
1758 if (Cast->use_empty())
1759 Cast->eraseFromParent();
1767 struct VISIBILITY_HIDDEN FloorOptimization : public UnaryDoubleFPOptimizer {
1769 : UnaryDoubleFPOptimizer("floor", "Number of 'floor' calls simplified") {}
1771 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1773 // If this is a float argument passed in, convert to floorf.
1774 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_floorf))
1777 return false; // opt failed
1781 struct VISIBILITY_HIDDEN CeilOptimization : public UnaryDoubleFPOptimizer {
1783 : UnaryDoubleFPOptimizer("ceil", "Number of 'ceil' calls simplified") {}
1785 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1787 // If this is a float argument passed in, convert to ceilf.
1788 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_ceilf))
1791 return false; // opt failed
1795 struct VISIBILITY_HIDDEN RoundOptimization : public UnaryDoubleFPOptimizer {
1797 : UnaryDoubleFPOptimizer("round", "Number of 'round' calls simplified") {}
1799 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1801 // If this is a float argument passed in, convert to roundf.
1802 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_roundf))
1805 return false; // opt failed
1809 struct VISIBILITY_HIDDEN RintOptimization : public UnaryDoubleFPOptimizer {
1811 : UnaryDoubleFPOptimizer("rint", "Number of 'rint' calls simplified") {}
1813 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1815 // If this is a float argument passed in, convert to rintf.
1816 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_rintf))
1819 return false; // opt failed
1823 struct VISIBILITY_HIDDEN NearByIntOptimization : public UnaryDoubleFPOptimizer {
1824 NearByIntOptimization()
1825 : UnaryDoubleFPOptimizer("nearbyint",
1826 "Number of 'nearbyint' calls simplified") {}
1828 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1829 #ifdef HAVE_NEARBYINTF
1830 // If this is a float argument passed in, convert to nearbyintf.
1831 if (ShrinkFunctionToFloatVersion(CI, SLC,&SimplifyLibCalls::get_nearbyintf))
1834 return false; // opt failed
1836 } NearByIntOptimizer;
1838 /// GetConstantStringInfo - This function computes the length of a
1839 /// null-terminated constant array of integers. This function can't rely on the
1840 /// size of the constant array because there could be a null terminator in the
1841 /// middle of the array.
1843 /// We also have to bail out if we find a non-integer constant initializer
1844 /// of one of the elements or if there is no null-terminator. The logic
1845 /// below checks each of these conditions and will return true only if all
1846 /// conditions are met. If the conditions aren't met, this returns false.
1848 /// If successful, the \p Array param is set to the constant array being
1849 /// indexed, the \p Length parameter is set to the length of the null-terminated
1850 /// string pointed to by V, the \p StartIdx value is set to the first
1851 /// element of the Array that V points to, and true is returned.
1852 static bool GetConstantStringInfo(Value *V, ConstantArray *&Array,
1853 uint64_t &Length, uint64_t &StartIdx) {
1854 assert(V != 0 && "Invalid args to GetConstantStringInfo");
1855 // Initialize results.
1861 // If the value is not a GEP instruction nor a constant expression with a
1862 // GEP instruction, then return false because ConstantArray can't occur
1864 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
1866 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1867 if (CE->getOpcode() != Instruction::GetElementPtr)
1874 // Make sure the GEP has exactly three arguments.
1875 if (GEP->getNumOperands() != 3)
1878 // Check to make sure that the first operand of the GEP is an integer and
1879 // has value 0 so that we are sure we're indexing into the initializer.
1880 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1886 // If the second index isn't a ConstantInt, then this is a variable index
1887 // into the array. If this occurs, we can't say anything meaningful about
1890 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1891 StartIdx = CI->getZExtValue();
1895 // The GEP instruction, constant or instruction, must reference a global
1896 // variable that is a constant and is initialized. The referenced constant
1897 // initializer is the array that we'll use for optimization.
1898 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1899 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1901 Constant *GlobalInit = GV->getInitializer();
1903 // Handle the ConstantAggregateZero case
1904 if (isa<ConstantAggregateZero>(GlobalInit)) {
1905 // This is a degenerate case. The initializer is constant zero so the
1906 // length of the string must be zero.
1911 // Must be a Constant Array
1912 Array = dyn_cast<ConstantArray>(GlobalInit);
1913 if (!Array) return false;
1915 // Get the number of elements in the array
1916 uint64_t NumElts = Array->getType()->getNumElements();
1918 // Traverse the constant array from start_idx (derived above) which is
1919 // the place the GEP refers to in the array.
1922 if (Length >= NumElts)
1923 return false; // The array isn't null terminated.
1925 Constant *Elt = Array->getOperand(Length);
1926 if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
1927 // Check for the null terminator.
1929 break; // we found end of string
1931 return false; // This array isn't suitable, non-int initializer
1935 // Subtract out the initial value from the length
1937 return true; // success!
1940 /// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
1941 /// inserting the cast before IP, and return the cast.
1942 /// @brief Cast a value to a "C" string.
1943 static Value *CastToCStr(Value *V, Instruction *IP) {
1944 assert(isa<PointerType>(V->getType()) &&
1945 "Can't cast non-pointer type to C string type");
1946 const Type *SBPTy = PointerType::get(Type::Int8Ty);
1947 if (V->getType() != SBPTy)
1948 return new BitCastInst(V, SBPTy, V->getName(), IP);
1953 // Additional cases that we need to add to this file:
1956 // * cbrt(expN(X)) -> expN(x/3)
1957 // * cbrt(sqrt(x)) -> pow(x,1/6)
1958 // * cbrt(sqrt(x)) -> pow(x,1/9)
1961 // * cos(-x) -> cos(x)
1964 // * exp(log(x)) -> x
1967 // * log(exp(x)) -> x
1968 // * log(x**y) -> y*log(x)
1969 // * log(exp(y)) -> y*log(e)
1970 // * log(exp2(y)) -> y*log(2)
1971 // * log(exp10(y)) -> y*log(10)
1972 // * log(sqrt(x)) -> 0.5*log(x)
1973 // * log(pow(x,y)) -> y*log(x)
1975 // lround, lroundf, lroundl:
1976 // * lround(cnst) -> cnst'
1979 // * memcmp(x,y,l) -> cnst
1980 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1983 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1984 // (if s is a global constant array)
1987 // * pow(exp(x),y) -> exp(x*y)
1988 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1989 // * pow(pow(x,y),z)-> pow(x,y*z)
1992 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1994 // round, roundf, roundl:
1995 // * round(cnst) -> cnst'
1998 // * signbit(cnst) -> cnst'
1999 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2001 // sqrt, sqrtf, sqrtl:
2002 // * sqrt(expN(x)) -> expN(x*0.5)
2003 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2004 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2007 // * stpcpy(str, "literal") ->
2008 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2010 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2011 // (if c is a constant integer and s is a constant string)
2012 // * strrchr(s1,0) -> strchr(s1,0)
2015 // * strncat(x,y,0) -> x
2016 // * strncat(x,y,0) -> x (if strlen(y) = 0)
2017 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2020 // * strncpy(d,s,0) -> d
2021 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
2022 // (if s and l are constants)
2025 // * strpbrk(s,a) -> offset_in_for(s,a)
2026 // (if s and a are both constant strings)
2027 // * strpbrk(s,"") -> 0
2028 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2031 // * strspn(s,a) -> const_int (if both args are constant)
2032 // * strspn("",a) -> 0
2033 // * strspn(s,"") -> 0
2034 // * strcspn(s,a) -> const_int (if both args are constant)
2035 // * strcspn("",a) -> 0
2036 // * strcspn(s,"") -> strlen(a)
2039 // * strstr(x,x) -> x
2040 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2041 // (if s1 and s2 are constant strings)
2044 // * tan(atan(x)) -> x
2046 // trunc, truncf, truncl:
2047 // * trunc(cnst) -> cnst'