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 )
71 , stat_name(std::string("simplify-libcalls:")+fname)
72 , occurrences(stat_name.c_str(),"Number of calls simplified")
75 // Register this call optimizer in the optlist (a hash_map)
76 optlist[func_name] = 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 std::string stat_name; ///< Holder for debug statistic name
121 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
125 /// This class is an LLVM Pass that applies each of the LibCallOptimization
126 /// instances to all the call sites in a module, relatively efficiently. The
127 /// purpose of this pass is to provide optimizations for calls to well-known
128 /// functions with well-known semantics, such as those in the c library. The
129 /// class provides the basic infrastructure for handling runOnModule. Whenever /// this pass finds a function call, it asks the appropriate optimizer to
130 /// validate the call (ValidateLibraryCall). If it is validated, then
131 /// the OptimizeCall method is also called.
132 /// @brief A ModulePass for optimizing well-known function calls.
133 class SimplifyLibCalls : public ModulePass
136 /// We need some target data for accurate signature details that are
137 /// target dependent. So we require target data in our AnalysisUsage.
138 /// @brief Require TargetData from AnalysisUsage.
139 virtual void getAnalysisUsage(AnalysisUsage& Info) const
141 // Ask that the TargetData analysis be performed before us so we can use
143 Info.addRequired<TargetData>();
146 /// For this pass, process all of the function calls in the module, calling
147 /// ValidateLibraryCall and OptimizeCall as appropriate.
148 /// @brief Run all the lib call optimizations on a Module.
149 virtual bool runOnModule(Module &M)
155 // The call optimizations can be recursive. That is, the optimization might
156 // generate a call to another function which can also be optimized. This way
157 // we make the LibCallOptimization instances very specific to the case they
158 // handle. It also means we need to keep running over the function calls in
159 // the module until we don't get any more optimizations possible.
160 bool found_optimization = false;
163 found_optimization = false;
164 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
166 // All the "well-known" functions are external and have external linkage
167 // because they live in a runtime library somewhere and were (probably)
168 // not compiled by LLVM. So, we only act on external functions that have
169 // external linkage and non-empty uses.
170 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
173 // Get the optimization class that pertains to this function
174 LibCallOptimization* CO = optlist[FI->getName().c_str()];
178 // Make sure the called function is suitable for the optimization
179 if (!CO->ValidateCalledFunction(FI,*this))
182 // Loop over each of the uses of the function
183 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
186 // If the use of the function is a call instruction
187 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
189 // Do the optimization on the LibCallOptimization.
190 if (CO->OptimizeCall(CI,*this))
192 ++SimplifiedLibCalls;
193 found_optimization = result = true;
201 } while (found_optimization);
205 /// @brief Return the *current* module we're working on.
206 Module* getModule() { return M; }
208 /// @brief Return the *current* target data for the module we're working on.
209 TargetData* getTargetData() { return TD; }
211 /// @brief Return a Function* for the strlen libcall
212 Function* get_strlen()
216 std::vector<const Type*> args;
217 args.push_back(PointerType::get(Type::SByteTy));
218 FunctionType* strlen_type =
219 FunctionType::get(TD->getIntPtrType(), args, false);
220 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
225 /// @brief Return a Function* for the memcpy libcall
226 Function* get_memcpy()
230 // Note: this is for llvm.memcpy intrinsic
231 std::vector<const Type*> args;
232 args.push_back(PointerType::get(Type::SByteTy));
233 args.push_back(PointerType::get(Type::SByteTy));
234 args.push_back(Type::IntTy);
235 args.push_back(Type::IntTy);
236 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
237 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
243 /// @brief Reset our cached data for a new Module
244 void reset(Module& mod)
247 TD = &getAnalysis<TargetData>();
253 Function* memcpy_func; ///< Cached llvm.memcpy function
254 Function* strlen_func; ///< Cached strlen function
255 Module* M; ///< Cached Module
256 TargetData* TD; ///< Cached TargetData
260 RegisterOpt<SimplifyLibCalls>
261 X("simplify-libcalls","Simplify well-known library calls");
263 } // anonymous namespace
265 // The only public symbol in this file which just instantiates the pass object
266 ModulePass *llvm::createSimplifyLibCallsPass()
268 return new SimplifyLibCalls();
271 // Classes below here, in the anonymous namespace, are all subclasses of the
272 // LibCallOptimization class, each implementing all optimizations possible for a
273 // single well-known library call. Each has a static singleton instance that
274 // auto registers it into the "optlist" global above.
277 // Forward declare a utility function.
278 bool getConstantStringLength(Value* V, uint64_t& len );
280 /// This LibCallOptimization will find instances of a call to "exit" that occurs
281 /// within the "main" function and change it to a simple "ret" instruction with
282 /// the same value passed to the exit function. When this is done, it splits the
283 /// basic block at the exit(3) call and deletes the call instruction.
284 /// @brief Replace calls to exit in main with a simple return
285 struct ExitInMainOptimization : public LibCallOptimization
287 ExitInMainOptimization() : LibCallOptimization("exit") {}
288 virtual ~ExitInMainOptimization() {}
290 // Make sure the called function looks like exit (int argument, int return
291 // type, external linkage, not varargs).
292 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
294 if (f->arg_size() >= 1)
295 if (f->arg_begin()->getType()->isInteger())
300 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
302 // To be careful, we check that the call to exit is coming from "main", that
303 // main has external linkage, and the return type of main and the argument
304 // to exit have the same type.
305 Function *from = ci->getParent()->getParent();
306 if (from->hasExternalLinkage())
307 if (from->getReturnType() == ci->getOperand(1)->getType())
308 if (from->getName() == "main")
310 // Okay, time to actually do the optimization. First, get the basic
311 // block of the call instruction
312 BasicBlock* bb = ci->getParent();
314 // Create a return instruction that we'll replace the call with.
315 // Note that the argument of the return is the argument of the call
317 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
319 // Split the block at the call instruction which places it in a new
321 bb->splitBasicBlock(ci);
323 // The block split caused a branch instruction to be inserted into
324 // the end of the original block, right after the return instruction
325 // that we put there. That's not a valid block, so delete the branch
327 bb->getInstList().pop_back();
329 // Now we can finally get rid of the call instruction which now lives
330 // in the new basic block.
331 ci->eraseFromParent();
333 // Optimization succeeded, return true.
336 // We didn't pass the criteria for this optimization so return false
339 } ExitInMainOptimizer;
341 /// This LibCallOptimization will simplify a call to the strcat library
342 /// function. The simplification is possible only if the string being
343 /// concatenated is a constant array or a constant expression that results in
344 /// a constant string. In this case we can replace it with strlen + llvm.memcpy
345 /// of the constant string. Both of these calls are further reduced, if possible
346 /// on subsequent passes.
347 /// @brief Simplify the strcat library function.
348 struct StrCatOptimization : public LibCallOptimization
351 /// @brief Default constructor
352 StrCatOptimization() : LibCallOptimization("strcat") {}
355 /// @breif Destructor
356 virtual ~StrCatOptimization() {}
358 /// @brief Make sure that the "strcat" function has the right prototype
359 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
361 if (f->getReturnType() == PointerType::get(Type::SByteTy))
362 if (f->arg_size() == 2)
364 Function::const_arg_iterator AI = f->arg_begin();
365 if (AI++->getType() == PointerType::get(Type::SByteTy))
366 if (AI->getType() == PointerType::get(Type::SByteTy))
368 // Indicate this is a suitable call type.
375 /// @brief Optimize the strcat library function
376 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
378 // Extract some information from the instruction
379 Module* M = ci->getParent()->getParent()->getParent();
380 Value* dest = ci->getOperand(1);
381 Value* src = ci->getOperand(2);
383 // Extract the initializer (while making numerous checks) from the
384 // source operand of the call to strcat. If we get null back, one of
385 // a variety of checks in get_GVInitializer failed
387 if (!getConstantStringLength(src,len))
390 // Handle the simple, do-nothing case
393 ci->replaceAllUsesWith(dest);
394 ci->eraseFromParent();
398 // Increment the length because we actually want to memcpy the null
399 // terminator as well.
403 // We need to find the end of the destination string. That's where the
404 // memory is to be moved to. We just generate a call to strlen (further
405 // optimized in another pass). Note that the SLC.get_strlen() call
406 // caches the Function* for us.
407 CallInst* strlen_inst =
408 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
410 // Now that we have the destination's length, we must index into the
411 // destination's pointer to get the actual memcpy destination (end of
412 // the string .. we're concatenating).
413 std::vector<Value*> idx;
414 idx.push_back(strlen_inst);
415 GetElementPtrInst* gep =
416 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
418 // We have enough information to now generate the memcpy call to
419 // do the concatenation for us.
420 std::vector<Value*> vals;
421 vals.push_back(gep); // destination
422 vals.push_back(ci->getOperand(2)); // source
423 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
424 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
425 new CallInst(SLC.get_memcpy(), vals, "", ci);
427 // Finally, substitute the first operand of the strcat call for the
428 // strcat call itself since strcat returns its first operand; and,
429 // kill the strcat CallInst.
430 ci->replaceAllUsesWith(dest);
431 ci->eraseFromParent();
436 /// This LibCallOptimization will simplify a call to the strcpy library
437 /// function. Two optimizations are possible:
438 /// (1) If src and dest are the same and not volatile, just return dest
439 /// (2) If the src is a constant then we can convert to llvm.memmove
440 /// @brief Simplify the strcpy library function.
441 struct StrCpyOptimization : public LibCallOptimization
444 StrCpyOptimization() : LibCallOptimization("strcpy") {}
445 virtual ~StrCpyOptimization() {}
447 /// @brief Make sure that the "strcpy" function has the right prototype
448 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
450 if (f->getReturnType() == PointerType::get(Type::SByteTy))
451 if (f->arg_size() == 2)
453 Function::const_arg_iterator AI = f->arg_begin();
454 if (AI++->getType() == PointerType::get(Type::SByteTy))
455 if (AI->getType() == PointerType::get(Type::SByteTy))
457 // Indicate this is a suitable call type.
464 /// @brief Perform the strcpy optimization
465 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
467 // First, check to see if src and destination are the same. If they are,
468 // then the optimization is to replace the CallInst with the destination
469 // because the call is a no-op. Note that this corresponds to the
470 // degenerate strcpy(X,X) case which should have "undefined" results
471 // according to the C specification. However, it occurs sometimes and
472 // we optimize it as a no-op.
473 Value* dest = ci->getOperand(1);
474 Value* src = ci->getOperand(2);
477 ci->replaceAllUsesWith(dest);
478 ci->eraseFromParent();
482 // Get the length of the constant string referenced by the second operand,
483 // the "src" parameter. Fail the optimization if we can't get the length
484 // (note that getConstantStringLength does lots of checks to make sure this
487 if (!getConstantStringLength(ci->getOperand(2),len))
490 // If the constant string's length is zero we can optimize this by just
491 // doing a store of 0 at the first byte of the destination
494 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
495 ci->replaceAllUsesWith(dest);
496 ci->eraseFromParent();
500 // Increment the length because we actually want to memcpy the null
501 // terminator as well.
504 // Extract some information from the instruction
505 Module* M = ci->getParent()->getParent()->getParent();
507 // We have enough information to now generate the memcpy call to
508 // do the concatenation for us.
509 std::vector<Value*> vals;
510 vals.push_back(dest); // destination
511 vals.push_back(src); // source
512 vals.push_back(ConstantSInt::get(Type::IntTy,len)); // length
513 vals.push_back(ConstantSInt::get(Type::IntTy,1)); // alignment
514 new CallInst(SLC.get_memcpy(), vals, "", ci);
516 // Finally, substitute the first operand of the strcat call for the
517 // strcat call itself since strcat returns its first operand; and,
518 // kill the strcat CallInst.
519 ci->replaceAllUsesWith(dest);
520 ci->eraseFromParent();
525 /// This LibCallOptimization will simplify a call to the strlen library
526 /// function by replacing it with a constant value if the string provided to
527 /// it is a constant array.
528 /// @brief Simplify the strlen library function.
529 struct StrLenOptimization : public LibCallOptimization
531 StrLenOptimization() : LibCallOptimization("strlen") {}
532 virtual ~StrLenOptimization() {}
534 /// @brief Make sure that the "strlen" function has the right prototype
535 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
537 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
538 if (f->arg_size() == 1)
539 if (Function::const_arg_iterator AI = f->arg_begin())
540 if (AI->getType() == PointerType::get(Type::SByteTy))
545 /// @brief Perform the strlen optimization
546 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
548 // Get the length of the string
550 if (!getConstantStringLength(ci->getOperand(1),len))
553 ci->replaceAllUsesWith(
554 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
555 ci->eraseFromParent();
560 /// This LibCallOptimization will simplify a call to the memcpy library
561 /// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
562 /// bytes depending on the length of the string and the alignment. Additional
563 /// optimizations are possible in code generation (sequence of immediate store)
564 /// @brief Simplify the memcpy library function.
565 struct MemCpyOptimization : public LibCallOptimization
567 /// @brief Default Constructor
568 MemCpyOptimization() : LibCallOptimization("llvm.memcpy") {}
570 /// @brief Subclass Constructor
571 MemCpyOptimization(const char* fname) : LibCallOptimization(fname) {}
573 /// @brief Destructor
574 virtual ~MemCpyOptimization() {}
576 /// @brief Make sure that the "memcpy" function has the right prototype
577 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
579 // Just make sure this has 4 arguments per LLVM spec.
580 return (f->arg_size() == 4);
583 /// Because of alignment and instruction information that we don't have, we
584 /// leave the bulk of this to the code generators. The optimization here just
585 /// deals with a few degenerate cases where the length of the string and the
586 /// alignment match the sizes of our intrinsic types so we can do a load and
587 /// store instead of the memcpy call.
588 /// @brief Perform the memcpy optimization.
589 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
591 // Make sure we have constant int values to work with
592 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
595 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
599 // If the length is larger than the alignment, we can't optimize
600 uint64_t len = LEN->getRawValue();
601 uint64_t alignment = ALIGN->getRawValue();
605 // Get the type we will cast to, based on size of the string
606 Value* dest = ci->getOperand(1);
607 Value* src = ci->getOperand(2);
612 // The memcpy is a no-op so just dump its call.
613 ci->eraseFromParent();
615 case 1: castType = Type::SByteTy; break;
616 case 2: castType = Type::ShortTy; break;
617 case 4: castType = Type::IntTy; break;
618 case 8: castType = Type::LongTy; break;
623 // Cast source and dest to the right sized primitive and then load/store
625 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
627 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
628 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
629 StoreInst* SI = new StoreInst(LI, DestCast, ci);
630 ci->eraseFromParent();
635 /// This LibCallOptimization will simplify a call to the memmove library
636 /// function. It is identical to MemCopyOptimization except for the name of
638 /// @brief Simplify the memmove library function.
639 struct MemMoveOptimization : public MemCpyOptimization
641 /// @brief Default Constructor
642 MemMoveOptimization() : MemCpyOptimization("llvm.memmove") {}
646 /// A function to compute the length of a null-terminated constant array of
647 /// integers. This function can't rely on the size of the constant array
648 /// because there could be a null terminator in the middle of the array.
649 /// We also have to bail out if we find a non-integer constant initializer
650 /// of one of the elements or if there is no null-terminator. The logic
651 /// below checks each of these conditions and will return true only if all
652 /// conditions are met. In that case, the \p len parameter is set to the length
653 /// of the null-terminated string. If false is returned, the conditions were
654 /// not met and len is set to 0.
655 /// @brief Get the length of a constant string (null-terminated array).
656 bool getConstantStringLength(Value* V, uint64_t& len )
658 assert(V != 0 && "Invalid args to getConstantStringLength");
659 len = 0; // make sure we initialize this
661 // If the value is not a GEP instruction nor a constant expression with a
662 // GEP instruction, then return false because ConstantArray can't occur
664 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
666 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
667 if (CE->getOpcode() == Instruction::GetElementPtr)
674 // Make sure the GEP has exactly three arguments.
675 if (GEP->getNumOperands() != 3)
678 // Check to make sure that the first operand of the GEP is an integer and
679 // has value 0 so that we are sure we're indexing into the initializer.
680 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
682 if (!op1->isNullValue())
688 // Ensure that the second operand is a ConstantInt. If it isn't then this
689 // GEP is wonky and we're not really sure what were referencing into and
690 // better of not optimizing it. While we're at it, get the second index
691 // value. We'll need this later for indexing the ConstantArray.
692 uint64_t start_idx = 0;
693 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
694 start_idx = CI->getRawValue();
698 // The GEP instruction, constant or instruction, must reference a global
699 // variable that is a constant and is initialized. The referenced constant
700 // initializer is the array that we'll use for optimization.
701 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
702 if (!GV || !GV->isConstant() || !GV->hasInitializer())
705 // Get the initializer.
706 Constant* INTLZR = GV->getInitializer();
708 // Handle the ConstantAggregateZero case
709 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
711 // This is a degenerate case. The initializer is constant zero so the
712 // length of the string must be zero.
717 // Must be a Constant Array
718 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
722 // Get the number of elements in the array
723 uint64_t max_elems = A->getType()->getNumElements();
725 // Traverse the constant array from start_idx (derived above) which is
726 // the place the GEP refers to in the array.
727 for ( len = start_idx; len < max_elems; len++)
729 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
731 // Check for the null terminator
732 if (CI->isNullValue())
733 break; // we found end of string
736 return false; // This array isn't suitable, non-int initializer
738 if (len >= max_elems)
739 return false; // This array isn't null terminated
741 // Subtract out the initial value from the length
743 return true; // success!
747 // Additional cases that we need to add to this file:
750 // * cbrt(expN(X)) -> expN(x/3)
751 // * cbrt(sqrt(x)) -> pow(x,1/6)
752 // * cbrt(sqrt(x)) -> pow(x,1/9)
755 // * cos(-x) -> cos(x)
758 // * exp(int) -> contant'
759 // * exp(log(x)) -> x
762 // * ffs(cnst) -> cnst'
765 // * fprintf(file,fmt) -> fputs(fmt,file)
766 // (if fmt is constant and constains no % characters)
767 // * fprintf(file,"%s",str) -> fputs(orig,str)
768 // (only if the fprintf result is not used)
769 // * fprintf(file,"%c",chr) -> fputc(chr,file)
771 // fputs: (only if the result is not used)
772 // * fputs("",F) -> noop
773 // * fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
774 // * fputs(s,F) -> fwrite(s, 1, len, F) (if s is constant and strlen(s) > 1)
777 // * isascii(c) -> ((c & ~0x7f) == 0)
780 // * isdigit(c) -> (unsigned)(c) - '0' <= 9
783 // * log(exp(x)) -> x
784 // * log(x**y) -> y*log(x)
785 // * log(exp(y)) -> y*log(e)
786 // * log(exp2(y)) -> y*log(2)
787 // * log(exp10(y)) -> y*log(10)
788 // * log(sqrt(x)) -> 0.5*log(x)
789 // * log(pow(x,y)) -> y*log(x)
791 // lround, lroundf, lroundl:
792 // * lround(cnst) -> cnst'
795 // * memcmp(s1,s2,0) -> 0
796 // * memcmp(x,x,l) -> 0
797 // * memcmp(x,y,l) -> cnst
798 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
799 // * memcpy(x,y,1) -> *x - *y
802 // * memcpy(d,s,0,a) -> d
805 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
806 // (if s is a global constant array)
809 // * memset(s,c,0) -> noop
810 // * memset(s,c,n) -> store s, c
814 // * pow(x,-1.0) -> 1.0/x
815 // * pow(x,0.5) -> sqrt(x)
816 // * pow(cst1,cst2) -> const1**const2
817 // * pow(exp(x),y) -> exp(x*y)
818 // * pow(sqrt(x),y) -> pow(x,y*0.5)
819 // * pow(pow(x,y),z)-> pow(x,y*z)
822 // * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
824 // round, roundf, roundl:
825 // * round(cnst) -> cnst'
828 // * signbit(cnst) -> cnst'
829 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
832 // * sprintf(dest,fmt) -> strcpy(dest,fmt)
833 // (if fmt is constant and constains no % characters)
834 // * sprintf(dest,"%s",orig) -> strcpy(dest,orig)
835 // (only if the sprintf result is not used)
837 // sqrt, sqrtf, sqrtl:
838 // * sqrt(expN(x)) -> expN(x*0.5)
839 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
840 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
843 // * strchr(s,c) -> offset_of_in(c,s)
844 // (if c is a constant integer and s is a constant string)
845 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
846 // (if c is a constant integer and s is a constant string)
847 // * strrchr(s1,0) -> strchr(s1,0)
850 // * strcmp(x,x) -> 0
851 // * strcmp(x,"") -> *x
852 // * strcmp("",x) -> *x
853 // * strcmp(x,y) -> cnst (if both x and y are constant strings)
856 // * strncat(x,y,0) -> x
857 // * strncat(x,y,0) -> x (if strlen(y) = 0)
858 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
861 // * strncmp(x,y,0) -> 0
862 // * strncmp(x,x,l) -> 0
863 // * strncmp(x,"",l) -> *x
864 // * strncmp("",x,l) -> *x
865 // * strncmp(x,y,1) -> *x - *y
868 // * strncpy(d,s,0) -> d
869 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
870 // (if s and l are constants)
873 // * strpbrk(s,a) -> offset_in_for(s,a)
874 // (if s and a are both constant strings)
875 // * strpbrk(s,"") -> 0
876 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
879 // * strspn(s,a) -> const_int (if both args are constant)
880 // * strspn("",a) -> 0
881 // * strspn(s,"") -> 0
882 // * strcspn(s,a) -> const_int (if both args are constant)
883 // * strcspn("",a) -> 0
884 // * strcspn(s,"") -> strlen(a)
887 // * strstr(x,x) -> x
888 // * strstr(s1,s2) -> offset_of_s2_in(s1)
889 // (if s1 and s2 are constant strings)
892 // * tan(atan(x)) -> x
895 // * toascii(c) -> (c & 0x7f)
897 // trunc, truncf, truncl:
898 // * trunc(cnst) -> cnst'