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 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.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "simplify-libcalls"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Instructions.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/ADT/hash_map"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Transforms/IPO.h"
35 /// This statistic keeps track of the total number of library calls that have
36 /// been simplified regardless of which call it is.
37 Statistic<> SimplifiedLibCalls("simplify-libcalls",
38 "Number of well-known library calls simplified");
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
44 /// @brief The list of optimizations deriving from LibCallOptimization
45 hash_map<std::string,LibCallOptimization*> optlist;
47 /// This class is the abstract base class for the set of optimizations that
48 /// corresponds to one library call. The SimplifyLibCalls pass will call the
49 /// ValidateCalledFunction method to ask the optimization if a given Function
50 /// is the kind that the optimization can handle. If the subclass returns true,
51 /// then SImplifyLibCalls will also call the OptimizeCall method to perform,
52 /// or attempt to perform, the optimization(s) for the library call. Otherwise,
53 /// OptimizeCall won't be called. Subclasses are responsible for providing the
54 /// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
55 /// constructor. This is used to efficiently select which call instructions to
56 /// optimize. The criteria for a "lib call" is "anything with well known
57 /// semantics", typically a library function that is defined by an international
58 /// standard. Because the semantics are well known, the optimizations can
59 /// generally short-circuit actually calling the function if there's a simpler
60 /// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
61 /// @brief Base class for library call optimizations
62 class LibCallOptimization
65 /// The \p fname argument must be the name of the library function being
66 /// optimized by the subclass.
67 /// @brief Constructor that registers the optimization.
68 LibCallOptimization(const char* fname,
69 const char* stat_name, const char* description )
72 , occurrences(stat_name,description)
75 // Register this call optimizer in the optlist (a hash_map)
76 optlist[fname] = this;
79 /// @brief Deregister from the optlist
80 virtual ~LibCallOptimization() { optlist.erase(func_name); }
82 /// The implementation of this function in subclasses should determine if
83 /// \p F is suitable for the optimization. This method is called by
84 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
85 /// sites of such a function if that function is not suitable in the first
86 /// place. If the called function is suitabe, this method should return true;
87 /// false, otherwise. This function should also perform any lazy
88 /// initialization that the LibCallOptimization needs to do, if its to return
89 /// true. This avoids doing initialization until the optimizer is actually
90 /// going to be called upon to do some optimization.
91 /// @brief Determine if the function is suitable for optimization
92 virtual bool ValidateCalledFunction(
93 const Function* F, ///< The function that is the target of call sites
94 SimplifyLibCalls& SLC ///< The pass object invoking us
97 /// The implementations of this function in subclasses is the heart of the
98 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
99 /// OptimizeCall to determine if (a) the conditions are right for optimizing
100 /// the call and (b) to perform the optimization. If an action is taken
101 /// against ci, the subclass is responsible for returning true and ensuring
102 /// that ci is erased from its parent.
103 /// @brief Optimize a call, if possible.
104 virtual bool OptimizeCall(
105 CallInst* ci, ///< The call instruction that should be optimized.
106 SimplifyLibCalls& SLC ///< The pass object invoking us
109 /// @brief Get the name of the library call being optimized
110 const char * getFunctionName() const { return func_name; }
113 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
114 void succeeded() { ++occurrences; }
118 const char* func_name; ///< Name of the library call we optimize
120 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
124 /// This class is an LLVM Pass that applies each of the LibCallOptimization
125 /// instances to all the call sites in a module, relatively efficiently. The
126 /// purpose of this pass is to provide optimizations for calls to well-known
127 /// functions with well-known semantics, such as those in the c library. The
128 /// class provides the basic infrastructure for handling runOnModule. Whenever /// this pass finds a function call, it asks the appropriate optimizer to
129 /// validate the call (ValidateLibraryCall). If it is validated, then
130 /// the OptimizeCall method is also called.
131 /// @brief A ModulePass for optimizing well-known function calls.
132 class SimplifyLibCalls : public ModulePass
135 /// We need some target data for accurate signature details that are
136 /// target dependent. So we require target data in our AnalysisUsage.
137 /// @brief Require TargetData from AnalysisUsage.
138 virtual void getAnalysisUsage(AnalysisUsage& Info) const
140 // Ask that the TargetData analysis be performed before us so we can use
142 Info.addRequired<TargetData>();
145 /// For this pass, process all of the function calls in the module, calling
146 /// ValidateLibraryCall and OptimizeCall as appropriate.
147 /// @brief Run all the lib call optimizations on a Module.
148 virtual bool runOnModule(Module &M)
154 // The call optimizations can be recursive. That is, the optimization might
155 // generate a call to another function which can also be optimized. This way
156 // we make the LibCallOptimization instances very specific to the case they
157 // handle. It also means we need to keep running over the function calls in
158 // the module until we don't get any more optimizations possible.
159 bool found_optimization = false;
162 found_optimization = false;
163 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
165 // All the "well-known" functions are external and have external linkage
166 // because they live in a runtime library somewhere and were (probably)
167 // not compiled by LLVM. So, we only act on external functions that
168 // have external linkage and non-empty uses.
169 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
172 // Get the optimization class that pertains to this function
173 LibCallOptimization* CO = optlist[FI->getName().c_str()];
177 // Make sure the called function is suitable for the optimization
178 if (!CO->ValidateCalledFunction(FI,*this))
181 // Loop over each of the uses of the function
182 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
185 // If the use of the function is a call instruction
186 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
188 // Do the optimization on the LibCallOptimization.
189 if (CO->OptimizeCall(CI,*this))
191 ++SimplifiedLibCalls;
192 found_optimization = result = true;
200 } while (found_optimization);
204 /// @brief Return the *current* module we're working on.
205 Module* getModule() const { return M; }
207 /// @brief Return the *current* target data for the module we're working on.
208 TargetData* getTargetData() const { return TD; }
210 /// @brief Return the size_t type -- syntactic shortcut
211 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
213 /// @brief Return a Function* for the fputc libcall
214 Function* get_fputc(const Type* FILEptr_type)
218 std::vector<const Type*> args;
219 args.push_back(Type::IntTy);
220 args.push_back(FILEptr_type);
221 FunctionType* fputc_type =
222 FunctionType::get(Type::IntTy, args, false);
223 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
228 /// @brief Return a Function* for the fwrite libcall
229 Function* get_fwrite(const Type* FILEptr_type)
233 std::vector<const Type*> args;
234 args.push_back(PointerType::get(Type::SByteTy));
235 args.push_back(TD->getIntPtrType());
236 args.push_back(TD->getIntPtrType());
237 args.push_back(FILEptr_type);
238 FunctionType* fwrite_type =
239 FunctionType::get(TD->getIntPtrType(), args, false);
240 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
245 /// @brief Return a Function* for the sqrt libcall
250 std::vector<const Type*> args;
251 args.push_back(Type::DoubleTy);
252 FunctionType* sqrt_type =
253 FunctionType::get(Type::DoubleTy, args, false);
254 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
259 /// @brief Return a Function* for the strlen libcall
260 Function* get_strlen()
264 std::vector<const Type*> args;
265 args.push_back(PointerType::get(Type::SByteTy));
266 FunctionType* strlen_type =
267 FunctionType::get(TD->getIntPtrType(), args, false);
268 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
273 /// @brief Return a Function* for the memchr libcall
274 Function* get_memchr()
278 std::vector<const Type*> args;
279 args.push_back(PointerType::get(Type::SByteTy));
280 args.push_back(Type::IntTy);
281 args.push_back(TD->getIntPtrType());
282 FunctionType* memchr_type = FunctionType::get(
283 PointerType::get(Type::SByteTy), args, false);
284 memchr_func = M->getOrInsertFunction("memchr",memchr_type);
289 /// @brief Return a Function* for the memcpy libcall
290 Function* get_memcpy()
294 // Note: this is for llvm.memcpy intrinsic
295 std::vector<const Type*> args;
296 args.push_back(PointerType::get(Type::SByteTy));
297 args.push_back(PointerType::get(Type::SByteTy));
298 args.push_back(Type::IntTy);
299 args.push_back(Type::IntTy);
300 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
301 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
307 /// @brief Reset our cached data for a new Module
308 void reset(Module& mod)
311 TD = &getAnalysis<TargetData>();
321 Function* fputc_func; ///< Cached fputc function
322 Function* fwrite_func; ///< Cached fwrite function
323 Function* memcpy_func; ///< Cached llvm.memcpy function
324 Function* memchr_func; ///< Cached memchr function
325 Function* sqrt_func; ///< Cached sqrt function
326 Function* strlen_func; ///< Cached strlen function
327 Module* M; ///< Cached Module
328 TargetData* TD; ///< Cached TargetData
332 RegisterOpt<SimplifyLibCalls>
333 X("simplify-libcalls","Simplify well-known library calls");
335 } // anonymous namespace
337 // The only public symbol in this file which just instantiates the pass object
338 ModulePass *llvm::createSimplifyLibCallsPass()
340 return new SimplifyLibCalls();
343 // Classes below here, in the anonymous namespace, are all subclasses of the
344 // LibCallOptimization class, each implementing all optimizations possible for a
345 // single well-known library call. Each has a static singleton instance that
346 // auto registers it into the "optlist" global above.
349 // Forward declare a utility function.
350 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
352 /// This LibCallOptimization will find instances of a call to "exit" that occurs
353 /// within the "main" function and change it to a simple "ret" instruction with
354 /// the same value passed to the exit function. When this is done, it splits the
355 /// basic block at the exit(3) call and deletes the call instruction.
356 /// @brief Replace calls to exit in main with a simple return
357 struct ExitInMainOptimization : public LibCallOptimization
359 ExitInMainOptimization() : LibCallOptimization("exit",
360 "simplify-libcalls:exit","Number of 'exit' calls simplified") {}
361 virtual ~ExitInMainOptimization() {}
363 // Make sure the called function looks like exit (int argument, int return
364 // type, external linkage, not varargs).
365 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
367 if (f->arg_size() >= 1)
368 if (f->arg_begin()->getType()->isInteger())
373 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
375 // To be careful, we check that the call to exit is coming from "main", that
376 // main has external linkage, and the return type of main and the argument
377 // to exit have the same type.
378 Function *from = ci->getParent()->getParent();
379 if (from->hasExternalLinkage())
380 if (from->getReturnType() == ci->getOperand(1)->getType())
381 if (from->getName() == "main")
383 // Okay, time to actually do the optimization. First, get the basic
384 // block of the call instruction
385 BasicBlock* bb = ci->getParent();
387 // Create a return instruction that we'll replace the call with.
388 // Note that the argument of the return is the argument of the call
390 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
392 // Split the block at the call instruction which places it in a new
394 bb->splitBasicBlock(ci);
396 // The block split caused a branch instruction to be inserted into
397 // the end of the original block, right after the return instruction
398 // that we put there. That's not a valid block, so delete the branch
400 bb->getInstList().pop_back();
402 // Now we can finally get rid of the call instruction which now lives
403 // in the new basic block.
404 ci->eraseFromParent();
406 // Optimization succeeded, return true.
409 // We didn't pass the criteria for this optimization so return false
412 } ExitInMainOptimizer;
414 /// This LibCallOptimization will simplify a call to the strcat library
415 /// function. The simplification is possible only if the string being
416 /// concatenated is a constant array or a constant expression that results in
417 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
418 /// of the constant string. Both of these calls are further reduced, if possible
419 /// on subsequent passes.
420 /// @brief Simplify the strcat library function.
421 struct StrCatOptimization : public LibCallOptimization
424 /// @brief Default constructor
425 StrCatOptimization() : LibCallOptimization("strcat",
426 "simplify-libcalls:strcat","Number of 'strcat' calls simplified") {}
429 /// @breif Destructor
430 virtual ~StrCatOptimization() {}
432 /// @brief Make sure that the "strcat" function has the right prototype
433 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
435 if (f->getReturnType() == PointerType::get(Type::SByteTy))
436 if (f->arg_size() == 2)
438 Function::const_arg_iterator AI = f->arg_begin();
439 if (AI++->getType() == PointerType::get(Type::SByteTy))
440 if (AI->getType() == PointerType::get(Type::SByteTy))
442 // Indicate this is a suitable call type.
449 /// @brief Optimize the strcat library function
450 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
452 // Extract some information from the instruction
453 Module* M = ci->getParent()->getParent()->getParent();
454 Value* dest = ci->getOperand(1);
455 Value* src = ci->getOperand(2);
457 // Extract the initializer (while making numerous checks) from the
458 // source operand of the call to strcat. If we get null back, one of
459 // a variety of checks in get_GVInitializer failed
461 if (!getConstantStringLength(src,len))
464 // Handle the simple, do-nothing case
467 ci->replaceAllUsesWith(dest);
468 ci->eraseFromParent();
472 // Increment the length because we actually want to memcpy the null
473 // terminator as well.
476 // We need to find the end of the destination string. That's where the
477 // memory is to be moved to. We just generate a call to strlen (further
478 // optimized in another pass). Note that the SLC.get_strlen() call
479 // caches the Function* for us.
480 CallInst* strlen_inst =
481 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
483 // Now that we have the destination's length, we must index into the
484 // destination's pointer to get the actual memcpy destination (end of
485 // the string .. we're concatenating).
486 std::vector<Value*> idx;
487 idx.push_back(strlen_inst);
488 GetElementPtrInst* gep =
489 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
491 // We have enough information to now generate the memcpy call to
492 // do the concatenation for us.
493 std::vector<Value*> vals;
494 vals.push_back(gep); // destination
495 vals.push_back(ci->getOperand(2)); // source
496 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
497 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
498 new CallInst(SLC.get_memcpy(), vals, "", ci);
500 // Finally, substitute the first operand of the strcat call for the
501 // strcat call itself since strcat returns its first operand; and,
502 // kill the strcat CallInst.
503 ci->replaceAllUsesWith(dest);
504 ci->eraseFromParent();
509 /// This LibCallOptimization will simplify a call to the strchr library
510 /// function. It optimizes out cases where the arguments are both constant
511 /// and the result can be determined statically.
512 /// @brief Simplify the strcmp library function.
513 struct StrChrOptimization : public LibCallOptimization
516 StrChrOptimization() : LibCallOptimization("strchr",
517 "simplify-libcalls:strchr","Number of 'strchr' calls simplified") {}
518 virtual ~StrChrOptimization() {}
520 /// @brief Make sure that the "strchr" function has the right prototype
521 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
523 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
529 /// @brief Perform the strcpy optimization
530 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
532 // If there aren't three operands, bail
533 if (ci->getNumOperands() != 3)
536 // Check that the first argument to strchr is a constant array of sbyte.
537 // If it is, get the length and data, otherwise return false.
540 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
543 // Check that the second argument to strchr is a constant int, return false
545 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
548 // Just lower this to memchr since we know the length of the string as
550 Function* f = SLC.get_memchr();
551 std::vector<Value*> args;
552 args.push_back(ci->getOperand(1));
553 args.push_back(ci->getOperand(2));
554 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
555 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
556 ci->eraseFromParent();
560 // Get the character we're looking for
561 int64_t chr = CSI->getValue();
563 // Compute the offset
565 bool char_found = false;
566 for (uint64_t i = 0; i < len; ++i)
568 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
570 // Check for the null terminator
571 if (CI->isNullValue())
572 break; // we found end of string
573 else if (CI->getValue() == chr)
582 // strchr(s,c) -> offset_of_in(c,s)
583 // (if c is a constant integer and s is a constant string)
586 std::vector<Value*> indices;
587 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
588 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
589 ci->getOperand(1)->getName()+".strchr",ci);
590 ci->replaceAllUsesWith(GEP);
593 ci->replaceAllUsesWith(
594 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
596 ci->eraseFromParent();
601 /// This LibCallOptimization will simplify a call to the strcmp library
602 /// function. It optimizes out cases where one or both arguments are constant
603 /// and the result can be determined statically.
604 /// @brief Simplify the strcmp library function.
605 struct StrCmpOptimization : public LibCallOptimization
608 StrCmpOptimization() : LibCallOptimization("strcmp",
609 "simplify-libcalls:strcmp","Number of 'strcmp' calls simplified") {}
610 virtual ~StrCmpOptimization() {}
612 /// @brief Make sure that the "strcpy" function has the right prototype
613 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
615 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
620 /// @brief Perform the strcpy optimization
621 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
623 // First, check to see if src and destination are the same. If they are,
624 // then the optimization is to replace the CallInst with a constant 0
625 // because the call is a no-op.
626 Value* s1 = ci->getOperand(1);
627 Value* s2 = ci->getOperand(2);
631 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
632 ci->eraseFromParent();
636 bool isstr_1 = false;
639 if (getConstantStringLength(s1,len_1,&A1))
644 // strcmp("",x) -> *x
645 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
647 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
648 ci->replaceAllUsesWith(cast);
649 ci->eraseFromParent();
654 bool isstr_2 = false;
657 if (getConstantStringLength(s2,len_2,&A2))
662 // strcmp(x,"") -> *x
663 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
665 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
666 ci->replaceAllUsesWith(cast);
667 ci->eraseFromParent();
672 if (isstr_1 && isstr_2)
674 // strcmp(x,y) -> cnst (if both x and y are constant strings)
675 std::string str1 = A1->getAsString();
676 std::string str2 = A2->getAsString();
677 int result = strcmp(str1.c_str(), str2.c_str());
678 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
679 ci->eraseFromParent();
686 /// This LibCallOptimization will simplify a call to the strncmp library
687 /// function. It optimizes out cases where one or both arguments are constant
688 /// and the result can be determined statically.
689 /// @brief Simplify the strncmp library function.
690 struct StrNCmpOptimization : public LibCallOptimization
693 StrNCmpOptimization() : LibCallOptimization("strncmp",
694 "simplify-libcalls:strncmp","Number of 'strncmp' calls simplified") {}
695 virtual ~StrNCmpOptimization() {}
697 /// @brief Make sure that the "strcpy" function has the right prototype
698 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
700 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
705 /// @brief Perform the strncpy optimization
706 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
708 // First, check to see if src and destination are the same. If they are,
709 // then the optimization is to replace the CallInst with a constant 0
710 // because the call is a no-op.
711 Value* s1 = ci->getOperand(1);
712 Value* s2 = ci->getOperand(2);
715 // strncmp(x,x,l) -> 0
716 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
717 ci->eraseFromParent();
721 // Check the length argument, if it is Constant zero then the strings are
723 uint64_t len_arg = 0;
724 bool len_arg_is_const = false;
725 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
727 len_arg_is_const = true;
728 len_arg = len_CI->getRawValue();
731 // strncmp(x,y,0) -> 0
732 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
733 ci->eraseFromParent();
738 bool isstr_1 = false;
741 if (getConstantStringLength(s1,len_1,&A1))
746 // strncmp("",x) -> *x
747 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
749 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
750 ci->replaceAllUsesWith(cast);
751 ci->eraseFromParent();
756 bool isstr_2 = false;
759 if (getConstantStringLength(s2,len_2,&A2))
764 // strncmp(x,"") -> *x
765 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
767 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
768 ci->replaceAllUsesWith(cast);
769 ci->eraseFromParent();
774 if (isstr_1 && isstr_2 && len_arg_is_const)
776 // strncmp(x,y,const) -> constant
777 std::string str1 = A1->getAsString();
778 std::string str2 = A2->getAsString();
779 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
780 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
781 ci->eraseFromParent();
788 /// This LibCallOptimization will simplify a call to the strcpy library
789 /// function. Two optimizations are possible:
790 /// (1) If src and dest are the same and not volatile, just return dest
791 /// (2) If the src is a constant then we can convert to llvm.memmove
792 /// @brief Simplify the strcpy library function.
793 struct StrCpyOptimization : public LibCallOptimization
796 StrCpyOptimization() : LibCallOptimization("strcpy",
797 "simplify-libcalls:strcpy","Number of 'strcpy' calls simplified") {}
798 virtual ~StrCpyOptimization() {}
800 /// @brief Make sure that the "strcpy" function has the right prototype
801 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
803 if (f->getReturnType() == PointerType::get(Type::SByteTy))
804 if (f->arg_size() == 2)
806 Function::const_arg_iterator AI = f->arg_begin();
807 if (AI++->getType() == PointerType::get(Type::SByteTy))
808 if (AI->getType() == PointerType::get(Type::SByteTy))
810 // Indicate this is a suitable call type.
817 /// @brief Perform the strcpy optimization
818 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
820 // First, check to see if src and destination are the same. If they are,
821 // then the optimization is to replace the CallInst with the destination
822 // because the call is a no-op. Note that this corresponds to the
823 // degenerate strcpy(X,X) case which should have "undefined" results
824 // according to the C specification. However, it occurs sometimes and
825 // we optimize it as a no-op.
826 Value* dest = ci->getOperand(1);
827 Value* src = ci->getOperand(2);
830 ci->replaceAllUsesWith(dest);
831 ci->eraseFromParent();
835 // Get the length of the constant string referenced by the second operand,
836 // the "src" parameter. Fail the optimization if we can't get the length
837 // (note that getConstantStringLength does lots of checks to make sure this
840 if (!getConstantStringLength(ci->getOperand(2),len))
843 // If the constant string's length is zero we can optimize this by just
844 // doing a store of 0 at the first byte of the destination
847 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
848 ci->replaceAllUsesWith(dest);
849 ci->eraseFromParent();
853 // Increment the length because we actually want to memcpy the null
854 // terminator as well.
857 // Extract some information from the instruction
858 Module* M = ci->getParent()->getParent()->getParent();
860 // We have enough information to now generate the memcpy call to
861 // do the concatenation for us.
862 std::vector<Value*> vals;
863 vals.push_back(dest); // destination
864 vals.push_back(src); // source
865 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
866 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
867 new CallInst(SLC.get_memcpy(), vals, "", ci);
869 // Finally, substitute the first operand of the strcat call for the
870 // strcat call itself since strcat returns its first operand; and,
871 // kill the strcat CallInst.
872 ci->replaceAllUsesWith(dest);
873 ci->eraseFromParent();
878 /// This LibCallOptimization will simplify a call to the strlen library
879 /// function by replacing it with a constant value if the string provided to
880 /// it is a constant array.
881 /// @brief Simplify the strlen library function.
882 struct StrLenOptimization : public LibCallOptimization
884 StrLenOptimization() : LibCallOptimization("strlen",
885 "simplify-libcalls:strlen","Number of 'strlen' calls simplified") {}
886 virtual ~StrLenOptimization() {}
888 /// @brief Make sure that the "strlen" function has the right prototype
889 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
891 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
892 if (f->arg_size() == 1)
893 if (Function::const_arg_iterator AI = f->arg_begin())
894 if (AI->getType() == PointerType::get(Type::SByteTy))
899 /// @brief Perform the strlen optimization
900 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
902 // Get the length of the string
904 if (!getConstantStringLength(ci->getOperand(1),len))
907 ci->replaceAllUsesWith(
908 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
909 ci->eraseFromParent();
914 /// This LibCallOptimization will simplify a call to the memcpy library
915 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
916 /// bytes depending on the length of the string and the alignment. Additional
917 /// optimizations are possible in code generation (sequence of immediate store)
918 /// @brief Simplify the memcpy library function.
919 struct LLVMMemCpyOptimization : public LibCallOptimization
921 /// @brief Default Constructor
922 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
923 "simplify-libcalls:llvm.memcpy",
924 "Number of 'llvm.memcpy' calls simplified") {}
927 /// @brief Subclass Constructor
928 LLVMMemCpyOptimization(const char* fname, const char* sname, const char* desc)
929 : LibCallOptimization(fname, sname, desc) {}
931 /// @brief Destructor
932 virtual ~LLVMMemCpyOptimization() {}
934 /// @brief Make sure that the "memcpy" function has the right prototype
935 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
937 // Just make sure this has 4 arguments per LLVM spec.
938 return (f->arg_size() == 4);
941 /// Because of alignment and instruction information that we don't have, we
942 /// leave the bulk of this to the code generators. The optimization here just
943 /// deals with a few degenerate cases where the length of the string and the
944 /// alignment match the sizes of our intrinsic types so we can do a load and
945 /// store instead of the memcpy call.
946 /// @brief Perform the memcpy optimization.
947 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
949 // Make sure we have constant int values to work with
950 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
953 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
957 // If the length is larger than the alignment, we can't optimize
958 uint64_t len = LEN->getRawValue();
959 uint64_t alignment = ALIGN->getRawValue();
961 alignment = 1; // Alignment 0 is identity for alignment 1
965 // Get the type we will cast to, based on size of the string
966 Value* dest = ci->getOperand(1);
967 Value* src = ci->getOperand(2);
972 // memcpy(d,s,0,a) -> noop
973 ci->eraseFromParent();
975 case 1: castType = Type::SByteTy; break;
976 case 2: castType = Type::ShortTy; break;
977 case 4: castType = Type::IntTy; break;
978 case 8: castType = Type::LongTy; break;
983 // Cast source and dest to the right sized primitive and then load/store
985 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
987 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
988 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
989 StoreInst* SI = new StoreInst(LI, DestCast, ci);
990 ci->eraseFromParent();
993 } LLVMMemCpyOptimizer;
995 /// This LibCallOptimization will simplify a call to the memmove library
996 /// function. It is identical to MemCopyOptimization except for the name of
998 /// @brief Simplify the memmove library function.
999 struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
1001 /// @brief Default Constructor
1002 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
1003 "simplify-libcalls:llvm.memmove",
1004 "Number of 'llvm.memmove' calls simplified") {}
1006 } LLVMMemMoveOptimizer;
1008 /// This LibCallOptimization will simplify a call to the memset library
1009 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1010 /// bytes depending on the length argument.
1011 struct LLVMMemSetOptimization : public LibCallOptimization
1013 /// @brief Default Constructor
1014 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
1015 "simplify-libcalls:llvm.memset",
1016 "Number of 'llvm.memset' calls simplified") {}
1019 /// @brief Destructor
1020 virtual ~LLVMMemSetOptimization() {}
1022 /// @brief Make sure that the "memset" function has the right prototype
1023 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1025 // Just make sure this has 3 arguments per LLVM spec.
1026 return (f->arg_size() == 4);
1029 /// Because of alignment and instruction information that we don't have, we
1030 /// leave the bulk of this to the code generators. The optimization here just
1031 /// deals with a few degenerate cases where the length parameter is constant
1032 /// and the alignment matches the sizes of our intrinsic types so we can do
1033 /// store instead of the memcpy call. Other calls are transformed into the
1034 /// llvm.memset intrinsic.
1035 /// @brief Perform the memset optimization.
1036 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1038 // Make sure we have constant int values to work with
1039 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1042 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1046 // Extract the length and alignment
1047 uint64_t len = LEN->getRawValue();
1048 uint64_t alignment = ALIGN->getRawValue();
1050 // Alignment 0 is identity for alignment 1
1054 // If the length is zero, this is a no-op
1057 // memset(d,c,0,a) -> noop
1058 ci->eraseFromParent();
1062 // If the length is larger than the alignment, we can't optimize
1063 if (len > alignment)
1066 // Make sure we have a constant ubyte to work with so we can extract
1067 // the value to be filled.
1068 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1071 if (FILL->getType() != Type::UByteTy)
1074 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1076 // Extract the fill character
1077 uint64_t fill_char = FILL->getValue();
1078 uint64_t fill_value = fill_char;
1080 // Get the type we will cast to, based on size of memory area to fill, and
1081 // and the value we will store there.
1082 Value* dest = ci->getOperand(1);
1087 castType = Type::UByteTy;
1090 castType = Type::UShortTy;
1091 fill_value |= fill_char << 8;
1094 castType = Type::UIntTy;
1095 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1098 castType = Type::ULongTy;
1099 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1100 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1101 fill_value |= fill_char << 56;
1107 // Cast dest to the right sized primitive and then load/store
1108 CastInst* DestCast =
1109 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1110 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1111 ci->eraseFromParent();
1114 } LLVMMemSetOptimizer;
1116 /// This LibCallOptimization will simplify calls to the "pow" library
1117 /// function. It looks for cases where the result of pow is well known and
1118 /// substitutes the appropriate value.
1119 /// @brief Simplify the pow library function.
1120 struct PowOptimization : public LibCallOptimization
1123 /// @brief Default Constructor
1124 PowOptimization() : LibCallOptimization("pow",
1125 "simplify-libcalls:pow", "Number of 'pow' calls simplified") {}
1127 /// @brief Destructor
1128 virtual ~PowOptimization() {}
1130 /// @brief Make sure that the "pow" function has the right prototype
1131 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1133 // Just make sure this has 2 arguments
1134 return (f->arg_size() == 2);
1137 /// @brief Perform the pow optimization.
1138 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1140 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1141 Value* base = ci->getOperand(1);
1142 Value* expn = ci->getOperand(2);
1143 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1144 double Op1V = Op1->getValue();
1147 // pow(1.0,x) -> 1.0
1148 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1149 ci->eraseFromParent();
1153 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
1155 double Op2V = Op2->getValue();
1158 // pow(x,0.0) -> 1.0
1159 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1160 ci->eraseFromParent();
1163 else if (Op2V == 0.5)
1165 // pow(x,0.5) -> sqrt(x)
1166 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1167 ci->getName()+".pow",ci);
1168 ci->replaceAllUsesWith(sqrt_inst);
1169 ci->eraseFromParent();
1172 else if (Op2V == 1.0)
1175 ci->replaceAllUsesWith(base);
1176 ci->eraseFromParent();
1179 else if (Op2V == -1.0)
1181 // pow(x,-1.0) -> 1.0/x
1182 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
1183 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1184 ci->replaceAllUsesWith(div_inst);
1185 ci->eraseFromParent();
1189 return false; // opt failed
1193 /// This LibCallOptimization will simplify calls to the "fprintf" library
1194 /// function. It looks for cases where the result of fprintf is not used and the
1195 /// operation can be reduced to something simpler.
1196 /// @brief Simplify the pow library function.
1197 struct FPrintFOptimization : public LibCallOptimization
1200 /// @brief Default Constructor
1201 FPrintFOptimization() : LibCallOptimization("fprintf",
1202 "simplify-libcalls:fprintf", "Number of 'fprintf' calls simplified") {}
1204 /// @brief Destructor
1205 virtual ~FPrintFOptimization() {}
1207 /// @brief Make sure that the "fprintf" function has the right prototype
1208 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1210 // Just make sure this has at least 2 arguments
1211 return (f->arg_size() >= 2);
1214 /// @brief Perform the fprintf optimization.
1215 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1217 // If the call has more than 3 operands, we can't optimize it
1218 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1221 // If the result of the fprintf call is used, none of these optimizations
1223 if (!ci->hasNUses(0))
1226 // All the optimizations depend on the length of the second argument and the
1227 // fact that it is a constant string array. Check that now
1229 ConstantArray* CA = 0;
1230 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1233 if (ci->getNumOperands() == 3)
1235 // Make sure there's no % in the constant array
1236 for (unsigned i = 0; i < len; ++i)
1238 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1240 // Check for the null terminator
1241 if (CI->getRawValue() == '%')
1242 return false; // we found end of string
1248 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1file)
1249 const Type* FILEptr_type = ci->getOperand(1)->getType();
1250 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1253 std::vector<Value*> args;
1254 args.push_back(ci->getOperand(2));
1255 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1256 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1257 args.push_back(ci->getOperand(1));
1258 new CallInst(fwrite_func,args,"",ci);
1259 ci->eraseFromParent();
1263 // The remaining optimizations require the format string to be length 2
1268 // The first character has to be a %
1269 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1270 if (CI->getRawValue() != '%')
1273 // Get the second character and switch on its value
1274 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1275 switch (CI->getRawValue())
1280 ConstantArray* CA = 0;
1281 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1284 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1,file)
1285 const Type* FILEptr_type = ci->getOperand(1)->getType();
1286 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1289 std::vector<Value*> args;
1290 args.push_back(ci->getOperand(3));
1291 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1292 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1293 args.push_back(ci->getOperand(1));
1294 new CallInst(fwrite_func,args,"",ci);
1299 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1303 const Type* FILEptr_type = ci->getOperand(1)->getType();
1304 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1307 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1308 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
1314 ci->eraseFromParent();
1320 /// This LibCallOptimization will simplify calls to the "fputs" library
1321 /// function. It looks for cases where the result of fputs is not used and the
1322 /// operation can be reduced to something simpler.
1323 /// @brief Simplify the pow library function.
1324 struct PutsOptimization : public LibCallOptimization
1327 /// @brief Default Constructor
1328 PutsOptimization() : LibCallOptimization("fputs",
1329 "simplify-libcalls:fputs", "Number of 'fputs' calls simplified") {}
1331 /// @brief Destructor
1332 virtual ~PutsOptimization() {}
1334 /// @brief Make sure that the "fputs" function has the right prototype
1335 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1337 // Just make sure this has 2 arguments
1338 return (f->arg_size() == 2);
1341 /// @brief Perform the fputs optimization.
1342 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1344 // If the result is used, none of these optimizations work
1345 if (!ci->hasNUses(0))
1348 // All the optimizations depend on the length of the first argument and the
1349 // fact that it is a constant string array. Check that now
1351 if (!getConstantStringLength(ci->getOperand(1), len))
1357 // fputs("",F) -> noop
1361 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
1362 const Type* FILEptr_type = ci->getOperand(2)->getType();
1363 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1366 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1367 ci->getOperand(1)->getName()+".byte",ci);
1368 CastInst* casti = new CastInst(loadi,Type::IntTy,
1369 loadi->getName()+".int",ci);
1370 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1375 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1376 const Type* FILEptr_type = ci->getOperand(2)->getType();
1377 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1380 std::vector<Value*> parms;
1381 parms.push_back(ci->getOperand(1));
1382 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1383 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1384 parms.push_back(ci->getOperand(2));
1385 new CallInst(fwrite_func,parms,"",ci);
1389 ci->eraseFromParent();
1390 return true; // success
1394 /// This LibCallOptimization will simplify calls to the "toascii" library
1395 /// function. It simply does the corresponding and operation to restrict the
1396 /// range of values to the ASCII character set (0-127).
1397 /// @brief Simplify the toascii library function.
1398 struct ToAsciiOptimization : public LibCallOptimization
1401 /// @brief Default Constructor
1402 ToAsciiOptimization() : LibCallOptimization("toascii",
1403 "simplify-libcalls:toascii", "Number of 'toascii' calls simplified") {}
1405 /// @brief Destructor
1406 virtual ~ToAsciiOptimization() {}
1408 /// @brief Make sure that the "fputs" function has the right prototype
1409 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1411 // Just make sure this has 2 arguments
1412 return (f->arg_size() == 1);
1415 /// @brief Perform the toascii optimization.
1416 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1418 // toascii(c) -> (c & 0x7f)
1419 Value* chr = ci->getOperand(1);
1420 BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1421 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1422 ci->replaceAllUsesWith(and_inst);
1423 ci->eraseFromParent();
1428 /// A function to compute the length of a null-terminated constant array of
1429 /// integers. This function can't rely on the size of the constant array
1430 /// because there could be a null terminator in the middle of the array.
1431 /// We also have to bail out if we find a non-integer constant initializer
1432 /// of one of the elements or if there is no null-terminator. The logic
1433 /// below checks each of these conditions and will return true only if all
1434 /// conditions are met. In that case, the \p len parameter is set to the length
1435 /// of the null-terminated string. If false is returned, the conditions were
1436 /// not met and len is set to 0.
1437 /// @brief Get the length of a constant string (null-terminated array).
1438 bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
1440 assert(V != 0 && "Invalid args to getConstantStringLength");
1441 len = 0; // make sure we initialize this
1443 // If the value is not a GEP instruction nor a constant expression with a
1444 // GEP instruction, then return false because ConstantArray can't occur
1446 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1448 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1449 if (CE->getOpcode() == Instruction::GetElementPtr)
1456 // Make sure the GEP has exactly three arguments.
1457 if (GEP->getNumOperands() != 3)
1460 // Check to make sure that the first operand of the GEP is an integer and
1461 // has value 0 so that we are sure we're indexing into the initializer.
1462 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1464 if (!op1->isNullValue())
1470 // Ensure that the second operand is a ConstantInt. If it isn't then this
1471 // GEP is wonky and we're not really sure what were referencing into and
1472 // better of not optimizing it. While we're at it, get the second index
1473 // value. We'll need this later for indexing the ConstantArray.
1474 uint64_t start_idx = 0;
1475 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1476 start_idx = CI->getRawValue();
1480 // The GEP instruction, constant or instruction, must reference a global
1481 // variable that is a constant and is initialized. The referenced constant
1482 // initializer is the array that we'll use for optimization.
1483 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1484 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1487 // Get the initializer.
1488 Constant* INTLZR = GV->getInitializer();
1490 // Handle the ConstantAggregateZero case
1491 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1493 // This is a degenerate case. The initializer is constant zero so the
1494 // length of the string must be zero.
1499 // Must be a Constant Array
1500 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1504 // Get the number of elements in the array
1505 uint64_t max_elems = A->getType()->getNumElements();
1507 // Traverse the constant array from start_idx (derived above) which is
1508 // the place the GEP refers to in the array.
1509 for ( len = start_idx; len < max_elems; len++)
1511 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1513 // Check for the null terminator
1514 if (CI->isNullValue())
1515 break; // we found end of string
1518 return false; // This array isn't suitable, non-int initializer
1520 if (len >= max_elems)
1521 return false; // This array isn't null terminated
1523 // Subtract out the initial value from the length
1527 return true; // success!
1531 // Additional cases that we need to add to this file:
1534 // * cbrt(expN(X)) -> expN(x/3)
1535 // * cbrt(sqrt(x)) -> pow(x,1/6)
1536 // * cbrt(sqrt(x)) -> pow(x,1/9)
1539 // * cos(-x) -> cos(x)
1542 // * exp(log(x)) -> x
1544 // ffs, ffsl, ffsll:
1545 // * ffs(cnst) -> cnst'
1548 // * isascii(c) -> ((c & ~0x7f) == 0)
1551 // * isdigit(c) -> (unsigned)(c) - '0' <= 9
1554 // * log(exp(x)) -> x
1555 // * log(x**y) -> y*log(x)
1556 // * log(exp(y)) -> y*log(e)
1557 // * log(exp2(y)) -> y*log(2)
1558 // * log(exp10(y)) -> y*log(10)
1559 // * log(sqrt(x)) -> 0.5*log(x)
1560 // * log(pow(x,y)) -> y*log(x)
1562 // lround, lroundf, lroundl:
1563 // * lround(cnst) -> cnst'
1566 // * memcmp(s1,s2,0) -> 0
1567 // * memcmp(x,x,l) -> 0
1568 // * memcmp(x,y,l) -> cnst
1569 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1570 // * memcmp(x,y,1) -> *x - *y
1573 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1574 // (if s is a global constant array)
1577 // * pow(exp(x),y) -> exp(x*y)
1578 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1579 // * pow(pow(x,y),z)-> pow(x,y*z)
1582 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1584 // round, roundf, roundl:
1585 // * round(cnst) -> cnst'
1588 // * signbit(cnst) -> cnst'
1589 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1592 // * sprintf(dest,fmt) -> strcpy(dest,fmt)
1593 // (if fmt is constant and constains no % characters)
1594 // * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
1595 // (only if the sprintf result is not used)
1597 // sqrt, sqrtf, sqrtl:
1598 // * sqrt(expN(x)) -> expN(x*0.5)
1599 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1600 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1603 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1604 // (if c is a constant integer and s is a constant string)
1605 // * strrchr(s1,0) -> strchr(s1,0)
1608 // * strncat(x,y,0) -> x
1609 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1610 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1613 // * strncpy(d,s,0) -> d
1614 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1615 // (if s and l are constants)
1618 // * strpbrk(s,a) -> offset_in_for(s,a)
1619 // (if s and a are both constant strings)
1620 // * strpbrk(s,"") -> 0
1621 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1624 // * strspn(s,a) -> const_int (if both args are constant)
1625 // * strspn("",a) -> 0
1626 // * strspn(s,"") -> 0
1627 // * strcspn(s,a) -> const_int (if both args are constant)
1628 // * strcspn("",a) -> 0
1629 // * strcspn(s,"") -> strlen(a)
1632 // * strstr(x,x) -> x
1633 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1634 // (if s1 and s2 are constant strings)
1637 // * tan(atan(x)) -> x
1639 // trunc, truncf, truncl:
1640 // * trunc(cnst) -> cnst'