blob: 382bbb879e7ef62343d293b6f3e6a35d57afc405 [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//
Reid Spencer0b13cda2005-05-21 00:57:44 +000010// This file implements a module pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
12// library functions). For example, a call to the function "exit(3)" that
13// occurs within the main() function can be transformed into a simple "return 3"
14// instruction. Any optimization that takes this form (replace call to library
15// function with simpler code that provides the same result) belongs in this
16// file.
Reid Spencer39a762d2005-04-25 02:53:12 +000017//
18//===----------------------------------------------------------------------===//
19
Reid Spencer18b99812005-04-26 23:05:17 +000020#define DEBUG_TYPE "simplify-libcalls"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000021#include "llvm/Constants.h"
22#include "llvm/DerivedTypes.h"
23#include "llvm/Instructions.h"
Reid Spencer39a762d2005-04-25 02:53:12 +000024#include "llvm/Module.h"
25#include "llvm/Pass.h"
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000026#include "llvm/ADT/hash_map"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000027#include "llvm/ADT/Statistic.h"
28#include "llvm/Support/Debug.h"
Reid Spencerbb92b4f2005-04-26 19:13:17 +000029#include "llvm/Target/TargetData.h"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000030#include "llvm/Transforms/IPO.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
Reid Spencer9fbad132005-05-21 01:27:04 +000045/// This hash map is populated by the constructor for LibCallOptimization class.
46/// Therefore all subclasses are registered here at static initialization time
47/// and this list is what the SimplifyLibCalls pass uses to apply the individual
48/// optimizations to the call sites.
Reid Spencer7ddcfb32005-04-27 21:29:20 +000049/// @brief The list of optimizations deriving from LibCallOptimization
Reid Spencer9fbad132005-05-21 01:27:04 +000050static hash_map<std::string,LibCallOptimization*> optlist;
Reid Spencer39a762d2005-04-25 02:53:12 +000051
Reid Spencere249a822005-04-27 07:54:40 +000052/// This class is the abstract base class for the set of optimizations that
Reid Spencer7ddcfb32005-04-27 21:29:20 +000053/// corresponds to one library call. The SimplifyLibCalls pass will call the
Reid Spencere249a822005-04-27 07:54:40 +000054/// ValidateCalledFunction method to ask the optimization if a given Function
Reid Spencer7ddcfb32005-04-27 21:29:20 +000055/// is the kind that the optimization can handle. If the subclass returns true,
56/// then SImplifyLibCalls will also call the OptimizeCall method to perform,
57/// or attempt to perform, the optimization(s) for the library call. Otherwise,
58/// OptimizeCall won't be called. Subclasses are responsible for providing the
59/// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
60/// constructor. This is used to efficiently select which call instructions to
61/// optimize. The criteria for a "lib call" is "anything with well known
62/// semantics", typically a library function that is defined by an international
63/// standard. Because the semantics are well known, the optimizations can
64/// generally short-circuit actually calling the function if there's a simpler
65/// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
Reid Spencere249a822005-04-27 07:54:40 +000066/// @brief Base class for library call optimizations
Jeff Cohen4bc952f2005-04-29 03:05:44 +000067class LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +000068{
Jeff Cohen4bc952f2005-04-29 03:05:44 +000069public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +000070 /// The \p fname argument must be the name of the library function being
71 /// optimized by the subclass.
72 /// @brief Constructor that registers the optimization.
Reid Spencer170ae7f2005-05-07 20:15:59 +000073 LibCallOptimization(const char* fname, const char* description )
Reid Spencer9bbaa2a2005-04-25 03:59:26 +000074 : func_name(fname)
Reid Spencere95a6472005-04-27 00:05:45 +000075#ifndef NDEBUG
Reid Spencer170ae7f2005-05-07 20:15:59 +000076 , occurrences("simplify-libcalls",description)
Reid Spencere95a6472005-04-27 00:05:45 +000077#endif
Reid Spencer39a762d2005-04-25 02:53:12 +000078 {
Reid Spencer7ddcfb32005-04-27 21:29:20 +000079 // Register this call optimizer in the optlist (a hash_map)
Reid Spencer95d8efd2005-05-03 02:54:54 +000080 optlist[fname] = this;
Reid Spencer39a762d2005-04-25 02:53:12 +000081 }
82
Reid Spencer7ddcfb32005-04-27 21:29:20 +000083 /// @brief Deregister from the optlist
84 virtual ~LibCallOptimization() { optlist.erase(func_name); }
Reid Spencer8ee5aac2005-04-26 03:26:15 +000085
Reid Spencere249a822005-04-27 07:54:40 +000086 /// The implementation of this function in subclasses should determine if
87 /// \p F is suitable for the optimization. This method is called by
Reid Spencer7ddcfb32005-04-27 21:29:20 +000088 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
89 /// sites of such a function if that function is not suitable in the first
90 /// place. If the called function is suitabe, this method should return true;
Reid Spencere249a822005-04-27 07:54:40 +000091 /// false, otherwise. This function should also perform any lazy
92 /// initialization that the LibCallOptimization needs to do, if its to return
93 /// true. This avoids doing initialization until the optimizer is actually
94 /// going to be called upon to do some optimization.
Reid Spencer7ddcfb32005-04-27 21:29:20 +000095 /// @brief Determine if the function is suitable for optimization
Reid Spencere249a822005-04-27 07:54:40 +000096 virtual bool ValidateCalledFunction(
97 const Function* F, ///< The function that is the target of call sites
98 SimplifyLibCalls& SLC ///< The pass object invoking us
99 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000100
Reid Spencere249a822005-04-27 07:54:40 +0000101 /// The implementations of this function in subclasses is the heart of the
102 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
103 /// OptimizeCall to determine if (a) the conditions are right for optimizing
104 /// the call and (b) to perform the optimization. If an action is taken
105 /// against ci, the subclass is responsible for returning true and ensuring
106 /// that ci is erased from its parent.
Reid Spencere249a822005-04-27 07:54:40 +0000107 /// @brief Optimize a call, if possible.
108 virtual bool OptimizeCall(
109 CallInst* ci, ///< The call instruction that should be optimized.
110 SimplifyLibCalls& SLC ///< The pass object invoking us
111 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000112
Reid Spencere249a822005-04-27 07:54:40 +0000113 /// @brief Get the name of the library call being optimized
114 const char * getFunctionName() const { return func_name; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000115
Reid Spencere95a6472005-04-27 00:05:45 +0000116#ifndef NDEBUG
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000117 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
Reid Spencer4f01a822005-05-07 04:59:45 +0000118 void succeeded() { DEBUG(++occurrences); }
Reid Spencere95a6472005-04-27 00:05:45 +0000119#endif
Reid Spencere249a822005-04-27 07:54:40 +0000120
121private:
122 const char* func_name; ///< Name of the library call we optimize
123#ifndef NDEBUG
Reid Spencere249a822005-04-27 07:54:40 +0000124 Statistic<> occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
125#endif
126};
127
Reid Spencere249a822005-04-27 07:54:40 +0000128/// This class is an LLVM Pass that applies each of the LibCallOptimization
129/// instances to all the call sites in a module, relatively efficiently. The
130/// purpose of this pass is to provide optimizations for calls to well-known
131/// functions with well-known semantics, such as those in the c library. The
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000132/// class provides the basic infrastructure for handling runOnModule. Whenever /// this pass finds a function call, it asks the appropriate optimizer to
133/// validate the call (ValidateLibraryCall). If it is validated, then
134/// the OptimizeCall method is also called.
Reid Spencere249a822005-04-27 07:54:40 +0000135/// @brief A ModulePass for optimizing well-known function calls.
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000136class SimplifyLibCalls : public ModulePass
Reid Spencere249a822005-04-27 07:54:40 +0000137{
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000138public:
Reid Spencere249a822005-04-27 07:54:40 +0000139 /// We need some target data for accurate signature details that are
140 /// target dependent. So we require target data in our AnalysisUsage.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000141 /// @brief Require TargetData from AnalysisUsage.
Reid Spencere249a822005-04-27 07:54:40 +0000142 virtual void getAnalysisUsage(AnalysisUsage& Info) const
143 {
144 // Ask that the TargetData analysis be performed before us so we can use
145 // the target data.
146 Info.addRequired<TargetData>();
147 }
148
149 /// For this pass, process all of the function calls in the module, calling
150 /// ValidateLibraryCall and OptimizeCall as appropriate.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000151 /// @brief Run all the lib call optimizations on a Module.
Reid Spencere249a822005-04-27 07:54:40 +0000152 virtual bool runOnModule(Module &M)
153 {
154 reset(M);
155
156 bool result = false;
157
158 // The call optimizations can be recursive. That is, the optimization might
159 // generate a call to another function which can also be optimized. This way
160 // we make the LibCallOptimization instances very specific to the case they
161 // handle. It also means we need to keep running over the function calls in
162 // the module until we don't get any more optimizations possible.
163 bool found_optimization = false;
164 do
165 {
166 found_optimization = false;
167 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
168 {
169 // All the "well-known" functions are external and have external linkage
170 // because they live in a runtime library somewhere and were (probably)
Reid Spencer38cabd72005-05-03 07:23:44 +0000171 // not compiled by LLVM. So, we only act on external functions that
172 // have external linkage and non-empty uses.
Reid Spencere249a822005-04-27 07:54:40 +0000173 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
174 continue;
175
176 // Get the optimization class that pertains to this function
177 LibCallOptimization* CO = optlist[FI->getName().c_str()];
178 if (!CO)
179 continue;
180
181 // Make sure the called function is suitable for the optimization
182 if (!CO->ValidateCalledFunction(FI,*this))
183 continue;
184
185 // Loop over each of the uses of the function
186 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
187 UI != UE ; )
188 {
189 // If the use of the function is a call instruction
190 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
191 {
192 // Do the optimization on the LibCallOptimization.
193 if (CO->OptimizeCall(CI,*this))
194 {
195 ++SimplifiedLibCalls;
196 found_optimization = result = true;
197#ifndef NDEBUG
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000198 CO->succeeded();
Reid Spencere249a822005-04-27 07:54:40 +0000199#endif
200 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000201 }
202 }
203 }
Reid Spencere249a822005-04-27 07:54:40 +0000204 } while (found_optimization);
205 return result;
206 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000207
Reid Spencere249a822005-04-27 07:54:40 +0000208 /// @brief Return the *current* module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000209 Module* getModule() const { return M; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000210
Reid Spencere249a822005-04-27 07:54:40 +0000211 /// @brief Return the *current* target data for the module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000212 TargetData* getTargetData() const { return TD; }
213
214 /// @brief Return the size_t type -- syntactic shortcut
215 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
216
217 /// @brief Return a Function* for the fputc libcall
Reid Spencer4c444fe2005-04-30 03:17:54 +0000218 Function* get_fputc(const Type* FILEptr_type)
Reid Spencer93616972005-04-29 09:39:47 +0000219 {
220 if (!fputc_func)
221 {
222 std::vector<const Type*> args;
223 args.push_back(Type::IntTy);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000224 args.push_back(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +0000225 FunctionType* fputc_type =
226 FunctionType::get(Type::IntTy, args, false);
227 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
228 }
229 return fputc_func;
230 }
231
232 /// @brief Return a Function* for the fwrite libcall
Reid Spencer4c444fe2005-04-30 03:17:54 +0000233 Function* get_fwrite(const Type* FILEptr_type)
Reid Spencer93616972005-04-29 09:39:47 +0000234 {
235 if (!fwrite_func)
236 {
237 std::vector<const Type*> args;
238 args.push_back(PointerType::get(Type::SByteTy));
239 args.push_back(TD->getIntPtrType());
240 args.push_back(TD->getIntPtrType());
Reid Spencer4c444fe2005-04-30 03:17:54 +0000241 args.push_back(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +0000242 FunctionType* fwrite_type =
243 FunctionType::get(TD->getIntPtrType(), args, false);
244 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
245 }
246 return fwrite_func;
247 }
248
249 /// @brief Return a Function* for the sqrt libcall
250 Function* get_sqrt()
251 {
252 if (!sqrt_func)
253 {
254 std::vector<const Type*> args;
255 args.push_back(Type::DoubleTy);
256 FunctionType* sqrt_type =
257 FunctionType::get(Type::DoubleTy, args, false);
258 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
259 }
260 return sqrt_func;
261 }
Reid Spencere249a822005-04-27 07:54:40 +0000262
263 /// @brief Return a Function* for the strlen libcall
Reid Spencer1e520fd2005-05-04 03:20:21 +0000264 Function* get_strcpy()
265 {
266 if (!strcpy_func)
267 {
268 std::vector<const Type*> args;
269 args.push_back(PointerType::get(Type::SByteTy));
270 args.push_back(PointerType::get(Type::SByteTy));
271 FunctionType* strcpy_type =
272 FunctionType::get(PointerType::get(Type::SByteTy), args, false);
273 strcpy_func = M->getOrInsertFunction("strcpy",strcpy_type);
274 }
275 return strcpy_func;
276 }
277
278 /// @brief Return a Function* for the strlen libcall
Reid Spencere249a822005-04-27 07:54:40 +0000279 Function* get_strlen()
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000280 {
Reid Spencere249a822005-04-27 07:54:40 +0000281 if (!strlen_func)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000282 {
283 std::vector<const Type*> args;
284 args.push_back(PointerType::get(Type::SByteTy));
Reid Spencere249a822005-04-27 07:54:40 +0000285 FunctionType* strlen_type =
286 FunctionType::get(TD->getIntPtrType(), args, false);
287 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000288 }
Reid Spencere249a822005-04-27 07:54:40 +0000289 return strlen_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000290 }
291
Reid Spencer38cabd72005-05-03 07:23:44 +0000292 /// @brief Return a Function* for the memchr libcall
293 Function* get_memchr()
294 {
295 if (!memchr_func)
296 {
297 std::vector<const Type*> args;
298 args.push_back(PointerType::get(Type::SByteTy));
299 args.push_back(Type::IntTy);
300 args.push_back(TD->getIntPtrType());
301 FunctionType* memchr_type = FunctionType::get(
302 PointerType::get(Type::SByteTy), args, false);
303 memchr_func = M->getOrInsertFunction("memchr",memchr_type);
304 }
305 return memchr_func;
306 }
307
Reid Spencere249a822005-04-27 07:54:40 +0000308 /// @brief Return a Function* for the memcpy libcall
309 Function* get_memcpy()
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000310 {
Reid Spencere249a822005-04-27 07:54:40 +0000311 if (!memcpy_func)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000312 {
313 // Note: this is for llvm.memcpy intrinsic
314 std::vector<const Type*> args;
315 args.push_back(PointerType::get(Type::SByteTy));
316 args.push_back(PointerType::get(Type::SByteTy));
Reid Spencer1e520fd2005-05-04 03:20:21 +0000317 args.push_back(Type::UIntTy);
318 args.push_back(Type::UIntTy);
Reid Spencere249a822005-04-27 07:54:40 +0000319 FunctionType* memcpy_type = FunctionType::get(Type::VoidTy, args, false);
320 memcpy_func = M->getOrInsertFunction("llvm.memcpy",memcpy_type);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000321 }
Reid Spencere249a822005-04-27 07:54:40 +0000322 return memcpy_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000323 }
Reid Spencer76dab9a2005-04-26 05:24:00 +0000324
Reid Spencere249a822005-04-27 07:54:40 +0000325private:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000326 /// @brief Reset our cached data for a new Module
Reid Spencere249a822005-04-27 07:54:40 +0000327 void reset(Module& mod)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000328 {
Reid Spencere249a822005-04-27 07:54:40 +0000329 M = &mod;
330 TD = &getAnalysis<TargetData>();
Reid Spencer93616972005-04-29 09:39:47 +0000331 fputc_func = 0;
332 fwrite_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000333 memcpy_func = 0;
Reid Spencer38cabd72005-05-03 07:23:44 +0000334 memchr_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000335 sqrt_func = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +0000336 strcpy_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000337 strlen_func = 0;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000338 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000339
Reid Spencere249a822005-04-27 07:54:40 +0000340private:
Reid Spencer93616972005-04-29 09:39:47 +0000341 Function* fputc_func; ///< Cached fputc function
342 Function* fwrite_func; ///< Cached fwrite function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000343 Function* memcpy_func; ///< Cached llvm.memcpy function
Reid Spencer38cabd72005-05-03 07:23:44 +0000344 Function* memchr_func; ///< Cached memchr function
Reid Spencer93616972005-04-29 09:39:47 +0000345 Function* sqrt_func; ///< Cached sqrt function
Reid Spencer1e520fd2005-05-04 03:20:21 +0000346 Function* strcpy_func; ///< Cached strcpy function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000347 Function* strlen_func; ///< Cached strlen function
348 Module* M; ///< Cached Module
349 TargetData* TD; ///< Cached TargetData
Reid Spencere249a822005-04-27 07:54:40 +0000350};
351
352// Register the pass
353RegisterOpt<SimplifyLibCalls>
354X("simplify-libcalls","Simplify well-known library calls");
355
356} // anonymous namespace
357
358// The only public symbol in this file which just instantiates the pass object
359ModulePass *llvm::createSimplifyLibCallsPass()
360{
361 return new SimplifyLibCalls();
362}
363
364// Classes below here, in the anonymous namespace, are all subclasses of the
365// LibCallOptimization class, each implementing all optimizations possible for a
366// single well-known library call. Each has a static singleton instance that
367// auto registers it into the "optlist" global above.
368namespace {
369
Reid Spencer08b49402005-04-27 17:46:54 +0000370// Forward declare a utility function.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000371bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
Reid Spencere249a822005-04-27 07:54:40 +0000372
373/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000374/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000375/// the same value passed to the exit function. When this is done, it splits the
376/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000377/// @brief Replace calls to exit in main with a simple return
Reid Spencere249a822005-04-27 07:54:40 +0000378struct ExitInMainOptimization : public LibCallOptimization
Reid Spencer39a762d2005-04-25 02:53:12 +0000379{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000380 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000381 "Number of 'exit' calls simplified") {}
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000382 virtual ~ExitInMainOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000383
384 // Make sure the called function looks like exit (int argument, int return
385 // type, external linkage, not varargs).
Reid Spencere249a822005-04-27 07:54:40 +0000386 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000387 {
Reid Spencerb4f7b832005-04-26 07:45:18 +0000388 if (f->arg_size() >= 1)
389 if (f->arg_begin()->getType()->isInteger())
390 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +0000391 return false;
392 }
393
Reid Spencere249a822005-04-27 07:54:40 +0000394 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000395 {
Reid Spencerf2534c72005-04-25 21:11:48 +0000396 // To be careful, we check that the call to exit is coming from "main", that
397 // main has external linkage, and the return type of main and the argument
398 // to exit have the same type.
399 Function *from = ci->getParent()->getParent();
400 if (from->hasExternalLinkage())
401 if (from->getReturnType() == ci->getOperand(1)->getType())
402 if (from->getName() == "main")
403 {
404 // Okay, time to actually do the optimization. First, get the basic
405 // block of the call instruction
406 BasicBlock* bb = ci->getParent();
Reid Spencer39a762d2005-04-25 02:53:12 +0000407
Reid Spencerf2534c72005-04-25 21:11:48 +0000408 // Create a return instruction that we'll replace the call with.
409 // Note that the argument of the return is the argument of the call
410 // instruction.
411 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000412
Reid Spencerf2534c72005-04-25 21:11:48 +0000413 // Split the block at the call instruction which places it in a new
414 // basic block.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000415 bb->splitBasicBlock(ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000416
Reid Spencerf2534c72005-04-25 21:11:48 +0000417 // The block split caused a branch instruction to be inserted into
418 // the end of the original block, right after the return instruction
419 // that we put there. That's not a valid block, so delete the branch
420 // instruction.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000421 bb->getInstList().pop_back();
Reid Spencer39a762d2005-04-25 02:53:12 +0000422
Reid Spencerf2534c72005-04-25 21:11:48 +0000423 // Now we can finally get rid of the call instruction which now lives
424 // in the new basic block.
425 ci->eraseFromParent();
426
427 // Optimization succeeded, return true.
428 return true;
429 }
430 // We didn't pass the criteria for this optimization so return false
431 return false;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000432 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000433} ExitInMainOptimizer;
434
Reid Spencere249a822005-04-27 07:54:40 +0000435/// This LibCallOptimization will simplify a call to the strcat library
436/// function. The simplification is possible only if the string being
437/// concatenated is a constant array or a constant expression that results in
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000438/// a constant string. In this case we can replace it with strlen + llvm.memcpy
439/// of the constant string. Both of these calls are further reduced, if possible
440/// on subsequent passes.
Reid Spencerf2534c72005-04-25 21:11:48 +0000441/// @brief Simplify the strcat library function.
Reid Spencere249a822005-04-27 07:54:40 +0000442struct StrCatOptimization : public LibCallOptimization
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000443{
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000444public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000445 /// @brief Default constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +0000446 StrCatOptimization() : LibCallOptimization("strcat",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000447 "Number of 'strcat' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000448
449public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000450 /// @breif Destructor
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000451 virtual ~StrCatOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000452
453 /// @brief Make sure that the "strcat" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000454 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000455 {
456 if (f->getReturnType() == PointerType::get(Type::SByteTy))
457 if (f->arg_size() == 2)
458 {
459 Function::const_arg_iterator AI = f->arg_begin();
460 if (AI++->getType() == PointerType::get(Type::SByteTy))
461 if (AI->getType() == PointerType::get(Type::SByteTy))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000462 {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000463 // Indicate this is a suitable call type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000464 return true;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000465 }
Reid Spencerf2534c72005-04-25 21:11:48 +0000466 }
467 return false;
468 }
469
Reid Spencere249a822005-04-27 07:54:40 +0000470 /// @brief Optimize the strcat library function
471 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000472 {
Reid Spencer08b49402005-04-27 17:46:54 +0000473 // Extract some information from the instruction
474 Module* M = ci->getParent()->getParent()->getParent();
475 Value* dest = ci->getOperand(1);
476 Value* src = ci->getOperand(2);
477
Reid Spencer76dab9a2005-04-26 05:24:00 +0000478 // Extract the initializer (while making numerous checks) from the
479 // source operand of the call to strcat. If we get null back, one of
480 // a variety of checks in get_GVInitializer failed
Reid Spencerb4f7b832005-04-26 07:45:18 +0000481 uint64_t len = 0;
Reid Spencer08b49402005-04-27 17:46:54 +0000482 if (!getConstantStringLength(src,len))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000483 return false;
484
Reid Spencerb4f7b832005-04-26 07:45:18 +0000485 // Handle the simple, do-nothing case
486 if (len == 0)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000487 {
Reid Spencer08b49402005-04-27 17:46:54 +0000488 ci->replaceAllUsesWith(dest);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000489 ci->eraseFromParent();
490 return true;
491 }
492
Reid Spencerb4f7b832005-04-26 07:45:18 +0000493 // Increment the length because we actually want to memcpy the null
494 // terminator as well.
495 len++;
Reid Spencerf2534c72005-04-25 21:11:48 +0000496
Reid Spencerb4f7b832005-04-26 07:45:18 +0000497 // We need to find the end of the destination string. That's where the
498 // memory is to be moved to. We just generate a call to strlen (further
Reid Spencere249a822005-04-27 07:54:40 +0000499 // optimized in another pass). Note that the SLC.get_strlen() call
Reid Spencerb4f7b832005-04-26 07:45:18 +0000500 // caches the Function* for us.
501 CallInst* strlen_inst =
Reid Spencer08b49402005-04-27 17:46:54 +0000502 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000503
504 // Now that we have the destination's length, we must index into the
505 // destination's pointer to get the actual memcpy destination (end of
506 // the string .. we're concatenating).
507 std::vector<Value*> idx;
508 idx.push_back(strlen_inst);
509 GetElementPtrInst* gep =
Reid Spencer08b49402005-04-27 17:46:54 +0000510 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000511
512 // We have enough information to now generate the memcpy call to
513 // do the concatenation for us.
514 std::vector<Value*> vals;
515 vals.push_back(gep); // destination
516 vals.push_back(ci->getOperand(2)); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000517 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
518 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000519 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000520
521 // Finally, substitute the first operand of the strcat call for the
522 // strcat call itself since strcat returns its first operand; and,
523 // kill the strcat CallInst.
Reid Spencer08b49402005-04-27 17:46:54 +0000524 ci->replaceAllUsesWith(dest);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000525 ci->eraseFromParent();
526 return true;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000527 }
528} StrCatOptimizer;
529
Reid Spencer38cabd72005-05-03 07:23:44 +0000530/// This LibCallOptimization will simplify a call to the strchr library
531/// function. It optimizes out cases where the arguments are both constant
532/// and the result can be determined statically.
533/// @brief Simplify the strcmp library function.
534struct StrChrOptimization : public LibCallOptimization
535{
536public:
537 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000538 "Number of 'strchr' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +0000539 virtual ~StrChrOptimization() {}
540
541 /// @brief Make sure that the "strchr" function has the right prototype
542 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
543 {
544 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
545 f->arg_size() == 2)
546 return true;
547 return false;
548 }
549
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000550 /// @brief Perform the strchr optimizations
Reid Spencer38cabd72005-05-03 07:23:44 +0000551 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
552 {
553 // If there aren't three operands, bail
554 if (ci->getNumOperands() != 3)
555 return false;
556
557 // Check that the first argument to strchr is a constant array of sbyte.
558 // If it is, get the length and data, otherwise return false.
559 uint64_t len = 0;
560 ConstantArray* CA;
561 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
562 return false;
563
564 // Check that the second argument to strchr is a constant int, return false
565 // if it isn't
566 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
567 if (!CSI)
568 {
569 // Just lower this to memchr since we know the length of the string as
570 // it is constant.
571 Function* f = SLC.get_memchr();
572 std::vector<Value*> args;
573 args.push_back(ci->getOperand(1));
574 args.push_back(ci->getOperand(2));
575 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
576 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
577 ci->eraseFromParent();
578 return true;
579 }
580
581 // Get the character we're looking for
582 int64_t chr = CSI->getValue();
583
584 // Compute the offset
585 uint64_t offset = 0;
586 bool char_found = false;
587 for (uint64_t i = 0; i < len; ++i)
588 {
589 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
590 {
591 // Check for the null terminator
592 if (CI->isNullValue())
593 break; // we found end of string
594 else if (CI->getValue() == chr)
595 {
596 char_found = true;
597 offset = i;
598 break;
599 }
600 }
601 }
602
603 // strchr(s,c) -> offset_of_in(c,s)
604 // (if c is a constant integer and s is a constant string)
605 if (char_found)
606 {
607 std::vector<Value*> indices;
608 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
609 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
610 ci->getOperand(1)->getName()+".strchr",ci);
611 ci->replaceAllUsesWith(GEP);
612 }
613 else
614 ci->replaceAllUsesWith(
615 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
616
617 ci->eraseFromParent();
618 return true;
619 }
620} StrChrOptimizer;
621
Reid Spencer4c444fe2005-04-30 03:17:54 +0000622/// This LibCallOptimization will simplify a call to the strcmp library
623/// function. It optimizes out cases where one or both arguments are constant
624/// and the result can be determined statically.
625/// @brief Simplify the strcmp library function.
626struct StrCmpOptimization : public LibCallOptimization
627{
628public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000629 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000630 "Number of 'strcmp' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +0000631 virtual ~StrCmpOptimization() {}
632
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000633 /// @brief Make sure that the "strcmp" function has the right prototype
Reid Spencer4c444fe2005-04-30 03:17:54 +0000634 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
635 {
636 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
637 return true;
638 return false;
639 }
640
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000641 /// @brief Perform the strcmp optimization
Reid Spencer4c444fe2005-04-30 03:17:54 +0000642 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
643 {
644 // First, check to see if src and destination are the same. If they are,
Reid Spencer16449a92005-04-30 06:45:47 +0000645 // then the optimization is to replace the CallInst with a constant 0
646 // because the call is a no-op.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000647 Value* s1 = ci->getOperand(1);
648 Value* s2 = ci->getOperand(2);
649 if (s1 == s2)
650 {
651 // strcmp(x,x) -> 0
652 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
653 ci->eraseFromParent();
654 return true;
655 }
656
657 bool isstr_1 = false;
658 uint64_t len_1 = 0;
659 ConstantArray* A1;
660 if (getConstantStringLength(s1,len_1,&A1))
661 {
662 isstr_1 = true;
663 if (len_1 == 0)
664 {
665 // strcmp("",x) -> *x
666 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
667 CastInst* cast =
668 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
669 ci->replaceAllUsesWith(cast);
670 ci->eraseFromParent();
671 return true;
672 }
673 }
674
675 bool isstr_2 = false;
676 uint64_t len_2 = 0;
677 ConstantArray* A2;
678 if (getConstantStringLength(s2,len_2,&A2))
679 {
680 isstr_2 = true;
681 if (len_2 == 0)
682 {
683 // strcmp(x,"") -> *x
684 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
685 CastInst* cast =
686 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
687 ci->replaceAllUsesWith(cast);
688 ci->eraseFromParent();
689 return true;
690 }
691 }
692
693 if (isstr_1 && isstr_2)
694 {
695 // strcmp(x,y) -> cnst (if both x and y are constant strings)
696 std::string str1 = A1->getAsString();
697 std::string str2 = A2->getAsString();
698 int result = strcmp(str1.c_str(), str2.c_str());
699 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
700 ci->eraseFromParent();
701 return true;
702 }
703 return false;
704 }
705} StrCmpOptimizer;
706
Reid Spencer49fa07042005-05-03 01:43:45 +0000707/// This LibCallOptimization will simplify a call to the strncmp library
708/// function. It optimizes out cases where one or both arguments are constant
709/// and the result can be determined statically.
710/// @brief Simplify the strncmp library function.
711struct StrNCmpOptimization : public LibCallOptimization
712{
713public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000714 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000715 "Number of 'strncmp' calls simplified") {}
Reid Spencer49fa07042005-05-03 01:43:45 +0000716 virtual ~StrNCmpOptimization() {}
717
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000718 /// @brief Make sure that the "strncmp" function has the right prototype
Reid Spencer49fa07042005-05-03 01:43:45 +0000719 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
720 {
721 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
722 return true;
723 return false;
724 }
725
726 /// @brief Perform the strncpy optimization
727 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
728 {
729 // First, check to see if src and destination are the same. If they are,
730 // then the optimization is to replace the CallInst with a constant 0
731 // because the call is a no-op.
732 Value* s1 = ci->getOperand(1);
733 Value* s2 = ci->getOperand(2);
734 if (s1 == s2)
735 {
736 // strncmp(x,x,l) -> 0
737 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
738 ci->eraseFromParent();
739 return true;
740 }
741
742 // Check the length argument, if it is Constant zero then the strings are
743 // considered equal.
744 uint64_t len_arg = 0;
745 bool len_arg_is_const = false;
746 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
747 {
748 len_arg_is_const = true;
749 len_arg = len_CI->getRawValue();
750 if (len_arg == 0)
751 {
752 // strncmp(x,y,0) -> 0
753 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
754 ci->eraseFromParent();
755 return true;
756 }
757 }
758
759 bool isstr_1 = false;
760 uint64_t len_1 = 0;
761 ConstantArray* A1;
762 if (getConstantStringLength(s1,len_1,&A1))
763 {
764 isstr_1 = true;
765 if (len_1 == 0)
766 {
767 // strncmp("",x) -> *x
768 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
769 CastInst* cast =
770 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
771 ci->replaceAllUsesWith(cast);
772 ci->eraseFromParent();
773 return true;
774 }
775 }
776
777 bool isstr_2 = false;
778 uint64_t len_2 = 0;
779 ConstantArray* A2;
780 if (getConstantStringLength(s2,len_2,&A2))
781 {
782 isstr_2 = true;
783 if (len_2 == 0)
784 {
785 // strncmp(x,"") -> *x
786 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
787 CastInst* cast =
788 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
789 ci->replaceAllUsesWith(cast);
790 ci->eraseFromParent();
791 return true;
792 }
793 }
794
795 if (isstr_1 && isstr_2 && len_arg_is_const)
796 {
797 // strncmp(x,y,const) -> constant
798 std::string str1 = A1->getAsString();
799 std::string str2 = A2->getAsString();
800 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
801 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
802 ci->eraseFromParent();
803 return true;
804 }
805 return false;
806 }
807} StrNCmpOptimizer;
808
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000809/// This LibCallOptimization will simplify a call to the strcpy library
810/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000811/// (1) If src and dest are the same and not volatile, just return dest
812/// (2) If the src is a constant then we can convert to llvm.memmove
813/// @brief Simplify the strcpy library function.
814struct StrCpyOptimization : public LibCallOptimization
815{
816public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000817 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000818 "Number of 'strcpy' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000819 virtual ~StrCpyOptimization() {}
820
821 /// @brief Make sure that the "strcpy" function has the right prototype
822 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
823 {
824 if (f->getReturnType() == PointerType::get(Type::SByteTy))
825 if (f->arg_size() == 2)
826 {
827 Function::const_arg_iterator AI = f->arg_begin();
828 if (AI++->getType() == PointerType::get(Type::SByteTy))
829 if (AI->getType() == PointerType::get(Type::SByteTy))
830 {
831 // Indicate this is a suitable call type.
832 return true;
833 }
834 }
835 return false;
836 }
837
838 /// @brief Perform the strcpy optimization
839 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
840 {
841 // First, check to see if src and destination are the same. If they are,
842 // then the optimization is to replace the CallInst with the destination
843 // because the call is a no-op. Note that this corresponds to the
844 // degenerate strcpy(X,X) case which should have "undefined" results
845 // according to the C specification. However, it occurs sometimes and
846 // we optimize it as a no-op.
847 Value* dest = ci->getOperand(1);
848 Value* src = ci->getOperand(2);
849 if (dest == src)
850 {
851 ci->replaceAllUsesWith(dest);
852 ci->eraseFromParent();
853 return true;
854 }
855
856 // Get the length of the constant string referenced by the second operand,
857 // the "src" parameter. Fail the optimization if we can't get the length
858 // (note that getConstantStringLength does lots of checks to make sure this
859 // is valid).
860 uint64_t len = 0;
861 if (!getConstantStringLength(ci->getOperand(2),len))
862 return false;
863
864 // If the constant string's length is zero we can optimize this by just
865 // doing a store of 0 at the first byte of the destination
866 if (len == 0)
867 {
868 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
869 ci->replaceAllUsesWith(dest);
870 ci->eraseFromParent();
871 return true;
872 }
873
874 // Increment the length because we actually want to memcpy the null
875 // terminator as well.
876 len++;
877
878 // Extract some information from the instruction
879 Module* M = ci->getParent()->getParent()->getParent();
880
881 // We have enough information to now generate the memcpy call to
882 // do the concatenation for us.
883 std::vector<Value*> vals;
884 vals.push_back(dest); // destination
885 vals.push_back(src); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000886 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
887 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000888 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencere249a822005-04-27 07:54:40 +0000889
890 // Finally, substitute the first operand of the strcat call for the
891 // strcat call itself since strcat returns its first operand; and,
892 // kill the strcat CallInst.
893 ci->replaceAllUsesWith(dest);
894 ci->eraseFromParent();
895 return true;
896 }
897} StrCpyOptimizer;
898
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000899/// This LibCallOptimization will simplify a call to the strlen library
900/// function by replacing it with a constant value if the string provided to
901/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000902/// @brief Simplify the strlen library function.
Reid Spencere249a822005-04-27 07:54:40 +0000903struct StrLenOptimization : public LibCallOptimization
Reid Spencer76dab9a2005-04-26 05:24:00 +0000904{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000905 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000906 "Number of 'strlen' calls simplified") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000907 virtual ~StrLenOptimization() {}
908
909 /// @brief Make sure that the "strlen" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000910 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000911 {
Reid Spencere249a822005-04-27 07:54:40 +0000912 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
Reid Spencer76dab9a2005-04-26 05:24:00 +0000913 if (f->arg_size() == 1)
914 if (Function::const_arg_iterator AI = f->arg_begin())
915 if (AI->getType() == PointerType::get(Type::SByteTy))
916 return true;
917 return false;
918 }
919
920 /// @brief Perform the strlen optimization
Reid Spencere249a822005-04-27 07:54:40 +0000921 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000922 {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000923 // Make sure we're dealing with an sbyte* here.
924 Value* str = ci->getOperand(1);
925 if (str->getType() != PointerType::get(Type::SByteTy))
926 return false;
927
928 // Does the call to strlen have exactly one use?
929 if (ci->hasOneUse())
930 // Is that single use a binary operator?
931 if (BinaryOperator* bop = dyn_cast<BinaryOperator>(ci->use_back()))
932 // Is it compared against a constant integer?
933 if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
934 {
935 // Get the value the strlen result is compared to
936 uint64_t val = CI->getRawValue();
937
938 // If its compared against length 0 with == or !=
939 if (val == 0 &&
940 (bop->getOpcode() == Instruction::SetEQ ||
941 bop->getOpcode() == Instruction::SetNE))
942 {
943 // strlen(x) != 0 -> *x != 0
944 // strlen(x) == 0 -> *x == 0
945 LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
946 BinaryOperator* rbop = BinaryOperator::create(bop->getOpcode(),
947 load, ConstantSInt::get(Type::SByteTy,0),
948 bop->getName()+".strlen", ci);
949 bop->replaceAllUsesWith(rbop);
950 bop->eraseFromParent();
951 ci->eraseFromParent();
952 return true;
953 }
954 }
955
956 // Get the length of the constant string operand
Reid Spencerb4f7b832005-04-26 07:45:18 +0000957 uint64_t len = 0;
958 if (!getConstantStringLength(ci->getOperand(1),len))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000959 return false;
960
Reid Spencer170ae7f2005-05-07 20:15:59 +0000961 // strlen("xyz") -> 3 (for example)
Reid Spencere249a822005-04-27 07:54:40 +0000962 ci->replaceAllUsesWith(
963 ConstantInt::get(SLC.getTargetData()->getIntPtrType(),len));
Reid Spencerb4f7b832005-04-26 07:45:18 +0000964 ci->eraseFromParent();
965 return true;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000966 }
967} StrLenOptimizer;
968
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000969/// This LibCallOptimization will simplify a call to the memcpy library
970/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
971/// bytes depending on the length of the string and the alignment. Additional
972/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +0000973/// @brief Simplify the memcpy library function.
Reid Spencer38cabd72005-05-03 07:23:44 +0000974struct LLVMMemCpyOptimization : public LibCallOptimization
Reid Spencerf2534c72005-04-25 21:11:48 +0000975{
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000976 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +0000977 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
Reid Spencer95d8efd2005-05-03 02:54:54 +0000978 "Number of 'llvm.memcpy' calls simplified") {}
979
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000980protected:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000981 /// @brief Subclass Constructor
Reid Spencer170ae7f2005-05-07 20:15:59 +0000982 LLVMMemCpyOptimization(const char* fname, const char* desc)
983 : LibCallOptimization(fname, desc) {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000984public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000985 /// @brief Destructor
Reid Spencer38cabd72005-05-03 07:23:44 +0000986 virtual ~LLVMMemCpyOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000987
988 /// @brief Make sure that the "memcpy" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000989 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +0000990 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000991 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +0000992 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +0000993 }
994
Reid Spencerb4f7b832005-04-26 07:45:18 +0000995 /// Because of alignment and instruction information that we don't have, we
996 /// leave the bulk of this to the code generators. The optimization here just
997 /// deals with a few degenerate cases where the length of the string and the
998 /// alignment match the sizes of our intrinsic types so we can do a load and
999 /// store instead of the memcpy call.
1000 /// @brief Perform the memcpy optimization.
Reid Spencere249a822005-04-27 07:54:40 +00001001 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +00001002 {
Reid Spencer4855ebf2005-04-26 19:55:57 +00001003 // Make sure we have constant int values to work with
1004 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1005 if (!LEN)
1006 return false;
1007 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1008 if (!ALIGN)
1009 return false;
1010
1011 // If the length is larger than the alignment, we can't optimize
1012 uint64_t len = LEN->getRawValue();
1013 uint64_t alignment = ALIGN->getRawValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001014 if (alignment == 0)
1015 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001016 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +00001017 return false;
1018
Reid Spencer08b49402005-04-27 17:46:54 +00001019 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +00001020 Value* dest = ci->getOperand(1);
1021 Value* src = ci->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +00001022 Type* castType = 0;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001023 switch (len)
1024 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001025 case 0:
Reid Spencer93616972005-04-29 09:39:47 +00001026 // memcpy(d,s,0,a) -> noop
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001027 ci->eraseFromParent();
1028 return true;
Reid Spencer08b49402005-04-27 17:46:54 +00001029 case 1: castType = Type::SByteTy; break;
1030 case 2: castType = Type::ShortTy; break;
1031 case 4: castType = Type::IntTy; break;
1032 case 8: castType = Type::LongTy; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001033 default:
1034 return false;
1035 }
Reid Spencer08b49402005-04-27 17:46:54 +00001036
1037 // Cast source and dest to the right sized primitive and then load/store
1038 CastInst* SrcCast =
1039 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
1040 CastInst* DestCast =
1041 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1042 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001043 StoreInst* SI = new StoreInst(LI, DestCast, ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001044 ci->eraseFromParent();
1045 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +00001046 }
Reid Spencer38cabd72005-05-03 07:23:44 +00001047} LLVMMemCpyOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001048
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001049/// This LibCallOptimization will simplify a call to the memmove library
1050/// function. It is identical to MemCopyOptimization except for the name of
1051/// the intrinsic.
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001052/// @brief Simplify the memmove library function.
Reid Spencer38cabd72005-05-03 07:23:44 +00001053struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001054{
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001055 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +00001056 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
Reid Spencer95d8efd2005-05-03 02:54:54 +00001057 "Number of 'llvm.memmove' calls simplified") {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001058
Reid Spencer38cabd72005-05-03 07:23:44 +00001059} LLVMMemMoveOptimizer;
1060
1061/// This LibCallOptimization will simplify a call to the memset library
1062/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1063/// bytes depending on the length argument.
1064struct LLVMMemSetOptimization : public LibCallOptimization
1065{
1066 /// @brief Default Constructor
1067 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
Reid Spencer38cabd72005-05-03 07:23:44 +00001068 "Number of 'llvm.memset' calls simplified") {}
1069
1070public:
1071 /// @brief Destructor
1072 virtual ~LLVMMemSetOptimization() {}
1073
1074 /// @brief Make sure that the "memset" function has the right prototype
1075 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1076 {
1077 // Just make sure this has 3 arguments per LLVM spec.
1078 return (f->arg_size() == 4);
1079 }
1080
1081 /// Because of alignment and instruction information that we don't have, we
1082 /// leave the bulk of this to the code generators. The optimization here just
1083 /// deals with a few degenerate cases where the length parameter is constant
1084 /// and the alignment matches the sizes of our intrinsic types so we can do
1085 /// store instead of the memcpy call. Other calls are transformed into the
1086 /// llvm.memset intrinsic.
1087 /// @brief Perform the memset optimization.
1088 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1089 {
1090 // Make sure we have constant int values to work with
1091 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1092 if (!LEN)
1093 return false;
1094 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1095 if (!ALIGN)
1096 return false;
1097
1098 // Extract the length and alignment
1099 uint64_t len = LEN->getRawValue();
1100 uint64_t alignment = ALIGN->getRawValue();
1101
1102 // Alignment 0 is identity for alignment 1
1103 if (alignment == 0)
1104 alignment = 1;
1105
1106 // If the length is zero, this is a no-op
1107 if (len == 0)
1108 {
1109 // memset(d,c,0,a) -> noop
1110 ci->eraseFromParent();
1111 return true;
1112 }
1113
1114 // If the length is larger than the alignment, we can't optimize
1115 if (len > alignment)
1116 return false;
1117
1118 // Make sure we have a constant ubyte to work with so we can extract
1119 // the value to be filled.
1120 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1121 if (!FILL)
1122 return false;
1123 if (FILL->getType() != Type::UByteTy)
1124 return false;
1125
1126 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
1127
1128 // Extract the fill character
1129 uint64_t fill_char = FILL->getValue();
1130 uint64_t fill_value = fill_char;
1131
1132 // Get the type we will cast to, based on size of memory area to fill, and
1133 // and the value we will store there.
1134 Value* dest = ci->getOperand(1);
1135 Type* castType = 0;
1136 switch (len)
1137 {
1138 case 1:
1139 castType = Type::UByteTy;
1140 break;
1141 case 2:
1142 castType = Type::UShortTy;
1143 fill_value |= fill_char << 8;
1144 break;
1145 case 4:
1146 castType = Type::UIntTy;
1147 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1148 break;
1149 case 8:
1150 castType = Type::ULongTy;
1151 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1152 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1153 fill_value |= fill_char << 56;
1154 break;
1155 default:
1156 return false;
1157 }
1158
1159 // Cast dest to the right sized primitive and then load/store
1160 CastInst* DestCast =
1161 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1162 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1163 ci->eraseFromParent();
1164 return true;
1165 }
1166} LLVMMemSetOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001167
Reid Spencer93616972005-04-29 09:39:47 +00001168/// This LibCallOptimization will simplify calls to the "pow" library
1169/// function. It looks for cases where the result of pow is well known and
1170/// substitutes the appropriate value.
1171/// @brief Simplify the pow library function.
1172struct PowOptimization : public LibCallOptimization
1173{
1174public:
1175 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001176 PowOptimization() : LibCallOptimization("pow",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001177 "Number of 'pow' calls simplified") {}
Reid Spencer95d8efd2005-05-03 02:54:54 +00001178
Reid Spencer93616972005-04-29 09:39:47 +00001179 /// @brief Destructor
1180 virtual ~PowOptimization() {}
1181
1182 /// @brief Make sure that the "pow" function has the right prototype
1183 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1184 {
1185 // Just make sure this has 2 arguments
1186 return (f->arg_size() == 2);
1187 }
1188
1189 /// @brief Perform the pow optimization.
1190 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1191 {
1192 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1193 Value* base = ci->getOperand(1);
1194 Value* expn = ci->getOperand(2);
1195 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1196 double Op1V = Op1->getValue();
1197 if (Op1V == 1.0)
1198 {
1199 // pow(1.0,x) -> 1.0
1200 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1201 ci->eraseFromParent();
1202 return true;
1203 }
1204 }
1205 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
1206 {
1207 double Op2V = Op2->getValue();
1208 if (Op2V == 0.0)
1209 {
1210 // pow(x,0.0) -> 1.0
1211 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1212 ci->eraseFromParent();
1213 return true;
1214 }
1215 else if (Op2V == 0.5)
1216 {
1217 // pow(x,0.5) -> sqrt(x)
1218 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1219 ci->getName()+".pow",ci);
1220 ci->replaceAllUsesWith(sqrt_inst);
1221 ci->eraseFromParent();
1222 return true;
1223 }
1224 else if (Op2V == 1.0)
1225 {
1226 // pow(x,1.0) -> x
1227 ci->replaceAllUsesWith(base);
1228 ci->eraseFromParent();
1229 return true;
1230 }
1231 else if (Op2V == -1.0)
1232 {
1233 // pow(x,-1.0) -> 1.0/x
1234 BinaryOperator* div_inst= BinaryOperator::create(Instruction::Div,
1235 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1236 ci->replaceAllUsesWith(div_inst);
1237 ci->eraseFromParent();
1238 return true;
1239 }
1240 }
1241 return false; // opt failed
1242 }
1243} PowOptimizer;
1244
Reid Spencer45bb4af2005-05-21 00:39:30 +00001245/// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
1246/// inserting the cast before IP, and return the cast.
1247/// @brief Cast a value to a "C" string.
1248static Value *CastToCStr(Value *V, Instruction &IP) {
1249 const Type *SBPTy = PointerType::get(Type::SByteTy);
1250 if (V->getType() != SBPTy)
1251 return new CastInst(V, SBPTy, V->getName(), &IP);
1252 return V;
1253}
1254
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001255/// This LibCallOptimization will simplify calls to the "fprintf" library
1256/// function. It looks for cases where the result of fprintf is not used and the
1257/// operation can be reduced to something simpler.
1258/// @brief Simplify the pow library function.
1259struct FPrintFOptimization : public LibCallOptimization
1260{
1261public:
1262 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001263 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001264 "Number of 'fprintf' calls simplified") {}
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001265
1266 /// @brief Destructor
1267 virtual ~FPrintFOptimization() {}
1268
1269 /// @brief Make sure that the "fprintf" function has the right prototype
1270 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1271 {
1272 // Just make sure this has at least 2 arguments
1273 return (f->arg_size() >= 2);
1274 }
1275
1276 /// @brief Perform the fprintf optimization.
1277 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1278 {
1279 // If the call has more than 3 operands, we can't optimize it
1280 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1281 return false;
1282
1283 // If the result of the fprintf call is used, none of these optimizations
1284 // can be made.
1285 if (!ci->hasNUses(0))
1286 return false;
1287
1288 // All the optimizations depend on the length of the second argument and the
1289 // fact that it is a constant string array. Check that now
1290 uint64_t len = 0;
1291 ConstantArray* CA = 0;
1292 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1293 return false;
1294
1295 if (ci->getNumOperands() == 3)
1296 {
1297 // Make sure there's no % in the constant array
1298 for (unsigned i = 0; i < len; ++i)
1299 {
1300 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1301 {
1302 // Check for the null terminator
1303 if (CI->getRawValue() == '%')
1304 return false; // we found end of string
1305 }
1306 else
1307 return false;
1308 }
1309
Reid Spencer45bb4af2005-05-21 00:39:30 +00001310 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001311 const Type* FILEptr_type = ci->getOperand(1)->getType();
1312 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1313 if (!fwrite_func)
1314 return false;
1315 std::vector<Value*> args;
1316 args.push_back(ci->getOperand(2));
1317 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1318 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1319 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001320 new CallInst(fwrite_func,args,ci->getName(),ci);
1321 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001322 ci->eraseFromParent();
1323 return true;
1324 }
1325
1326 // The remaining optimizations require the format string to be length 2
1327 // "%s" or "%c".
1328 if (len != 2)
1329 return false;
1330
1331 // The first character has to be a %
1332 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1333 if (CI->getRawValue() != '%')
1334 return false;
1335
1336 // Get the second character and switch on its value
1337 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1338 switch (CI->getRawValue())
1339 {
1340 case 's':
1341 {
1342 uint64_t len = 0;
1343 ConstantArray* CA = 0;
1344 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1345 return false;
1346
Reid Spencer1e520fd2005-05-04 03:20:21 +00001347 // fprintf(file,"%s",str) -> fwrite(fmt,strlen(fmt),1,file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001348 const Type* FILEptr_type = ci->getOperand(1)->getType();
1349 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1350 if (!fwrite_func)
1351 return false;
1352 std::vector<Value*> args;
Reid Spencer45bb4af2005-05-21 00:39:30 +00001353 args.push_back(CastToCStr(ci->getOperand(3), *ci));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001354 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1355 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1356 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001357 new CallInst(fwrite_func,args,ci->getName(),ci);
1358 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001359 break;
1360 }
1361 case 'c':
1362 {
1363 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1364 if (!CI)
1365 return false;
1366
1367 const Type* FILEptr_type = ci->getOperand(1)->getType();
1368 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1369 if (!fputc_func)
1370 return false;
1371 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1372 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
Reid Spencer1e520fd2005-05-04 03:20:21 +00001373 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001374 break;
1375 }
1376 default:
1377 return false;
1378 }
1379 ci->eraseFromParent();
1380 return true;
1381 }
1382} FPrintFOptimizer;
1383
Reid Spencer1e520fd2005-05-04 03:20:21 +00001384/// This LibCallOptimization will simplify calls to the "sprintf" library
1385/// function. It looks for cases where the result of sprintf is not used and the
1386/// operation can be reduced to something simpler.
1387/// @brief Simplify the pow library function.
1388struct SPrintFOptimization : public LibCallOptimization
1389{
1390public:
1391 /// @brief Default Constructor
1392 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001393 "Number of 'sprintf' calls simplified") {}
Reid Spencer1e520fd2005-05-04 03:20:21 +00001394
1395 /// @brief Destructor
1396 virtual ~SPrintFOptimization() {}
1397
1398 /// @brief Make sure that the "fprintf" function has the right prototype
1399 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1400 {
1401 // Just make sure this has at least 2 arguments
1402 return (f->getReturnType() == Type::IntTy && f->arg_size() >= 2);
1403 }
1404
1405 /// @brief Perform the sprintf optimization.
1406 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1407 {
1408 // If the call has more than 3 operands, we can't optimize it
1409 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1410 return false;
1411
1412 // All the optimizations depend on the length of the second argument and the
1413 // fact that it is a constant string array. Check that now
1414 uint64_t len = 0;
1415 ConstantArray* CA = 0;
1416 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1417 return false;
1418
1419 if (ci->getNumOperands() == 3)
1420 {
1421 if (len == 0)
1422 {
1423 // If the length is 0, we just need to store a null byte
1424 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
1425 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1426 ci->eraseFromParent();
1427 return true;
1428 }
1429
1430 // Make sure there's no % in the constant array
1431 for (unsigned i = 0; i < len; ++i)
1432 {
1433 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1434 {
1435 // Check for the null terminator
1436 if (CI->getRawValue() == '%')
1437 return false; // we found a %, can't optimize
1438 }
1439 else
1440 return false; // initializer is not constant int, can't optimize
1441 }
1442
1443 // Increment length because we want to copy the null byte too
1444 len++;
1445
1446 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
1447 Function* memcpy_func = SLC.get_memcpy();
1448 if (!memcpy_func)
1449 return false;
1450 std::vector<Value*> args;
1451 args.push_back(ci->getOperand(1));
1452 args.push_back(ci->getOperand(2));
1453 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1454 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1455 new CallInst(memcpy_func,args,"",ci);
1456 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1457 ci->eraseFromParent();
1458 return true;
1459 }
1460
1461 // The remaining optimizations require the format string to be length 2
1462 // "%s" or "%c".
1463 if (len != 2)
1464 return false;
1465
1466 // The first character has to be a %
1467 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1468 if (CI->getRawValue() != '%')
1469 return false;
1470
1471 // Get the second character and switch on its value
1472 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1473 switch (CI->getRawValue())
1474 {
1475 case 's':
1476 {
1477 uint64_t len = 0;
1478 if (ci->hasNUses(0))
1479 {
1480 // sprintf(dest,"%s",str) -> strcpy(dest,str)
1481 Function* strcpy_func = SLC.get_strcpy();
1482 if (!strcpy_func)
1483 return false;
1484 std::vector<Value*> args;
Chris Lattnerf8053ce2005-05-20 22:22:25 +00001485 args.push_back(CastToCStr(ci->getOperand(1), *ci));
1486 args.push_back(CastToCStr(ci->getOperand(3), *ci));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001487 new CallInst(strcpy_func,args,"",ci);
1488 }
1489 else if (getConstantStringLength(ci->getOperand(3),len))
1490 {
1491 // sprintf(dest,"%s",cstr) -> llvm.memcpy(dest,str,strlen(str),1)
1492 len++; // get the null-terminator
1493 Function* memcpy_func = SLC.get_memcpy();
1494 if (!memcpy_func)
1495 return false;
1496 std::vector<Value*> args;
Chris Lattnerf8053ce2005-05-20 22:22:25 +00001497 args.push_back(CastToCStr(ci->getOperand(1), *ci));
1498 args.push_back(CastToCStr(ci->getOperand(3), *ci));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001499 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1500 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1501 new CallInst(memcpy_func,args,"",ci);
1502 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1503 }
1504 break;
1505 }
1506 case 'c':
1507 {
1508 // sprintf(dest,"%c",chr) -> store chr, dest
1509 CastInst* cast =
1510 new CastInst(ci->getOperand(3),Type::SByteTy,"char",ci);
1511 new StoreInst(cast, ci->getOperand(1), ci);
1512 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1513 ConstantUInt::get(Type::UIntTy,1),ci->getOperand(1)->getName()+".end",
1514 ci);
1515 new StoreInst(ConstantInt::get(Type::SByteTy,0),gep,ci);
1516 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1517 break;
1518 }
1519 default:
1520 return false;
1521 }
1522 ci->eraseFromParent();
1523 return true;
1524 }
1525} SPrintFOptimizer;
1526
Reid Spencer93616972005-04-29 09:39:47 +00001527/// This LibCallOptimization will simplify calls to the "fputs" library
1528/// function. It looks for cases where the result of fputs is not used and the
1529/// operation can be reduced to something simpler.
1530/// @brief Simplify the pow library function.
1531struct PutsOptimization : public LibCallOptimization
1532{
1533public:
1534 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001535 PutsOptimization() : LibCallOptimization("fputs",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001536 "Number of 'fputs' calls simplified") {}
Reid Spencer93616972005-04-29 09:39:47 +00001537
1538 /// @brief Destructor
1539 virtual ~PutsOptimization() {}
1540
1541 /// @brief Make sure that the "fputs" function has the right prototype
1542 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1543 {
1544 // Just make sure this has 2 arguments
1545 return (f->arg_size() == 2);
1546 }
1547
1548 /// @brief Perform the fputs optimization.
1549 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1550 {
1551 // If the result is used, none of these optimizations work
1552 if (!ci->hasNUses(0))
1553 return false;
1554
1555 // All the optimizations depend on the length of the first argument and the
1556 // fact that it is a constant string array. Check that now
1557 uint64_t len = 0;
1558 if (!getConstantStringLength(ci->getOperand(1), len))
1559 return false;
1560
1561 switch (len)
1562 {
1563 case 0:
1564 // fputs("",F) -> noop
1565 break;
1566 case 1:
1567 {
1568 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001569 const Type* FILEptr_type = ci->getOperand(2)->getType();
1570 Function* fputc_func = SLC.get_fputc(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001571 if (!fputc_func)
1572 return false;
1573 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1574 ci->getOperand(1)->getName()+".byte",ci);
1575 CastInst* casti = new CastInst(loadi,Type::IntTy,
1576 loadi->getName()+".int",ci);
1577 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1578 break;
1579 }
1580 default:
1581 {
1582 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001583 const Type* FILEptr_type = ci->getOperand(2)->getType();
1584 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001585 if (!fwrite_func)
1586 return false;
1587 std::vector<Value*> parms;
1588 parms.push_back(ci->getOperand(1));
1589 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1590 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1591 parms.push_back(ci->getOperand(2));
1592 new CallInst(fwrite_func,parms,"",ci);
1593 break;
1594 }
1595 }
1596 ci->eraseFromParent();
1597 return true; // success
1598 }
1599} PutsOptimizer;
1600
Reid Spencer282d0572005-05-04 18:58:28 +00001601/// This LibCallOptimization will simplify calls to the "isdigit" library
1602/// function. It simply does range checks the parameter explicitly.
1603/// @brief Simplify the isdigit library function.
1604struct IsDigitOptimization : public LibCallOptimization
1605{
1606public:
1607 /// @brief Default Constructor
1608 IsDigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001609 "Number of 'isdigit' calls simplified") {}
Reid Spencer282d0572005-05-04 18:58:28 +00001610
1611 /// @brief Destructor
1612 virtual ~IsDigitOptimization() {}
1613
1614 /// @brief Make sure that the "fputs" function has the right prototype
1615 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1616 {
1617 // Just make sure this has 1 argument
1618 return (f->arg_size() == 1);
1619 }
1620
1621 /// @brief Perform the toascii optimization.
1622 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1623 {
1624 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1625 {
1626 // isdigit(c) -> 0 or 1, if 'c' is constant
1627 uint64_t val = CI->getRawValue();
1628 if (val >= '0' && val <='9')
1629 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1630 else
1631 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1632 ci->eraseFromParent();
1633 return true;
1634 }
1635
1636 // isdigit(c) -> (unsigned)c - '0' <= 9
1637 CastInst* cast =
1638 new CastInst(ci->getOperand(1),Type::UIntTy,
1639 ci->getOperand(1)->getName()+".uint",ci);
1640 BinaryOperator* sub_inst = BinaryOperator::create(Instruction::Sub,cast,
1641 ConstantUInt::get(Type::UIntTy,0x30),
1642 ci->getOperand(1)->getName()+".sub",ci);
1643 SetCondInst* setcond_inst = new SetCondInst(Instruction::SetLE,sub_inst,
1644 ConstantUInt::get(Type::UIntTy,9),
1645 ci->getOperand(1)->getName()+".cmp",ci);
1646 CastInst* c2 =
1647 new CastInst(setcond_inst,Type::IntTy,
1648 ci->getOperand(1)->getName()+".isdigit",ci);
1649 ci->replaceAllUsesWith(c2);
1650 ci->eraseFromParent();
1651 return true;
1652 }
1653} IsDigitOptimizer;
1654
Reid Spencer4c444fe2005-04-30 03:17:54 +00001655/// This LibCallOptimization will simplify calls to the "toascii" library
1656/// function. It simply does the corresponding and operation to restrict the
1657/// range of values to the ASCII character set (0-127).
1658/// @brief Simplify the toascii library function.
1659struct ToAsciiOptimization : public LibCallOptimization
1660{
1661public:
1662 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001663 ToAsciiOptimization() : LibCallOptimization("toascii",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001664 "Number of 'toascii' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +00001665
1666 /// @brief Destructor
1667 virtual ~ToAsciiOptimization() {}
1668
1669 /// @brief Make sure that the "fputs" function has the right prototype
1670 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1671 {
1672 // Just make sure this has 2 arguments
1673 return (f->arg_size() == 1);
1674 }
1675
1676 /// @brief Perform the toascii optimization.
1677 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1678 {
1679 // toascii(c) -> (c & 0x7f)
1680 Value* chr = ci->getOperand(1);
1681 BinaryOperator* and_inst = BinaryOperator::create(Instruction::And,chr,
1682 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1683 ci->replaceAllUsesWith(and_inst);
1684 ci->eraseFromParent();
1685 return true;
1686 }
1687} ToAsciiOptimizer;
1688
Reid Spencerb195fcd2005-05-14 16:42:52 +00001689/// This LibCallOptimization will simplify calls to the "ffs" library
1690/// calls which find the first set bit in an int, long, or long long. The
1691/// optimization is to compute the result at compile time if the argument is
1692/// a constant.
1693/// @brief Simplify the ffs library function.
1694struct FFSOptimization : public LibCallOptimization
1695{
1696protected:
1697 /// @brief Subclass Constructor
1698 FFSOptimization(const char* funcName, const char* description)
1699 : LibCallOptimization(funcName, description)
1700 {}
1701
1702public:
1703 /// @brief Default Constructor
1704 FFSOptimization() : LibCallOptimization("ffs",
1705 "Number of 'ffs' calls simplified") {}
1706
1707 /// @brief Destructor
1708 virtual ~FFSOptimization() {}
1709
1710 /// @brief Make sure that the "fputs" function has the right prototype
1711 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1712 {
1713 // Just make sure this has 2 arguments
1714 return (f->arg_size() == 1 && f->getReturnType() == Type::IntTy);
1715 }
1716
1717 /// @brief Perform the ffs optimization.
1718 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1719 {
1720 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1721 {
1722 // ffs(cnst) -> bit#
1723 // ffsl(cnst) -> bit#
Reid Spencer17f77842005-05-15 21:19:45 +00001724 // ffsll(cnst) -> bit#
Reid Spencerb195fcd2005-05-14 16:42:52 +00001725 uint64_t val = CI->getRawValue();
Reid Spencer17f77842005-05-15 21:19:45 +00001726 int result = 0;
1727 while (val != 0) {
1728 result +=1;
1729 if (val&1)
1730 break;
1731 val >>= 1;
1732 }
Reid Spencerb195fcd2005-05-14 16:42:52 +00001733 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy, result));
1734 ci->eraseFromParent();
1735 return true;
1736 }
Reid Spencer17f77842005-05-15 21:19:45 +00001737
1738 // ffs(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1739 // ffsl(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1740 // ffsll(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1741 const Type* arg_type = ci->getOperand(1)->getType();
1742 std::vector<const Type*> args;
1743 args.push_back(arg_type);
1744 FunctionType* llvm_cttz_type = FunctionType::get(arg_type,args,false);
1745 Function* F =
1746 SLC.getModule()->getOrInsertFunction("llvm.cttz",llvm_cttz_type);
1747 std::string inst_name(ci->getName()+".ffs");
1748 Instruction* call =
1749 new CallInst(F, ci->getOperand(1), inst_name, ci);
1750 if (arg_type != Type::IntTy)
1751 call = new CastInst(call, Type::IntTy, inst_name, ci);
1752 BinaryOperator* add = BinaryOperator::create(Instruction::Add, call,
1753 ConstantSInt::get(Type::IntTy,1), inst_name, ci);
1754 SetCondInst* eq = new SetCondInst(Instruction::SetEQ,ci->getOperand(1),
1755 ConstantSInt::get(ci->getOperand(1)->getType(),0),inst_name,ci);
1756 SelectInst* select = new SelectInst(eq,ConstantSInt::get(Type::IntTy,0),add,
1757 inst_name,ci);
1758 ci->replaceAllUsesWith(select);
1759 ci->eraseFromParent();
1760 return true;
Reid Spencerb195fcd2005-05-14 16:42:52 +00001761 }
1762} FFSOptimizer;
1763
1764/// This LibCallOptimization will simplify calls to the "ffsl" library
1765/// calls. It simply uses FFSOptimization for which the transformation is
1766/// identical.
1767/// @brief Simplify the ffsl library function.
1768struct FFSLOptimization : public FFSOptimization
1769{
1770public:
1771 /// @brief Default Constructor
1772 FFSLOptimization() : FFSOptimization("ffsl",
1773 "Number of 'ffsl' calls simplified") {}
1774
1775} FFSLOptimizer;
1776
1777/// This LibCallOptimization will simplify calls to the "ffsll" library
1778/// calls. It simply uses FFSOptimization for which the transformation is
1779/// identical.
1780/// @brief Simplify the ffsl library function.
1781struct FFSLLOptimization : public FFSOptimization
1782{
1783public:
1784 /// @brief Default Constructor
1785 FFSLLOptimization() : FFSOptimization("ffsll",
1786 "Number of 'ffsll' calls simplified") {}
1787
1788} FFSLLOptimizer;
1789
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001790/// A function to compute the length of a null-terminated constant array of
1791/// integers. This function can't rely on the size of the constant array
1792/// because there could be a null terminator in the middle of the array.
1793/// We also have to bail out if we find a non-integer constant initializer
1794/// of one of the elements or if there is no null-terminator. The logic
1795/// below checks each of these conditions and will return true only if all
1796/// conditions are met. In that case, the \p len parameter is set to the length
1797/// of the null-terminated string. If false is returned, the conditions were
1798/// not met and len is set to 0.
1799/// @brief Get the length of a constant string (null-terminated array).
Reid Spencer4c444fe2005-04-30 03:17:54 +00001800bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
Reid Spencere249a822005-04-27 07:54:40 +00001801{
1802 assert(V != 0 && "Invalid args to getConstantStringLength");
1803 len = 0; // make sure we initialize this
1804 User* GEP = 0;
1805 // If the value is not a GEP instruction nor a constant expression with a
1806 // GEP instruction, then return false because ConstantArray can't occur
1807 // any other way
1808 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1809 GEP = GEPI;
1810 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1811 if (CE->getOpcode() == Instruction::GetElementPtr)
1812 GEP = CE;
1813 else
1814 return false;
1815 else
1816 return false;
1817
1818 // Make sure the GEP has exactly three arguments.
1819 if (GEP->getNumOperands() != 3)
1820 return false;
1821
1822 // Check to make sure that the first operand of the GEP is an integer and
1823 // has value 0 so that we are sure we're indexing into the initializer.
1824 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1825 {
1826 if (!op1->isNullValue())
1827 return false;
1828 }
1829 else
1830 return false;
1831
1832 // Ensure that the second operand is a ConstantInt. If it isn't then this
1833 // GEP is wonky and we're not really sure what were referencing into and
1834 // better of not optimizing it. While we're at it, get the second index
1835 // value. We'll need this later for indexing the ConstantArray.
1836 uint64_t start_idx = 0;
1837 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1838 start_idx = CI->getRawValue();
1839 else
1840 return false;
1841
1842 // The GEP instruction, constant or instruction, must reference a global
1843 // variable that is a constant and is initialized. The referenced constant
1844 // initializer is the array that we'll use for optimization.
1845 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1846 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1847 return false;
1848
1849 // Get the initializer.
1850 Constant* INTLZR = GV->getInitializer();
1851
1852 // Handle the ConstantAggregateZero case
1853 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
1854 {
1855 // This is a degenerate case. The initializer is constant zero so the
1856 // length of the string must be zero.
1857 len = 0;
1858 return true;
1859 }
1860
1861 // Must be a Constant Array
1862 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
1863 if (!A)
1864 return false;
1865
1866 // Get the number of elements in the array
1867 uint64_t max_elems = A->getType()->getNumElements();
1868
1869 // Traverse the constant array from start_idx (derived above) which is
1870 // the place the GEP refers to in the array.
1871 for ( len = start_idx; len < max_elems; len++)
1872 {
1873 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
1874 {
1875 // Check for the null terminator
1876 if (CI->isNullValue())
1877 break; // we found end of string
1878 }
1879 else
1880 return false; // This array isn't suitable, non-int initializer
1881 }
1882 if (len >= max_elems)
1883 return false; // This array isn't null terminated
1884
1885 // Subtract out the initial value from the length
1886 len -= start_idx;
Reid Spencer4c444fe2005-04-30 03:17:54 +00001887 if (CA)
1888 *CA = A;
Reid Spencere249a822005-04-27 07:54:40 +00001889 return true; // success!
1890}
1891
Reid Spencer649ac282005-04-28 04:40:06 +00001892// TODO:
1893// Additional cases that we need to add to this file:
1894//
Reid Spencer649ac282005-04-28 04:40:06 +00001895// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +00001896// * cbrt(expN(X)) -> expN(x/3)
1897// * cbrt(sqrt(x)) -> pow(x,1/6)
1898// * cbrt(sqrt(x)) -> pow(x,1/9)
1899//
Reid Spencer649ac282005-04-28 04:40:06 +00001900// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +00001901// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +00001902//
1903// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +00001904// * exp(log(x)) -> x
1905//
Reid Spencer649ac282005-04-28 04:40:06 +00001906// isascii:
1907// * isascii(c) -> ((c & ~0x7f) == 0)
1908//
1909// isdigit:
1910// * isdigit(c) -> (unsigned)(c) - '0' <= 9
1911//
1912// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +00001913// * log(exp(x)) -> x
1914// * log(x**y) -> y*log(x)
1915// * log(exp(y)) -> y*log(e)
1916// * log(exp2(y)) -> y*log(2)
1917// * log(exp10(y)) -> y*log(10)
1918// * log(sqrt(x)) -> 0.5*log(x)
1919// * log(pow(x,y)) -> y*log(x)
1920//
1921// lround, lroundf, lroundl:
1922// * lround(cnst) -> cnst'
1923//
1924// memcmp:
1925// * memcmp(s1,s2,0) -> 0
1926// * memcmp(x,x,l) -> 0
1927// * memcmp(x,y,l) -> cnst
1928// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer38cabd72005-05-03 07:23:44 +00001929// * memcmp(x,y,1) -> *x - *y
Reid Spencer649ac282005-04-28 04:40:06 +00001930//
Reid Spencer649ac282005-04-28 04:40:06 +00001931// memmove:
1932// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1933// (if s is a global constant array)
1934//
Reid Spencer649ac282005-04-28 04:40:06 +00001935// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00001936// * pow(exp(x),y) -> exp(x*y)
1937// * pow(sqrt(x),y) -> pow(x,y*0.5)
1938// * pow(pow(x,y),z)-> pow(x,y*z)
1939//
1940// puts:
1941// * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
1942//
1943// round, roundf, roundl:
1944// * round(cnst) -> cnst'
1945//
1946// signbit:
1947// * signbit(cnst) -> cnst'
1948// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1949//
Reid Spencer649ac282005-04-28 04:40:06 +00001950// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00001951// * sqrt(expN(x)) -> expN(x*0.5)
1952// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1953// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1954//
Reid Spencer170ae7f2005-05-07 20:15:59 +00001955// stpcpy:
1956// * stpcpy(str, "literal") ->
1957// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer38cabd72005-05-03 07:23:44 +00001958// strrchr:
Reid Spencer649ac282005-04-28 04:40:06 +00001959// * strrchr(s,c) -> reverse_offset_of_in(c,s)
1960// (if c is a constant integer and s is a constant string)
1961// * strrchr(s1,0) -> strchr(s1,0)
1962//
Reid Spencer649ac282005-04-28 04:40:06 +00001963// strncat:
1964// * strncat(x,y,0) -> x
1965// * strncat(x,y,0) -> x (if strlen(y) = 0)
1966// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1967//
Reid Spencer649ac282005-04-28 04:40:06 +00001968// strncpy:
1969// * strncpy(d,s,0) -> d
1970// * strncpy(d,s,l) -> memcpy(d,s,l,1)
1971// (if s and l are constants)
1972//
1973// strpbrk:
1974// * strpbrk(s,a) -> offset_in_for(s,a)
1975// (if s and a are both constant strings)
1976// * strpbrk(s,"") -> 0
1977// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1978//
1979// strspn, strcspn:
1980// * strspn(s,a) -> const_int (if both args are constant)
1981// * strspn("",a) -> 0
1982// * strspn(s,"") -> 0
1983// * strcspn(s,a) -> const_int (if both args are constant)
1984// * strcspn("",a) -> 0
1985// * strcspn(s,"") -> strlen(a)
1986//
1987// strstr:
1988// * strstr(x,x) -> x
1989// * strstr(s1,s2) -> offset_of_s2_in(s1)
1990// (if s1 and s2 are constant strings)
1991//
1992// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00001993// * tan(atan(x)) -> x
1994//
Reid Spencer649ac282005-04-28 04:40:06 +00001995// trunc, truncf, truncl:
1996// * trunc(cnst) -> cnst'
1997//
1998//
Reid Spencer39a762d2005-04-25 02:53:12 +00001999}