blob: c7734a814f81ff1d7fc77cd92ea5501f890fea31 [file] [log] [blame]
Reid Spencer9bbaa2a2005-04-25 03:59:26 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
Reid Spencer39a762d2005-04-25 02:53:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Reid Spencer9bbaa2a2005-04-25 03:59:26 +00005// This file was developed by Reid Spencer and is distributed under the
6// University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencer39a762d2005-04-25 02:53:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a variety of small optimizations for calls to specific
11// well-known (e.g. runtime library) function calls. For example, a call to the
12// function "exit(3)" that occurs within the main() function can be transformed
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000013// 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.
Reid Spencer39a762d2005-04-25 02:53:12 +000016//
17//===----------------------------------------------------------------------===//
18
Reid Spencer18b99812005-04-26 23:05:17 +000019#define DEBUG_TYPE "simplify-libcalls"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000020#include "llvm/Constants.h"
21#include "llvm/DerivedTypes.h"
22#include "llvm/Instructions.h"
Reid Spencer39a762d2005-04-25 02:53:12 +000023#include "llvm/Module.h"
24#include "llvm/Pass.h"
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000025#include "llvm/ADT/hash_map"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000026#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Debug.h"
Reid Spencerbb92b4f2005-04-26 19:13:17 +000028#include "llvm/Target/TargetData.h"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000029#include "llvm/Transforms/IPO.h"
Reid Spencer3de98ee2005-05-15 17:20:47 +000030#include "llvm/Config/config.h"
Reid Spencerf2534c72005-04-25 21:11:48 +000031#include <iostream>
Reid Spencer39a762d2005-04-25 02:53:12 +000032using namespace llvm;
33
34namespace {
Reid Spencer39a762d2005-04-25 02:53:12 +000035
Reid Spencere249a822005-04-27 07:54:40 +000036/// This statistic keeps track of the total number of library calls that have
37/// been simplified regardless of which call it is.
38Statistic<> SimplifiedLibCalls("simplify-libcalls",
Reid Spencer170ae7f2005-05-07 20:15:59 +000039 "Total number of library calls simplified");
Reid Spencer39a762d2005-04-25 02:53:12 +000040
Reid Spencer7ddcfb32005-04-27 21:29:20 +000041// Forward declarations
Reid Spencere249a822005-04-27 07:54:40 +000042class LibCallOptimization;
43class SimplifyLibCalls;
Reid Spencer7ddcfb32005-04-27 21:29:20 +000044
45/// @brief The list of optimizations deriving from LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +000046hash_map<std::string,LibCallOptimization*> optlist;
Reid Spencer39a762d2005-04-25 02:53:12 +000047
Reid Spencere249a822005-04-27 07:54:40 +000048/// This class is the abstract base class for the set of optimizations that
Reid Spencer7ddcfb32005-04-27 21:29:20 +000049/// corresponds to one library call. The SimplifyLibCalls pass will call the
Reid Spencere249a822005-04-27 07:54:40 +000050/// ValidateCalledFunction method to ask the optimization if a given Function
Reid Spencer7ddcfb32005-04-27 21:29:20 +000051/// is the kind that the optimization can handle. If the subclass returns true,
52/// then SImplifyLibCalls will also call the OptimizeCall method to perform,
53/// or attempt to perform, the optimization(s) for the library call. Otherwise,
54/// OptimizeCall won't be called. Subclasses are responsible for providing the
55/// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
56/// constructor. This is used to efficiently select which call instructions to
57/// optimize. The criteria for a "lib call" is "anything with well known
58/// semantics", typically a library function that is defined by an international
59/// standard. Because the semantics are well known, the optimizations can
60/// generally short-circuit actually calling the function if there's a simpler
61/// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
Reid Spencere249a822005-04-27 07:54:40 +000062/// @brief Base class for library call optimizations
Jeff Cohen4bc952f2005-04-29 03:05:44 +000063class LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +000064{
Jeff Cohen4bc952f2005-04-29 03:05:44 +000065public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +000066 /// The \p fname argument must be the name of the library function being
67 /// optimized by the subclass.
68 /// @brief Constructor that registers the optimization.
Reid Spencer170ae7f2005-05-07 20:15:59 +000069 LibCallOptimization(const char* fname, const char* description )
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000070 : func_name(fname)
Reid Spencere95a6472005-04-27 00:05:45 +000071#ifndef NDEBUG
Reid Spencer170ae7f2005-05-07 20:15:59 +000072 , occurrences("simplify-libcalls",description)
Reid Spencere95a6472005-04-27 00:05:45 +000073#endif
Reid Spencer39a762d2005-04-25 02:53:12 +000074 {
Reid Spencer7ddcfb32005-04-27 21:29:20 +000075 // Register this call optimizer in the optlist (a hash_map)
Reid Spencer95d8efd2005-05-03 02:54:54 +000076 optlist[fname] = this;
Reid Spencer39a762d2005-04-25 02:53:12 +000077 }
78
Reid Spencer7ddcfb32005-04-27 21:29:20 +000079 /// @brief Deregister from the optlist
80 virtual ~LibCallOptimization() { optlist.erase(func_name); }
Reid Spencer8ee5aac2005-04-26 03:26:15 +000081
Reid Spencere249a822005-04-27 07:54:40 +000082 /// The implementation of this function in subclasses should determine if
83 /// \p F is suitable for the optimization. This method is called by
Reid Spencer7ddcfb32005-04-27 21:29:20 +000084 /// 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;
Reid Spencere249a822005-04-27 07:54:40 +000087 /// 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.
Reid Spencer7ddcfb32005-04-27 21:29:20 +000091 /// @brief Determine if the function is suitable for optimization
Reid Spencere249a822005-04-27 07:54:40 +000092 virtual bool ValidateCalledFunction(
93 const Function* F, ///< The function that is the target of call sites
94 SimplifyLibCalls& SLC ///< The pass object invoking us
95 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +000096
Reid Spencere249a822005-04-27 07:54:40 +000097 /// 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.
Reid Spencere249a822005-04-27 07:54:40 +0000103 /// @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
107 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000108
Reid Spencere249a822005-04-27 07:54:40 +0000109 /// @brief Get the name of the library call being optimized
110 const char * getFunctionName() const { return func_name; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000111
Reid Spencere95a6472005-04-27 00:05:45 +0000112#ifndef NDEBUG
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000113 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
Reid Spencer4f01a822005-05-07 04:59:45 +0000114 void succeeded() { DEBUG(++occurrences); }
Reid Spencere95a6472005-04-27 00:05:45 +0000115#endif
Reid Spencere249a822005-04-27 07:54:40 +0000116
117private:
118 const char* func_name; ///< Name of the library call we optimize
119#ifndef NDEBUG
Reid Spencere249a822005-04-27 07:54:40 +0000120 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
121#endif
122};
123
Reid Spencere249a822005-04-27 07:54:40 +0000124/// 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
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000128/// 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.
Reid Spencere249a822005-04-27 07:54:40 +0000131/// @brief A ModulePass for optimizing well-known function calls.
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000132class SimplifyLibCalls : public ModulePass
Reid Spencere249a822005-04-27 07:54:40 +0000133{
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000134public:
Reid Spencere249a822005-04-27 07:54:40 +0000135 /// We need some target data for accurate signature details that are
136 /// target dependent. So we require target data in our AnalysisUsage.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000137 /// @brief Require TargetData from AnalysisUsage.
Reid Spencere249a822005-04-27 07:54:40 +0000138 virtual void getAnalysisUsage(AnalysisUsage& Info) const
139 {
140 // Ask that the TargetData analysis be performed before us so we can use
141 // the target data.
142 Info.addRequired<TargetData>();
143 }
144
145 /// For this pass, process all of the function calls in the module, calling
146 /// ValidateLibraryCall and OptimizeCall as appropriate.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000147 /// @brief Run all the lib call optimizations on a Module.
Reid Spencere249a822005-04-27 07:54:40 +0000148 virtual bool runOnModule(Module &M)
149 {
150 reset(M);
151
152 bool result = false;
153
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;
160 do
161 {
162 found_optimization = false;
163 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
164 {
165 // All the "well-known" functions are external and have external linkage
166 // because they live in a runtime library somewhere and were (probably)
Reid Spencer38cabd72005-05-03 07:23:44 +0000167 // not compiled by LLVM. So, we only act on external functions that
168 // have external linkage and non-empty uses.
Reid Spencere249a822005-04-27 07:54:40 +0000169 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
170 continue;
171
172 // Get the optimization class that pertains to this function
173 LibCallOptimization* CO = optlist[FI->getName().c_str()];
174 if (!CO)
175 continue;
176
177 // Make sure the called function is suitable for the optimization
178 if (!CO->ValidateCalledFunction(FI,*this))
179 continue;
180
181 // Loop over each of the uses of the function
182 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
183 UI != UE ; )
184 {
185 // If the use of the function is a call instruction
186 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
187 {
188 // Do the optimization on the LibCallOptimization.
189 if (CO->OptimizeCall(CI,*this))
190 {
191 ++SimplifiedLibCalls;
192 found_optimization = result = true;
193#ifndef NDEBUG
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000194 CO->succeeded();
Reid Spencere249a822005-04-27 07:54:40 +0000195#endif
196 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000197 }
198 }
199 }
Reid Spencere249a822005-04-27 07:54:40 +0000200 } while (found_optimization);
201 return result;
202 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000203
Reid Spencere249a822005-04-27 07:54:40 +0000204 /// @brief Return the *current* module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000205 Module* getModule() const { return M; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000206
Reid Spencere249a822005-04-27 07:54:40 +0000207 /// @brief Return the *current* target data for the module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000208 TargetData* getTargetData() const { return TD; }
209
210 /// @brief Return the size_t type -- syntactic shortcut
211 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
212
213 /// @brief Return a Function* for the fputc libcall
Reid Spencer4c444fe2005-04-30 03:17:54 +0000214 Function* get_fputc(const Type* FILEptr_type)
Reid Spencer93616972005-04-29 09:39:47 +0000215 {
216 if (!fputc_func)
217 {
218 std::vector<const Type*> args;
219 args.push_back(Type::IntTy);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000220 args.push_back(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +0000221 FunctionType* fputc_type =
222 FunctionType::get(Type::IntTy, args, false);
223 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
224 }
225 return fputc_func;
226 }
227
228 /// @brief Return a Function* for the fwrite libcall
Reid Spencer4c444fe2005-04-30 03:17:54 +0000229 Function* get_fwrite(const Type* FILEptr_type)
Reid Spencer93616972005-04-29 09:39:47 +0000230 {
231 if (!fwrite_func)
232 {
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());
Reid Spencer4c444fe2005-04-30 03:17:54 +0000237 args.push_back(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +0000238 FunctionType* fwrite_type =
239 FunctionType::get(TD->getIntPtrType(), args, false);
240 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
241 }
242 return fwrite_func;
243 }
244
245 /// @brief Return a Function* for the sqrt libcall
246 Function* get_sqrt()
247 {
248 if (!sqrt_func)
249 {
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);
255 }
256 return sqrt_func;
257 }
Reid Spencere249a822005-04-27 07:54:40 +0000258
259 /// @brief Return a Function* for the strlen libcall
Reid Spencer1e520fd2005-05-04 03:20:21 +0000260 Function* get_strcpy()
261 {
262 if (!strcpy_func)
263 {
264 std::vector<const Type*> args;
265 args.push_back(PointerType::get(Type::SByteTy));
266 args.push_back(PointerType::get(Type::SByteTy));
267 FunctionType* strcpy_type =
268 FunctionType::get(PointerType::get(Type::SByteTy), args, false);
269 strcpy_func = M->getOrInsertFunction("strcpy",strcpy_type);
270 }
271 return strcpy_func;
272 }
273
274 /// @brief Return a Function* for the strlen libcall
Reid Spencere249a822005-04-27 07:54:40 +0000275 Function* get_strlen()
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000276 {
Reid Spencere249a822005-04-27 07:54:40 +0000277 if (!strlen_func)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000278 {
279 std::vector<const Type*> args;
280 args.push_back(PointerType::get(Type::SByteTy));
Reid Spencere249a822005-04-27 07:54:40 +0000281 FunctionType* strlen_type =
282 FunctionType::get(TD->getIntPtrType(), args, false);
283 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000284 }
Reid Spencere249a822005-04-27 07:54:40 +0000285 return strlen_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000286 }
287
Reid Spencer38cabd72005-05-03 07:23:44 +0000288 /// @brief Return a Function* for the memchr libcall
289 Function* get_memchr()
290 {
291 if (!memchr_func)
292 {
293 std::vector<const Type*> args;
294 args.push_back(PointerType::get(Type::SByteTy));
295 args.push_back(Type::IntTy);
296 args.push_back(TD->getIntPtrType());
297 FunctionType* memchr_type = FunctionType::get(
298 PointerType::get(Type::SByteTy), args, false);
299 memchr_func = M->getOrInsertFunction("memchr",memchr_type);
300 }
301 return memchr_func;
302 }
303
Reid Spencere249a822005-04-27 07:54:40 +0000304 /// @brief Return a Function* for the memcpy libcall
305 Function* get_memcpy()
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000306 {
Reid Spencere249a822005-04-27 07:54:40 +0000307 if (!memcpy_func)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000308 {
309 // Note: this is for llvm.memcpy intrinsic
310 std::vector<const Type*> args;
311 args.push_back(PointerType::get(Type::SByteTy));
312 args.push_back(PointerType::get(Type::SByteTy));
Reid Spencer1e520fd2005-05-04 03:20:21 +0000313 args.push_back(Type::UIntTy);
314 args.push_back(Type::UIntTy);
Reid Spencere249a822005-04-27 07:54:40 +0000315 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
316 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000317 }
Reid Spencere249a822005-04-27 07:54:40 +0000318 return memcpy_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000319 }
Reid Spencer76dab9a2005-04-26 05:24:00 +0000320
Reid Spencere249a822005-04-27 07:54:40 +0000321private:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000322 /// @brief Reset our cached data for a new Module
Reid Spencere249a822005-04-27 07:54:40 +0000323 void reset(Module& mod)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000324 {
Reid Spencere249a822005-04-27 07:54:40 +0000325 M = &mod;
326 TD = &getAnalysis<TargetData>();
Reid Spencer93616972005-04-29 09:39:47 +0000327 fputc_func = 0;
328 fwrite_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000329 memcpy_func = 0;
Reid Spencer38cabd72005-05-03 07:23:44 +0000330 memchr_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000331 sqrt_func = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +0000332 strcpy_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000333 strlen_func = 0;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000334 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000335
Reid Spencere249a822005-04-27 07:54:40 +0000336private:
Reid Spencer93616972005-04-29 09:39:47 +0000337 Function* fputc_func; ///< Cached fputc function
338 Function* fwrite_func; ///< Cached fwrite function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000339 Function* memcpy_func; ///< Cached llvm.memcpy function
Reid Spencer38cabd72005-05-03 07:23:44 +0000340 Function* memchr_func; ///< Cached memchr function
Reid Spencer93616972005-04-29 09:39:47 +0000341 Function* sqrt_func; ///< Cached sqrt function
Reid Spencer1e520fd2005-05-04 03:20:21 +0000342 Function* strcpy_func; ///< Cached strcpy function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000343 Function* strlen_func; ///< Cached strlen function
344 Module* M; ///< Cached Module
345 TargetData* TD; ///< Cached TargetData
Reid Spencere249a822005-04-27 07:54:40 +0000346};
347
348// Register the pass
349RegisterOpt<SimplifyLibCalls>
350X("simplify-libcalls","Simplify well-known library calls");
351
352} // anonymous namespace
353
354// The only public symbol in this file which just instantiates the pass object
355ModulePass *llvm::createSimplifyLibCallsPass()
356{
357 return new SimplifyLibCalls();
358}
359
360// Classes below here, in the anonymous namespace, are all subclasses of the
361// LibCallOptimization class, each implementing all optimizations possible for a
362// single well-known library call. Each has a static singleton instance that
363// auto registers it into the "optlist" global above.
364namespace {
365
Reid Spencer08b49402005-04-27 17:46:54 +0000366// Forward declare a utility function.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000367bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
Reid Spencere249a822005-04-27 07:54:40 +0000368
369/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000370/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000371/// the same value passed to the exit function. When this is done, it splits the
372/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000373/// @brief Replace calls to exit in main with a simple return
Reid Spencere249a822005-04-27 07:54:40 +0000374struct ExitInMainOptimization : public LibCallOptimization
Reid Spencer39a762d2005-04-25 02:53:12 +0000375{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000376 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000377 "Number of 'exit' calls simplified") {}
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000378 virtual ~ExitInMainOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000379
380 // Make sure the called function looks like exit (int argument, int return
381 // type, external linkage, not varargs).
Reid Spencere249a822005-04-27 07:54:40 +0000382 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000383 {
Reid Spencerb4f7b832005-04-26 07:45:18 +0000384 if (f->arg_size() >= 1)
385 if (f->arg_begin()->getType()->isInteger())
386 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +0000387 return false;
388 }
389
Reid Spencere249a822005-04-27 07:54:40 +0000390 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000391 {
Reid Spencerf2534c72005-04-25 21:11:48 +0000392 // To be careful, we check that the call to exit is coming from "main", that
393 // main has external linkage, and the return type of main and the argument
394 // to exit have the same type.
395 Function *from = ci->getParent()->getParent();
396 if (from->hasExternalLinkage())
397 if (from->getReturnType() == ci->getOperand(1)->getType())
398 if (from->getName() == "main")
399 {
400 // Okay, time to actually do the optimization. First, get the basic
401 // block of the call instruction
402 BasicBlock* bb = ci->getParent();
Reid Spencer39a762d2005-04-25 02:53:12 +0000403
Reid Spencerf2534c72005-04-25 21:11:48 +0000404 // Create a return instruction that we'll replace the call with.
405 // Note that the argument of the return is the argument of the call
406 // instruction.
407 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000408
Reid Spencerf2534c72005-04-25 21:11:48 +0000409 // Split the block at the call instruction which places it in a new
410 // basic block.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000411 bb->splitBasicBlock(ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000412
Reid Spencerf2534c72005-04-25 21:11:48 +0000413 // The block split caused a branch instruction to be inserted into
414 // the end of the original block, right after the return instruction
415 // that we put there. That's not a valid block, so delete the branch
416 // instruction.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000417 bb->getInstList().pop_back();
Reid Spencer39a762d2005-04-25 02:53:12 +0000418
Reid Spencerf2534c72005-04-25 21:11:48 +0000419 // Now we can finally get rid of the call instruction which now lives
420 // in the new basic block.
421 ci->eraseFromParent();
422
423 // Optimization succeeded, return true.
424 return true;
425 }
426 // We didn't pass the criteria for this optimization so return false
427 return false;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000428 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000429} ExitInMainOptimizer;
430
Reid Spencere249a822005-04-27 07:54:40 +0000431/// This LibCallOptimization will simplify a call to the strcat library
432/// function. The simplification is possible only if the string being
433/// concatenated is a constant array or a constant expression that results in
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000434/// a constant string. In this case we can replace it with strlen + llvm.memcpy
435/// of the constant string. Both of these calls are further reduced, if possible
436/// on subsequent passes.
Reid Spencerf2534c72005-04-25 21:11:48 +0000437/// @brief Simplify the strcat library function.
Reid Spencere249a822005-04-27 07:54:40 +0000438struct StrCatOptimization : public LibCallOptimization
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000439{
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000440public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000441 /// @brief Default constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +0000442 StrCatOptimization() : LibCallOptimization("strcat",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000443 "Number of 'strcat' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000444
445public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000446 /// @breif Destructor
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000447 virtual ~StrCatOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000448
449 /// @brief Make sure that the "strcat" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000450 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000451 {
452 if (f->getReturnType() == PointerType::get(Type::SByteTy))
453 if (f->arg_size() == 2)
454 {
455 Function::const_arg_iterator AI = f->arg_begin();
456 if (AI++->getType() == PointerType::get(Type::SByteTy))
457 if (AI->getType() == PointerType::get(Type::SByteTy))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000458 {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000459 // Indicate this is a suitable call type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000460 return true;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000461 }
Reid Spencerf2534c72005-04-25 21:11:48 +0000462 }
463 return false;
464 }
465
Reid Spencere249a822005-04-27 07:54:40 +0000466 /// @brief Optimize the strcat library function
467 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000468 {
Reid Spencer08b49402005-04-27 17:46:54 +0000469 // Extract some information from the instruction
470 Module* M = ci->getParent()->getParent()->getParent();
471 Value* dest = ci->getOperand(1);
472 Value* src = ci->getOperand(2);
473
Reid Spencer76dab9a2005-04-26 05:24:00 +0000474 // Extract the initializer (while making numerous checks) from the
475 // source operand of the call to strcat. If we get null back, one of
476 // a variety of checks in get_GVInitializer failed
Reid Spencerb4f7b832005-04-26 07:45:18 +0000477 uint64_t len = 0;
Reid Spencer08b49402005-04-27 17:46:54 +0000478 if (!getConstantStringLength(src,len))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000479 return false;
480
Reid Spencerb4f7b832005-04-26 07:45:18 +0000481 // Handle the simple, do-nothing case
482 if (len == 0)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000483 {
Reid Spencer08b49402005-04-27 17:46:54 +0000484 ci->replaceAllUsesWith(dest);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000485 ci->eraseFromParent();
486 return true;
487 }
488
Reid Spencerb4f7b832005-04-26 07:45:18 +0000489 // Increment the length because we actually want to memcpy the null
490 // terminator as well.
491 len++;
Reid Spencerf2534c72005-04-25 21:11:48 +0000492
Reid Spencerb4f7b832005-04-26 07:45:18 +0000493 // We need to find the end of the destination string. That's where the
494 // memory is to be moved to. We just generate a call to strlen (further
Reid Spencere249a822005-04-27 07:54:40 +0000495 // optimized in another pass). Note that the SLC.get_strlen() call
Reid Spencerb4f7b832005-04-26 07:45:18 +0000496 // caches the Function* for us.
497 CallInst* strlen_inst =
Reid Spencer08b49402005-04-27 17:46:54 +0000498 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000499
500 // Now that we have the destination's length, we must index into the
501 // destination's pointer to get the actual memcpy destination (end of
502 // the string .. we're concatenating).
503 std::vector<Value*> idx;
504 idx.push_back(strlen_inst);
505 GetElementPtrInst* gep =
Reid Spencer08b49402005-04-27 17:46:54 +0000506 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000507
508 // We have enough information to now generate the memcpy call to
509 // do the concatenation for us.
510 std::vector<Value*> vals;
511 vals.push_back(gep); // destination
512 vals.push_back(ci->getOperand(2)); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000513 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
514 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000515 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000516
517 // Finally, substitute the first operand of the strcat call for the
518 // strcat call itself since strcat returns its first operand; and,
519 // kill the strcat CallInst.
Reid Spencer08b49402005-04-27 17:46:54 +0000520 ci->replaceAllUsesWith(dest);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000521 ci->eraseFromParent();
522 return true;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000523 }
524} StrCatOptimizer;
525
Reid Spencer38cabd72005-05-03 07:23:44 +0000526/// This LibCallOptimization will simplify a call to the strchr library
527/// function. It optimizes out cases where the arguments are both constant
528/// and the result can be determined statically.
529/// @brief Simplify the strcmp library function.
530struct StrChrOptimization : public LibCallOptimization
531{
532public:
533 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000534 "Number of 'strchr' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +0000535 virtual ~StrChrOptimization() {}
536
537 /// @brief Make sure that the "strchr" function has the right prototype
538 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
539 {
540 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
541 f->arg_size() == 2)
542 return true;
543 return false;
544 }
545
546 /// @brief Perform the strcpy optimization
547 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
548 {
549 // If there aren't three operands, bail
550 if (ci->getNumOperands() != 3)
551 return false;
552
553 // Check that the first argument to strchr is a constant array of sbyte.
554 // If it is, get the length and data, otherwise return false.
555 uint64_t len = 0;
556 ConstantArray* CA;
557 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
558 return false;
559
560 // Check that the second argument to strchr is a constant int, return false
561 // if it isn't
562 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
563 if (!CSI)
564 {
565 // Just lower this to memchr since we know the length of the string as
566 // it is constant.
567 Function* f = SLC.get_memchr();
568 std::vector<Value*> args;
569 args.push_back(ci->getOperand(1));
570 args.push_back(ci->getOperand(2));
571 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
572 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
573 ci->eraseFromParent();
574 return true;
575 }
576
577 // Get the character we're looking for
578 int64_t chr = CSI->getValue();
579
580 // Compute the offset
581 uint64_t offset = 0;
582 bool char_found = false;
583 for (uint64_t i = 0; i < len; ++i)
584 {
585 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
586 {
587 // Check for the null terminator
588 if (CI->isNullValue())
589 break; // we found end of string
590 else if (CI->getValue() == chr)
591 {
592 char_found = true;
593 offset = i;
594 break;
595 }
596 }
597 }
598
599 // strchr(s,c) -> offset_of_in(c,s)
600 // (if c is a constant integer and s is a constant string)
601 if (char_found)
602 {
603 std::vector<Value*> indices;
604 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
605 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
606 ci->getOperand(1)->getName()+".strchr",ci);
607 ci->replaceAllUsesWith(GEP);
608 }
609 else
610 ci->replaceAllUsesWith(
611 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
612
613 ci->eraseFromParent();
614 return true;
615 }
616} StrChrOptimizer;
617
Reid Spencer4c444fe2005-04-30 03:17:54 +0000618/// This LibCallOptimization will simplify a call to the strcmp library
619/// function. It optimizes out cases where one or both arguments are constant
620/// and the result can be determined statically.
621/// @brief Simplify the strcmp library function.
622struct StrCmpOptimization : public LibCallOptimization
623{
624public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000625 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000626 "Number of 'strcmp' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +0000627 virtual ~StrCmpOptimization() {}
628
629 /// @brief Make sure that the "strcpy" function has the right prototype
630 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
631 {
632 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
633 return true;
634 return false;
635 }
636
637 /// @brief Perform the strcpy optimization
638 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
639 {
640 // First, check to see if src and destination are the same. If they are,
Reid Spencer16449a92005-04-30 06:45:47 +0000641 // then the optimization is to replace the CallInst with a constant 0
642 // because the call is a no-op.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000643 Value* s1 = ci->getOperand(1);
644 Value* s2 = ci->getOperand(2);
645 if (s1 == s2)
646 {
647 // strcmp(x,x) -> 0
648 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
649 ci->eraseFromParent();
650 return true;
651 }
652
653 bool isstr_1 = false;
654 uint64_t len_1 = 0;
655 ConstantArray* A1;
656 if (getConstantStringLength(s1,len_1,&A1))
657 {
658 isstr_1 = true;
659 if (len_1 == 0)
660 {
661 // strcmp("",x) -> *x
662 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
663 CastInst* cast =
664 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
665 ci->replaceAllUsesWith(cast);
666 ci->eraseFromParent();
667 return true;
668 }
669 }
670
671 bool isstr_2 = false;
672 uint64_t len_2 = 0;
673 ConstantArray* A2;
674 if (getConstantStringLength(s2,len_2,&A2))
675 {
676 isstr_2 = true;
677 if (len_2 == 0)
678 {
679 // strcmp(x,"") -> *x
680 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
681 CastInst* cast =
682 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
683 ci->replaceAllUsesWith(cast);
684 ci->eraseFromParent();
685 return true;
686 }
687 }
688
689 if (isstr_1 && isstr_2)
690 {
691 // strcmp(x,y) -> cnst (if both x and y are constant strings)
692 std::string str1 = A1->getAsString();
693 std::string str2 = A2->getAsString();
694 int result = strcmp(str1.c_str(), str2.c_str());
695 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
696 ci->eraseFromParent();
697 return true;
698 }
699 return false;
700 }
701} StrCmpOptimizer;
702
Reid Spencer49fa07042005-05-03 01:43:45 +0000703/// This LibCallOptimization will simplify a call to the strncmp library
704/// function. It optimizes out cases where one or both arguments are constant
705/// and the result can be determined statically.
706/// @brief Simplify the strncmp library function.
707struct StrNCmpOptimization : public LibCallOptimization
708{
709public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000710 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000711 "Number of 'strncmp' calls simplified") {}
Reid Spencer49fa07042005-05-03 01:43:45 +0000712 virtual ~StrNCmpOptimization() {}
713
714 /// @brief Make sure that the "strcpy" function has the right prototype
715 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
716 {
717 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
718 return true;
719 return false;
720 }
721
722 /// @brief Perform the strncpy optimization
723 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
724 {
725 // First, check to see if src and destination are the same. If they are,
726 // then the optimization is to replace the CallInst with a constant 0
727 // because the call is a no-op.
728 Value* s1 = ci->getOperand(1);
729 Value* s2 = ci->getOperand(2);
730 if (s1 == s2)
731 {
732 // strncmp(x,x,l) -> 0
733 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
734 ci->eraseFromParent();
735 return true;
736 }
737
738 // Check the length argument, if it is Constant zero then the strings are
739 // considered equal.
740 uint64_t len_arg = 0;
741 bool len_arg_is_const = false;
742 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
743 {
744 len_arg_is_const = true;
745 len_arg = len_CI->getRawValue();
746 if (len_arg == 0)
747 {
748 // strncmp(x,y,0) -> 0
749 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
750 ci->eraseFromParent();
751 return true;
752 }
753 }
754
755 bool isstr_1 = false;
756 uint64_t len_1 = 0;
757 ConstantArray* A1;
758 if (getConstantStringLength(s1,len_1,&A1))
759 {
760 isstr_1 = true;
761 if (len_1 == 0)
762 {
763 // strncmp("",x) -> *x
764 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
765 CastInst* cast =
766 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
767 ci->replaceAllUsesWith(cast);
768 ci->eraseFromParent();
769 return true;
770 }
771 }
772
773 bool isstr_2 = false;
774 uint64_t len_2 = 0;
775 ConstantArray* A2;
776 if (getConstantStringLength(s2,len_2,&A2))
777 {
778 isstr_2 = true;
779 if (len_2 == 0)
780 {
781 // strncmp(x,"") -> *x
782 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
783 CastInst* cast =
784 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
785 ci->replaceAllUsesWith(cast);
786 ci->eraseFromParent();
787 return true;
788 }
789 }
790
791 if (isstr_1 && isstr_2 && len_arg_is_const)
792 {
793 // strncmp(x,y,const) -> constant
794 std::string str1 = A1->getAsString();
795 std::string str2 = A2->getAsString();
796 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
797 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
798 ci->eraseFromParent();
799 return true;
800 }
801 return false;
802 }
803} StrNCmpOptimizer;
804
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000805/// This LibCallOptimization will simplify a call to the strcpy library
806/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000807/// (1) If src and dest are the same and not volatile, just return dest
808/// (2) If the src is a constant then we can convert to llvm.memmove
809/// @brief Simplify the strcpy library function.
810struct StrCpyOptimization : public LibCallOptimization
811{
812public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000813 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000814 "Number of 'strcpy' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000815 virtual ~StrCpyOptimization() {}
816
817 /// @brief Make sure that the "strcpy" function has the right prototype
818 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
819 {
820 if (f->getReturnType() == PointerType::get(Type::SByteTy))
821 if (f->arg_size() == 2)
822 {
823 Function::const_arg_iterator AI = f->arg_begin();
824 if (AI++->getType() == PointerType::get(Type::SByteTy))
825 if (AI->getType() == PointerType::get(Type::SByteTy))
826 {
827 // Indicate this is a suitable call type.
828 return true;
829 }
830 }
831 return false;
832 }
833
834 /// @brief Perform the strcpy optimization
835 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
836 {
837 // First, check to see if src and destination are the same. If they are,
838 // then the optimization is to replace the CallInst with the destination
839 // because the call is a no-op. Note that this corresponds to the
840 // degenerate strcpy(X,X) case which should have "undefined" results
841 // according to the C specification. However, it occurs sometimes and
842 // we optimize it as a no-op.
843 Value* dest = ci->getOperand(1);
844 Value* src = ci->getOperand(2);
845 if (dest == src)
846 {
847 ci->replaceAllUsesWith(dest);
848 ci->eraseFromParent();
849 return true;
850 }
851
852 // Get the length of the constant string referenced by the second operand,
853 // the "src" parameter. Fail the optimization if we can't get the length
854 // (note that getConstantStringLength does lots of checks to make sure this
855 // is valid).
856 uint64_t len = 0;
857 if (!getConstantStringLength(ci->getOperand(2),len))
858 return false;
859
860 // If the constant string's length is zero we can optimize this by just
861 // doing a store of 0 at the first byte of the destination
862 if (len == 0)
863 {
864 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
865 ci->replaceAllUsesWith(dest);
866 ci->eraseFromParent();
867 return true;
868 }
869
870 // Increment the length because we actually want to memcpy the null
871 // terminator as well.
872 len++;
873
874 // Extract some information from the instruction
875 Module* M = ci->getParent()->getParent()->getParent();
876
877 // We have enough information to now generate the memcpy call to
878 // do the concatenation for us.
879 std::vector<Value*> vals;
880 vals.push_back(dest); // destination
881 vals.push_back(src); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000882 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
883 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000884 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencere249a822005-04-27 07:54:40 +0000885
886 // Finally, substitute the first operand of the strcat call for the
887 // strcat call itself since strcat returns its first operand; and,
888 // kill the strcat CallInst.
889 ci->replaceAllUsesWith(dest);
890 ci->eraseFromParent();
891 return true;
892 }
893} StrCpyOptimizer;
894
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000895/// This LibCallOptimization will simplify a call to the strlen library
896/// function by replacing it with a constant value if the string provided to
897/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000898/// @brief Simplify the strlen library function.
Reid Spencere249a822005-04-27 07:54:40 +0000899struct StrLenOptimization : public LibCallOptimization
Reid Spencer76dab9a2005-04-26 05:24:00 +0000900{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000901 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000902 "Number of 'strlen' calls simplified") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000903 virtual ~StrLenOptimization() {}
904
905 /// @brief Make sure that the "strlen" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000906 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000907 {
Reid Spencere249a822005-04-27 07:54:40 +0000908 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
Reid Spencer76dab9a2005-04-26 05:24:00 +0000909 if (f->arg_size() == 1)
910 if (Function::const_arg_iterator AI = f->arg_begin())
911 if (AI->getType() == PointerType::get(Type::SByteTy))
912 return true;
913 return false;
914 }
915
916 /// @brief Perform the strlen optimization
Reid Spencere249a822005-04-27 07:54:40 +0000917 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000918 {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000919 // Make sure we're dealing with an sbyte* here.
920 Value* str = ci->getOperand(1);
921 if (str->getType() != PointerType::get(Type::SByteTy))
922 return false;
923
924 // Does the call to strlen have exactly one use?
925 if (ci->hasOneUse())
926 // Is that single use a binary operator?
927 if (BinaryOperator* bop = dyn_cast<BinaryOperator>(ci->use_back()))
928 // Is it compared against a constant integer?
929 if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
930 {
931 // Get the value the strlen result is compared to
932 uint64_t val = CI->getRawValue();
933
934 // If its compared against length 0 with == or !=
935 if (val == 0 &&
936 (bop->getOpcode() == Instruction::SetEQ ||
937 bop->getOpcode() == Instruction::SetNE))
938 {
939 // strlen(x) != 0 -> *x != 0
940 // strlen(x) == 0 -> *x == 0
941 LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
942 BinaryOperator* rbop = BinaryOperator::create(bop->getOpcode(),
943 load, ConstantSInt::get(Type::SByteTy,0),
944 bop->getName()+".strlen", ci);
945 bop->replaceAllUsesWith(rbop);
946 bop->eraseFromParent();
947 ci->eraseFromParent();
948 return true;
949 }
950 }
951
952 // Get the length of the constant string operand
Reid Spencerb4f7b832005-04-26 07:45:18 +0000953 uint64_t len = 0;
954 if (!getConstantStringLength(ci->getOperand(1),len))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000955 return false;
956
Reid Spencer170ae7f2005-05-07 20:15:59 +0000957 // strlen("xyz") -> 3 (for example)
Reid Spencere249a822005-04-27 07:54:40 +0000958 ci->replaceAllUsesWith(
959 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
Reid Spencerb4f7b832005-04-26 07:45:18 +0000960 ci->eraseFromParent();
961 return true;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000962 }
963} StrLenOptimizer;
964
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000965/// This LibCallOptimization will simplify a call to the memcpy library
966/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
967/// bytes depending on the length of the string and the alignment. Additional
968/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +0000969/// @brief Simplify the memcpy library function.
Reid Spencer38cabd72005-05-03 07:23:44 +0000970struct LLVMMemCpyOptimization : public LibCallOptimization
Reid Spencerf2534c72005-04-25 21:11:48 +0000971{
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000972 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +0000973 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
Reid Spencer95d8efd2005-05-03 02:54:54 +0000974 "Number of 'llvm.memcpy' calls simplified") {}
975
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000976protected:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000977 /// @brief Subclass Constructor
Reid Spencer170ae7f2005-05-07 20:15:59 +0000978 LLVMMemCpyOptimization(const char* fname, const char* desc)
979 : LibCallOptimization(fname, desc) {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000980public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000981 /// @brief Destructor
Reid Spencer38cabd72005-05-03 07:23:44 +0000982 virtual ~LLVMMemCpyOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000983
984 /// @brief Make sure that the "memcpy" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000985 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +0000986 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000987 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +0000988 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +0000989 }
990
Reid Spencerb4f7b832005-04-26 07:45:18 +0000991 /// Because of alignment and instruction information that we don't have, we
992 /// leave the bulk of this to the code generators. The optimization here just
993 /// deals with a few degenerate cases where the length of the string and the
994 /// alignment match the sizes of our intrinsic types so we can do a load and
995 /// store instead of the memcpy call.
996 /// @brief Perform the memcpy optimization.
Reid Spencere249a822005-04-27 07:54:40 +0000997 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +0000998 {
Reid Spencer4855ebf2005-04-26 19:55:57 +0000999 // Make sure we have constant int values to work with
1000 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1001 if (!LEN)
1002 return false;
1003 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1004 if (!ALIGN)
1005 return false;
1006
1007 // If the length is larger than the alignment, we can't optimize
1008 uint64_t len = LEN->getRawValue();
1009 uint64_t alignment = ALIGN->getRawValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001010 if (alignment == 0)
1011 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001012 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +00001013 return false;
1014
Reid Spencer08b49402005-04-27 17:46:54 +00001015 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +00001016 Value* dest = ci->getOperand(1);
1017 Value* src = ci->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +00001018 Type* castType = 0;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001019 switch (len)
1020 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001021 case 0:
Reid Spencer93616972005-04-29 09:39:47 +00001022 // memcpy(d,s,0,a) -> noop
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001023 ci->eraseFromParent();
1024 return true;
Reid Spencer08b49402005-04-27 17:46:54 +00001025 case 1: castType = Type::SByteTy; break;
1026 case 2: castType = Type::ShortTy; break;
1027 case 4: castType = Type::IntTy; break;
1028 case 8: castType = Type::LongTy; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001029 default:
1030 return false;
1031 }
Reid Spencer08b49402005-04-27 17:46:54 +00001032
1033 // Cast source and dest to the right sized primitive and then load/store
1034 CastInst* SrcCast =
1035 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
1036 CastInst* DestCast =
1037 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1038 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001039 StoreInst* SI = new StoreInst(LI, DestCast, ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001040 ci->eraseFromParent();
1041 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +00001042 }
Reid Spencer38cabd72005-05-03 07:23:44 +00001043} LLVMMemCpyOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001044
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001045/// This LibCallOptimization will simplify a call to the memmove library
1046/// function. It is identical to MemCopyOptimization except for the name of
1047/// the intrinsic.
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001048/// @brief Simplify the memmove library function.
Reid Spencer38cabd72005-05-03 07:23:44 +00001049struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001050{
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001051 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +00001052 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
Reid Spencer95d8efd2005-05-03 02:54:54 +00001053 "Number of 'llvm.memmove' calls simplified") {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001054
Reid Spencer38cabd72005-05-03 07:23:44 +00001055} LLVMMemMoveOptimizer;
1056
1057/// This LibCallOptimization will simplify a call to the memset library
1058/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1059/// bytes depending on the length argument.
1060struct LLVMMemSetOptimization : public LibCallOptimization
1061{
1062 /// @brief Default Constructor
1063 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
Reid Spencer38cabd72005-05-03 07:23:44 +00001064 "Number of 'llvm.memset' calls simplified") {}
1065
1066public:
1067 /// @brief Destructor
1068 virtual ~LLVMMemSetOptimization() {}
1069
1070 /// @brief Make sure that the "memset" function has the right prototype
1071 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1072 {
1073 // Just make sure this has 3 arguments per LLVM spec.
1074 return (f->arg_size() == 4);
1075 }
1076
1077 /// Because of alignment and instruction information that we don't have, we
1078 /// leave the bulk of this to the code generators. The optimization here just
1079 /// deals with a few degenerate cases where the length parameter is constant
1080 /// and the alignment matches the sizes of our intrinsic types so we can do
1081 /// store instead of the memcpy call. Other calls are transformed into the
1082 /// llvm.memset intrinsic.
1083 /// @brief Perform the memset optimization.
1084 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1085 {
1086 // Make sure we have constant int values to work with
1087 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1088 if (!LEN)
1089 return false;
1090 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1091 if (!ALIGN)
1092 return false;
1093
1094 // Extract the length and alignment
1095 uint64_t len = LEN->getRawValue();
1096 uint64_t alignment = ALIGN->getRawValue();
1097
1098 // Alignment 0 is identity for alignment 1
1099 if (alignment == 0)
1100 alignment = 1;
1101
1102 // If the length is zero, this is a no-op
1103 if (len == 0)
1104 {
1105 // memset(d,c,0,a) -> noop
1106 ci->eraseFromParent();
1107 return true;
1108 }
1109
1110 // If the length is larger than the alignment, we can't optimize
1111 if (len > alignment)
1112 return false;
1113
1114 // Make sure we have a constant ubyte to work with so we can extract
1115 // the value to be filled.
1116 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1117 if (!FILL)
1118 return false;
1119 if (FILL->getType() != Type::UByteTy)
1120 return false;
1121
1122 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1123
1124 // Extract the fill character
1125 uint64_t fill_char = FILL->getValue();
1126 uint64_t fill_value = fill_char;
1127
1128 // Get the type we will cast to, based on size of memory area to fill, and
1129 // and the value we will store there.
1130 Value* dest = ci->getOperand(1);
1131 Type* castType = 0;
1132 switch (len)
1133 {
1134 case 1:
1135 castType = Type::UByteTy;
1136 break;
1137 case 2:
1138 castType = Type::UShortTy;
1139 fill_value |= fill_char << 8;
1140 break;
1141 case 4:
1142 castType = Type::UIntTy;
1143 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1144 break;
1145 case 8:
1146 castType = Type::ULongTy;
1147 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1148 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1149 fill_value |= fill_char << 56;
1150 break;
1151 default:
1152 return false;
1153 }
1154
1155 // Cast dest to the right sized primitive and then load/store
1156 CastInst* DestCast =
1157 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1158 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1159 ci->eraseFromParent();
1160 return true;
1161 }
1162} LLVMMemSetOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001163
Reid Spencer93616972005-04-29 09:39:47 +00001164/// This LibCallOptimization will simplify calls to the "pow" library
1165/// function. It looks for cases where the result of pow is well known and
1166/// substitutes the appropriate value.
1167/// @brief Simplify the pow library function.
1168struct PowOptimization : public LibCallOptimization
1169{
1170public:
1171 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001172 PowOptimization() : LibCallOptimization("pow",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001173 "Number of 'pow' calls simplified") {}
Reid Spencer95d8efd2005-05-03 02:54:54 +00001174
Reid Spencer93616972005-04-29 09:39:47 +00001175 /// @brief Destructor
1176 virtual ~PowOptimization() {}
1177
1178 /// @brief Make sure that the "pow" function has the right prototype
1179 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1180 {
1181 // Just make sure this has 2 arguments
1182 return (f->arg_size() == 2);
1183 }
1184
1185 /// @brief Perform the pow optimization.
1186 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1187 {
1188 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1189 Value* base = ci->getOperand(1);
1190 Value* expn = ci->getOperand(2);
1191 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1192 double Op1V = Op1->getValue();
1193 if (Op1V == 1.0)
1194 {
1195 // pow(1.0,x) -> 1.0
1196 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1197 ci->eraseFromParent();
1198 return true;
1199 }
1200 }
1201 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
1202 {
1203 double Op2V = Op2->getValue();
1204 if (Op2V == 0.0)
1205 {
1206 // pow(x,0.0) -> 1.0
1207 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1208 ci->eraseFromParent();
1209 return true;
1210 }
1211 else if (Op2V == 0.5)
1212 {
1213 // pow(x,0.5) -> sqrt(x)
1214 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1215 ci->getName()+".pow",ci);
1216 ci->replaceAllUsesWith(sqrt_inst);
1217 ci->eraseFromParent();
1218 return true;
1219 }
1220 else if (Op2V == 1.0)
1221 {
1222 // pow(x,1.0) -> x
1223 ci->replaceAllUsesWith(base);
1224 ci->eraseFromParent();
1225 return true;
1226 }
1227 else if (Op2V == -1.0)
1228 {
1229 // pow(x,-1.0) -> 1.0/x
1230 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
1231 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1232 ci->replaceAllUsesWith(div_inst);
1233 ci->eraseFromParent();
1234 return true;
1235 }
1236 }
1237 return false; // opt failed
1238 }
1239} PowOptimizer;
1240
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001241/// This LibCallOptimization will simplify calls to the "fprintf" library
1242/// function. It looks for cases where the result of fprintf is not used and the
1243/// operation can be reduced to something simpler.
1244/// @brief Simplify the pow library function.
1245struct FPrintFOptimization : public LibCallOptimization
1246{
1247public:
1248 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001249 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001250 "Number of 'fprintf' calls simplified") {}
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001251
1252 /// @brief Destructor
1253 virtual ~FPrintFOptimization() {}
1254
1255 /// @brief Make sure that the "fprintf" function has the right prototype
1256 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1257 {
1258 // Just make sure this has at least 2 arguments
1259 return (f->arg_size() >= 2);
1260 }
1261
1262 /// @brief Perform the fprintf optimization.
1263 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1264 {
1265 // If the call has more than 3 operands, we can't optimize it
1266 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1267 return false;
1268
1269 // If the result of the fprintf call is used, none of these optimizations
1270 // can be made.
1271 if (!ci->hasNUses(0))
1272 return false;
1273
1274 // All the optimizations depend on the length of the second argument and the
1275 // fact that it is a constant string array. Check that now
1276 uint64_t len = 0;
1277 ConstantArray* CA = 0;
1278 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1279 return false;
1280
1281 if (ci->getNumOperands() == 3)
1282 {
1283 // Make sure there's no % in the constant array
1284 for (unsigned i = 0; i < len; ++i)
1285 {
1286 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1287 {
1288 // Check for the null terminator
1289 if (CI->getRawValue() == '%')
1290 return false; // we found end of string
1291 }
1292 else
1293 return false;
1294 }
1295
1296 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),1file)
1297 const Type* FILEptr_type = ci->getOperand(1)->getType();
1298 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1299 if (!fwrite_func)
1300 return false;
1301 std::vector<Value*> args;
1302 args.push_back(ci->getOperand(2));
1303 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1304 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1305 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001306 new CallInst(fwrite_func,args,ci->getName(),ci);
1307 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001308 ci->eraseFromParent();
1309 return true;
1310 }
1311
1312 // The remaining optimizations require the format string to be length 2
1313 // "%s" or "%c".
1314 if (len != 2)
1315 return false;
1316
1317 // The first character has to be a %
1318 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1319 if (CI->getRawValue() != '%')
1320 return false;
1321
1322 // Get the second character and switch on its value
1323 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1324 switch (CI->getRawValue())
1325 {
1326 case 's':
1327 {
1328 uint64_t len = 0;
1329 ConstantArray* CA = 0;
1330 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1331 return false;
1332
Reid Spencer1e520fd2005-05-04 03:20:21 +00001333 // fprintf(file,"%s",str) -> fwrite(fmt,strlen(fmt),1,file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001334 const Type* FILEptr_type = ci->getOperand(1)->getType();
1335 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1336 if (!fwrite_func)
1337 return false;
1338 std::vector<Value*> args;
1339 args.push_back(ci->getOperand(3));
1340 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1341 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1342 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001343 new CallInst(fwrite_func,args,ci->getName(),ci);
1344 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001345 break;
1346 }
1347 case 'c':
1348 {
1349 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1350 if (!CI)
1351 return false;
1352
1353 const Type* FILEptr_type = ci->getOperand(1)->getType();
1354 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1355 if (!fputc_func)
1356 return false;
1357 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1358 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
Reid Spencer1e520fd2005-05-04 03:20:21 +00001359 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001360 break;
1361 }
1362 default:
1363 return false;
1364 }
1365 ci->eraseFromParent();
1366 return true;
1367 }
1368} FPrintFOptimizer;
1369
1370
Reid Spencer1e520fd2005-05-04 03:20:21 +00001371/// This LibCallOptimization will simplify calls to the "sprintf" library
1372/// function. It looks for cases where the result of sprintf is not used and the
1373/// operation can be reduced to something simpler.
1374/// @brief Simplify the pow library function.
1375struct SPrintFOptimization : public LibCallOptimization
1376{
1377public:
1378 /// @brief Default Constructor
1379 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001380 "Number of 'sprintf' calls simplified") {}
Reid Spencer1e520fd2005-05-04 03:20:21 +00001381
1382 /// @brief Destructor
1383 virtual ~SPrintFOptimization() {}
1384
1385 /// @brief Make sure that the "fprintf" function has the right prototype
1386 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1387 {
1388 // Just make sure this has at least 2 arguments
1389 return (f->getReturnType() == Type::IntTy && f->arg_size() >= 2);
1390 }
1391
1392 /// @brief Perform the sprintf optimization.
1393 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1394 {
1395 // If the call has more than 3 operands, we can't optimize it
1396 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1397 return false;
1398
1399 // All the optimizations depend on the length of the second argument and the
1400 // fact that it is a constant string array. Check that now
1401 uint64_t len = 0;
1402 ConstantArray* CA = 0;
1403 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1404 return false;
1405
1406 if (ci->getNumOperands() == 3)
1407 {
1408 if (len == 0)
1409 {
1410 // If the length is 0, we just need to store a null byte
1411 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
1412 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1413 ci->eraseFromParent();
1414 return true;
1415 }
1416
1417 // Make sure there's no % in the constant array
1418 for (unsigned i = 0; i < len; ++i)
1419 {
1420 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1421 {
1422 // Check for the null terminator
1423 if (CI->getRawValue() == '%')
1424 return false; // we found a %, can't optimize
1425 }
1426 else
1427 return false; // initializer is not constant int, can't optimize
1428 }
1429
1430 // Increment length because we want to copy the null byte too
1431 len++;
1432
1433 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
1434 Function* memcpy_func = SLC.get_memcpy();
1435 if (!memcpy_func)
1436 return false;
1437 std::vector<Value*> args;
1438 args.push_back(ci->getOperand(1));
1439 args.push_back(ci->getOperand(2));
1440 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1441 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1442 new CallInst(memcpy_func,args,"",ci);
1443 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1444 ci->eraseFromParent();
1445 return true;
1446 }
1447
1448 // The remaining optimizations require the format string to be length 2
1449 // "%s" or "%c".
1450 if (len != 2)
1451 return false;
1452
1453 // The first character has to be a %
1454 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1455 if (CI->getRawValue() != '%')
1456 return false;
1457
1458 // Get the second character and switch on its value
1459 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1460 switch (CI->getRawValue())
1461 {
1462 case 's':
1463 {
1464 uint64_t len = 0;
1465 if (ci->hasNUses(0))
1466 {
1467 // sprintf(dest,"%s",str) -> strcpy(dest,str)
1468 Function* strcpy_func = SLC.get_strcpy();
1469 if (!strcpy_func)
1470 return false;
1471 std::vector<Value*> args;
1472 args.push_back(ci->getOperand(1));
1473 args.push_back(ci->getOperand(3));
1474 new CallInst(strcpy_func,args,"",ci);
1475 }
1476 else if (getConstantStringLength(ci->getOperand(3),len))
1477 {
1478 // sprintf(dest,"%s",cstr) -> llvm.memcpy(dest,str,strlen(str),1)
1479 len++; // get the null-terminator
1480 Function* memcpy_func = SLC.get_memcpy();
1481 if (!memcpy_func)
1482 return false;
1483 std::vector<Value*> args;
1484 args.push_back(ci->getOperand(1));
1485 args.push_back(ci->getOperand(3));
1486 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1487 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1488 new CallInst(memcpy_func,args,"",ci);
1489 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1490 }
1491 break;
1492 }
1493 case 'c':
1494 {
1495 // sprintf(dest,"%c",chr) -> store chr, dest
1496 CastInst* cast =
1497 new CastInst(ci->getOperand(3),Type::SByteTy,"char",ci);
1498 new StoreInst(cast, ci->getOperand(1), ci);
1499 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1500 ConstantUInt::get(Type::UIntTy,1),ci->getOperand(1)->getName()+".end",
1501 ci);
1502 new StoreInst(ConstantInt::get(Type::SByteTy,0),gep,ci);
1503 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1504 break;
1505 }
1506 default:
1507 return false;
1508 }
1509 ci->eraseFromParent();
1510 return true;
1511 }
1512} SPrintFOptimizer;
1513
Reid Spencer93616972005-04-29 09:39:47 +00001514/// This LibCallOptimization will simplify calls to the "fputs" library
1515/// function. It looks for cases where the result of fputs is not used and the
1516/// operation can be reduced to something simpler.
1517/// @brief Simplify the pow library function.
1518struct PutsOptimization : public LibCallOptimization
1519{
1520public:
1521 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001522 PutsOptimization() : LibCallOptimization("fputs",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001523 "Number of 'fputs' calls simplified") {}
Reid Spencer93616972005-04-29 09:39:47 +00001524
1525 /// @brief Destructor
1526 virtual ~PutsOptimization() {}
1527
1528 /// @brief Make sure that the "fputs" function has the right prototype
1529 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1530 {
1531 // Just make sure this has 2 arguments
1532 return (f->arg_size() == 2);
1533 }
1534
1535 /// @brief Perform the fputs optimization.
1536 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1537 {
1538 // If the result is used, none of these optimizations work
1539 if (!ci->hasNUses(0))
1540 return false;
1541
1542 // All the optimizations depend on the length of the first argument and the
1543 // fact that it is a constant string array. Check that now
1544 uint64_t len = 0;
1545 if (!getConstantStringLength(ci->getOperand(1), len))
1546 return false;
1547
1548 switch (len)
1549 {
1550 case 0:
1551 // fputs("",F) -> noop
1552 break;
1553 case 1:
1554 {
1555 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001556 const Type* FILEptr_type = ci->getOperand(2)->getType();
1557 Function* fputc_func = SLC.get_fputc(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001558 if (!fputc_func)
1559 return false;
1560 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1561 ci->getOperand(1)->getName()+".byte",ci);
1562 CastInst* casti = new CastInst(loadi,Type::IntTy,
1563 loadi->getName()+".int",ci);
1564 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1565 break;
1566 }
1567 default:
1568 {
1569 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001570 const Type* FILEptr_type = ci->getOperand(2)->getType();
1571 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001572 if (!fwrite_func)
1573 return false;
1574 std::vector<Value*> parms;
1575 parms.push_back(ci->getOperand(1));
1576 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1577 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1578 parms.push_back(ci->getOperand(2));
1579 new CallInst(fwrite_func,parms,"",ci);
1580 break;
1581 }
1582 }
1583 ci->eraseFromParent();
1584 return true; // success
1585 }
1586} PutsOptimizer;
1587
Reid Spencer282d0572005-05-04 18:58:28 +00001588/// This LibCallOptimization will simplify calls to the "isdigit" library
1589/// function. It simply does range checks the parameter explicitly.
1590/// @brief Simplify the isdigit library function.
1591struct IsDigitOptimization : public LibCallOptimization
1592{
1593public:
1594 /// @brief Default Constructor
1595 IsDigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001596 "Number of 'isdigit' calls simplified") {}
Reid Spencer282d0572005-05-04 18:58:28 +00001597
1598 /// @brief Destructor
1599 virtual ~IsDigitOptimization() {}
1600
1601 /// @brief Make sure that the "fputs" function has the right prototype
1602 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1603 {
1604 // Just make sure this has 1 argument
1605 return (f->arg_size() == 1);
1606 }
1607
1608 /// @brief Perform the toascii optimization.
1609 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1610 {
1611 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1612 {
1613 // isdigit(c) -> 0 or 1, if 'c' is constant
1614 uint64_t val = CI->getRawValue();
1615 if (val >= '0' && val <='9')
1616 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1617 else
1618 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1619 ci->eraseFromParent();
1620 return true;
1621 }
1622
1623 // isdigit(c) -> (unsigned)c - '0' <= 9
1624 CastInst* cast =
1625 new CastInst(ci->getOperand(1),Type::UIntTy,
1626 ci->getOperand(1)->getName()+".uint",ci);
1627 BinaryOperator* sub_inst = BinaryOperator::create(Instruction::Sub,cast,
1628 ConstantUInt::get(Type::UIntTy,0x30),
1629 ci->getOperand(1)->getName()+".sub",ci);
1630 SetCondInst* setcond_inst = new SetCondInst(Instruction::SetLE,sub_inst,
1631 ConstantUInt::get(Type::UIntTy,9),
1632 ci->getOperand(1)->getName()+".cmp",ci);
1633 CastInst* c2 =
1634 new CastInst(setcond_inst,Type::IntTy,
1635 ci->getOperand(1)->getName()+".isdigit",ci);
1636 ci->replaceAllUsesWith(c2);
1637 ci->eraseFromParent();
1638 return true;
1639 }
1640} IsDigitOptimizer;
1641
Reid Spencer4c444fe2005-04-30 03:17:54 +00001642/// This LibCallOptimization will simplify calls to the "toascii" library
1643/// function. It simply does the corresponding and operation to restrict the
1644/// range of values to the ASCII character set (0-127).
1645/// @brief Simplify the toascii library function.
1646struct ToAsciiOptimization : public LibCallOptimization
1647{
1648public:
1649 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001650 ToAsciiOptimization() : LibCallOptimization("toascii",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001651 "Number of 'toascii' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +00001652
1653 /// @brief Destructor
1654 virtual ~ToAsciiOptimization() {}
1655
1656 /// @brief Make sure that the "fputs" function has the right prototype
1657 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1658 {
1659 // Just make sure this has 2 arguments
1660 return (f->arg_size() == 1);
1661 }
1662
1663 /// @brief Perform the toascii optimization.
1664 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1665 {
1666 // toascii(c) -> (c & 0x7f)
1667 Value* chr = ci->getOperand(1);
1668 BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1669 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1670 ci->replaceAllUsesWith(and_inst);
1671 ci->eraseFromParent();
1672 return true;
1673 }
1674} ToAsciiOptimizer;
1675
Reid Spencerb195fcd2005-05-14 16:42:52 +00001676#if defined(HAVE_FFSLL)
1677/// This LibCallOptimization will simplify calls to the "ffs" library
1678/// calls which find the first set bit in an int, long, or long long. The
1679/// optimization is to compute the result at compile time if the argument is
1680/// a constant.
1681/// @brief Simplify the ffs library function.
1682struct FFSOptimization : public LibCallOptimization
1683{
1684protected:
1685 /// @brief Subclass Constructor
1686 FFSOptimization(const char* funcName, const char* description)
1687 : LibCallOptimization(funcName, description)
1688 {}
1689
1690public:
1691 /// @brief Default Constructor
1692 FFSOptimization() : LibCallOptimization("ffs",
1693 "Number of 'ffs' calls simplified") {}
1694
1695 /// @brief Destructor
1696 virtual ~FFSOptimization() {}
1697
1698 /// @brief Make sure that the "fputs" function has the right prototype
1699 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1700 {
1701 // Just make sure this has 2 arguments
1702 return (f->arg_size() == 1 && f->getReturnType() == Type::IntTy);
1703 }
1704
1705 /// @brief Perform the ffs optimization.
1706 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1707 {
1708 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1709 {
1710 // ffs(cnst) -> bit#
1711 // ffsl(cnst) -> bit#
1712 uint64_t val = CI->getRawValue();
1713 int result = ffsll(static_cast<long long>(val));
1714 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy, result));
1715 ci->eraseFromParent();
1716 return true;
1717 }
1718 return false;
1719 }
1720} FFSOptimizer;
1721
1722/// This LibCallOptimization will simplify calls to the "ffsl" library
1723/// calls. It simply uses FFSOptimization for which the transformation is
1724/// identical.
1725/// @brief Simplify the ffsl library function.
1726struct FFSLOptimization : public FFSOptimization
1727{
1728public:
1729 /// @brief Default Constructor
1730 FFSLOptimization() : FFSOptimization("ffsl",
1731 "Number of 'ffsl' calls simplified") {}
1732
1733} FFSLOptimizer;
1734
1735/// This LibCallOptimization will simplify calls to the "ffsll" library
1736/// calls. It simply uses FFSOptimization for which the transformation is
1737/// identical.
1738/// @brief Simplify the ffsl library function.
1739struct FFSLLOptimization : public FFSOptimization
1740{
1741public:
1742 /// @brief Default Constructor
1743 FFSLLOptimization() : FFSOptimization("ffsll",
1744 "Number of 'ffsll' calls simplified") {}
1745
1746} FFSLLOptimizer;
1747
1748#endif
1749
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001750/// A function to compute the length of a null-terminated constant array of
1751/// integers. This function can't rely on the size of the constant array
1752/// because there could be a null terminator in the middle of the array.
1753/// We also have to bail out if we find a non-integer constant initializer
1754/// of one of the elements or if there is no null-terminator. The logic
1755/// below checks each of these conditions and will return true only if all
1756/// conditions are met. In that case, the \p len parameter is set to the length
1757/// of the null-terminated string. If false is returned, the conditions were
1758/// not met and len is set to 0.
1759/// @brief Get the length of a constant string (null-terminated array).
Reid Spencer4c444fe2005-04-30 03:17:54 +00001760bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
Reid Spencere249a822005-04-27 07:54:40 +00001761{
1762 assert(V != 0 && "Invalid args to getConstantStringLength");
1763 len = 0; // make sure we initialize this
1764 User* GEP = 0;
1765 // If the value is not a GEP instruction nor a constant expression with a
1766 // GEP instruction, then return false because ConstantArray can't occur
1767 // any other way
1768 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1769 GEP = GEPI;
1770 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1771 if (CE->getOpcode() == Instruction::GetElementPtr)
1772 GEP = CE;
1773 else
1774 return false;
1775 else
1776 return false;
1777
1778 // Make sure the GEP has exactly three arguments.
1779 if (GEP->getNumOperands() != 3)
1780 return false;
1781
1782 // Check to make sure that the first operand of the GEP is an integer and
1783 // has value 0 so that we are sure we're indexing into the initializer.
1784 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1785 {
1786 if (!op1->isNullValue())
1787 return false;
1788 }
1789 else
1790 return false;
1791
1792 // Ensure that the second operand is a ConstantInt. If it isn't then this
1793 // GEP is wonky and we're not really sure what were referencing into and
1794 // better of not optimizing it. While we're at it, get the second index
1795 // value. We'll need this later for indexing the ConstantArray.
1796 uint64_t start_idx = 0;
1797 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1798 start_idx = CI->getRawValue();
1799 else
1800 return false;
1801
1802 // The GEP instruction, constant or instruction, must reference a global
1803 // variable that is a constant and is initialized. The referenced constant
1804 // initializer is the array that we'll use for optimization.
1805 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1806 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1807 return false;
1808
1809 // Get the initializer.
1810 Constant* INTLZR = GV->getInitializer();
1811
1812 // Handle the ConstantAggregateZero case
1813 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1814 {
1815 // This is a degenerate case. The initializer is constant zero so the
1816 // length of the string must be zero.
1817 len = 0;
1818 return true;
1819 }
1820
1821 // Must be a Constant Array
1822 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1823 if (!A)
1824 return false;
1825
1826 // Get the number of elements in the array
1827 uint64_t max_elems = A->getType()->getNumElements();
1828
1829 // Traverse the constant array from start_idx (derived above) which is
1830 // the place the GEP refers to in the array.
1831 for ( len = start_idx; len < max_elems; len++)
1832 {
1833 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1834 {
1835 // Check for the null terminator
1836 if (CI->isNullValue())
1837 break; // we found end of string
1838 }
1839 else
1840 return false; // This array isn't suitable, non-int initializer
1841 }
1842 if (len >= max_elems)
1843 return false; // This array isn't null terminated
1844
1845 // Subtract out the initial value from the length
1846 len -= start_idx;
Reid Spencer4c444fe2005-04-30 03:17:54 +00001847 if (CA)
1848 *CA = A;
Reid Spencere249a822005-04-27 07:54:40 +00001849 return true; // success!
1850}
1851
Reid Spencer649ac282005-04-28 04:40:06 +00001852// TODO:
1853// Additional cases that we need to add to this file:
1854//
Reid Spencer649ac282005-04-28 04:40:06 +00001855// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +00001856// * cbrt(expN(X)) -> expN(x/3)
1857// * cbrt(sqrt(x)) -> pow(x,1/6)
1858// * cbrt(sqrt(x)) -> pow(x,1/9)
1859//
Reid Spencer649ac282005-04-28 04:40:06 +00001860// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +00001861// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +00001862//
1863// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +00001864// * exp(log(x)) -> x
1865//
Reid Spencer649ac282005-04-28 04:40:06 +00001866// isascii:
1867// * isascii(c) -> ((c & ~0x7f) == 0)
1868//
1869// isdigit:
1870// * isdigit(c) -> (unsigned)(c) - '0' <= 9
1871//
1872// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +00001873// * log(exp(x)) -> x
1874// * log(x**y) -> y*log(x)
1875// * log(exp(y)) -> y*log(e)
1876// * log(exp2(y)) -> y*log(2)
1877// * log(exp10(y)) -> y*log(10)
1878// * log(sqrt(x)) -> 0.5*log(x)
1879// * log(pow(x,y)) -> y*log(x)
1880//
1881// lround, lroundf, lroundl:
1882// * lround(cnst) -> cnst'
1883//
1884// memcmp:
1885// * memcmp(s1,s2,0) -> 0
1886// * memcmp(x,x,l) -> 0
1887// * memcmp(x,y,l) -> cnst
1888// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer38cabd72005-05-03 07:23:44 +00001889// * memcmp(x,y,1) -> *x - *y
Reid Spencer649ac282005-04-28 04:40:06 +00001890//
Reid Spencer649ac282005-04-28 04:40:06 +00001891// memmove:
1892// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1893// (if s is a global constant array)
1894//
Reid Spencer649ac282005-04-28 04:40:06 +00001895// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00001896// * pow(exp(x),y) -> exp(x*y)
1897// * pow(sqrt(x),y) -> pow(x,y*0.5)
1898// * pow(pow(x,y),z)-> pow(x,y*z)
1899//
1900// puts:
1901// * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1902//
1903// round, roundf, roundl:
1904// * round(cnst) -> cnst'
1905//
1906// signbit:
1907// * signbit(cnst) -> cnst'
1908// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1909//
Reid Spencer649ac282005-04-28 04:40:06 +00001910// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00001911// * sqrt(expN(x)) -> expN(x*0.5)
1912// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1913// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1914//
Reid Spencer170ae7f2005-05-07 20:15:59 +00001915// stpcpy:
1916// * stpcpy(str, "literal") ->
1917// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer38cabd72005-05-03 07:23:44 +00001918// strrchr:
Reid Spencer649ac282005-04-28 04:40:06 +00001919// * strrchr(s,c) -> reverse_offset_of_in(c,s)
1920// (if c is a constant integer and s is a constant string)
1921// * strrchr(s1,0) -> strchr(s1,0)
1922//
Reid Spencer649ac282005-04-28 04:40:06 +00001923// strncat:
1924// * strncat(x,y,0) -> x
1925// * strncat(x,y,0) -> x (if strlen(y) = 0)
1926// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1927//
Reid Spencer649ac282005-04-28 04:40:06 +00001928// strncpy:
1929// * strncpy(d,s,0) -> d
1930// * strncpy(d,s,l) -> memcpy(d,s,l,1)
1931// (if s and l are constants)
1932//
1933// strpbrk:
1934// * strpbrk(s,a) -> offset_in_for(s,a)
1935// (if s and a are both constant strings)
1936// * strpbrk(s,"") -> 0
1937// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1938//
1939// strspn, strcspn:
1940// * strspn(s,a) -> const_int (if both args are constant)
1941// * strspn("",a) -> 0
1942// * strspn(s,"") -> 0
1943// * strcspn(s,a) -> const_int (if both args are constant)
1944// * strcspn("",a) -> 0
1945// * strcspn(s,"") -> strlen(a)
1946//
1947// strstr:
1948// * strstr(x,x) -> x
1949// * strstr(s1,s2) -> offset_of_s2_in(s1)
1950// (if s1 and s2 are constant strings)
1951//
1952// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00001953// * tan(atan(x)) -> x
1954//
Reid Spencer649ac282005-04-28 04:40:06 +00001955// trunc, truncf, truncl:
1956// * trunc(cnst) -> cnst'
1957//
1958//
Reid Spencer39a762d2005-04-25 02:53:12 +00001959}