blob: eae2102d2fdb0004ff97cd8f3add91abbb1bd08d [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//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00005// This file was developed by Reid Spencer and is distributed under the
Reid Spencer9bbaa2a2005-04-25 03:59:26 +00006// University of Illinois Open Source License. See LICENSE.TXT for details.
Reid Spencer39a762d2005-04-25 02:53:12 +00007//
8//===----------------------------------------------------------------------===//
9//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +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
Reid Spencer0b13cda2005-05-21 00:57:44 +000013// occurs within the main() function can be transformed into a simple "return 3"
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000014// 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.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000038Statistic<> SimplifiedLibCalls("simplify-libcalls",
Chris Lattner579b20b2005-08-07 20:02:04 +000039 "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,
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000056/// then SImplifyLibCalls will also call the OptimizeCall method to perform,
Reid Spencer7ddcfb32005-04-27 21:29:20 +000057/// 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
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000061/// optimize. The criteria for a "lib call" is "anything with well known
Reid Spencer7ddcfb32005-04-27 21:29:20 +000062/// semantics", typically a library function that is defined by an international
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000063/// standard. Because the semantics are well known, the optimizations can
Reid Spencer7ddcfb32005-04-27 21:29:20 +000064/// 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:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000070 /// The \p fname argument must be the name of the library function being
Reid Spencer7ddcfb32005-04-27 21:29:20 +000071 /// 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
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000087 /// \p F is suitable for the optimization. This method is called by
88 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
89 /// sites of such a function if that function is not suitable in the first
Reid Spencer7ddcfb32005-04-27 21:29:20 +000090 /// place. If the called function is suitabe, this method should return true;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000091 /// false, otherwise. This function should also perform any lazy
92 /// initialization that the LibCallOptimization needs to do, if its to return
Reid Spencere249a822005-04-27 07:54:40 +000093 /// 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
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000101 /// The implementations of this function in subclasses is the heart of the
102 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
Reid Spencere249a822005-04-27 07:54:40 +0000103 /// OptimizeCall to determine if (a) the conditions are right for optimizing
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000104 /// the call and (b) to perform the optimization. If an action is taken
Reid Spencere249a822005-04-27 07:54:40 +0000105 /// 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
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000128/// This class is an LLVM Pass that applies each of the LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +0000129/// instances to all the call sites in a module, relatively efficiently. The
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000130/// purpose of this pass is to provide optimizations for calls to well-known
Reid Spencere249a822005-04-27 07:54:40 +0000131/// functions with well-known semantics, such as those in the c library. The
Chris Lattner4201cd12005-08-24 17:22:17 +0000132/// class provides the basic infrastructure for handling runOnModule. Whenever
133/// this pass finds a function call, it asks the appropriate optimizer to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000134/// validate the call (ValidateLibraryCall). If it is validated, then
135/// the OptimizeCall method is also called.
Reid Spencere249a822005-04-27 07:54:40 +0000136/// @brief A ModulePass for optimizing well-known function calls.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000137class SimplifyLibCalls : public ModulePass
Reid Spencere249a822005-04-27 07:54:40 +0000138{
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000139public:
Reid Spencere249a822005-04-27 07:54:40 +0000140 /// We need some target data for accurate signature details that are
141 /// target dependent. So we require target data in our AnalysisUsage.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000142 /// @brief Require TargetData from AnalysisUsage.
Reid Spencere249a822005-04-27 07:54:40 +0000143 virtual void getAnalysisUsage(AnalysisUsage& Info) const
144 {
145 // Ask that the TargetData analysis be performed before us so we can use
146 // the target data.
147 Info.addRequired<TargetData>();
148 }
149
150 /// For this pass, process all of the function calls in the module, calling
151 /// ValidateLibraryCall and OptimizeCall as appropriate.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000152 /// @brief Run all the lib call optimizations on a Module.
Reid Spencere249a822005-04-27 07:54:40 +0000153 virtual bool runOnModule(Module &M)
154 {
155 reset(M);
156
157 bool result = false;
158
159 // The call optimizations can be recursive. That is, the optimization might
160 // generate a call to another function which can also be optimized. This way
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000161 // we make the LibCallOptimization instances very specific to the case they
162 // handle. It also means we need to keep running over the function calls in
Reid Spencere249a822005-04-27 07:54:40 +0000163 // the module until we don't get any more optimizations possible.
164 bool found_optimization = false;
165 do
166 {
167 found_optimization = false;
168 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI)
169 {
170 // All the "well-known" functions are external and have external linkage
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000171 // because they live in a runtime library somewhere and were (probably)
172 // not compiled by LLVM. So, we only act on external functions that
Reid Spencer38cabd72005-05-03 07:23:44 +0000173 // have external linkage and non-empty uses.
Reid Spencere249a822005-04-27 07:54:40 +0000174 if (!FI->isExternal() || !FI->hasExternalLinkage() || FI->use_empty())
175 continue;
176
177 // Get the optimization class that pertains to this function
178 LibCallOptimization* CO = optlist[FI->getName().c_str()];
179 if (!CO)
180 continue;
181
182 // Make sure the called function is suitable for the optimization
183 if (!CO->ValidateCalledFunction(FI,*this))
184 continue;
185
186 // Loop over each of the uses of the function
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000187 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
Reid Spencere249a822005-04-27 07:54:40 +0000188 UI != UE ; )
189 {
190 // If the use of the function is a call instruction
191 if (CallInst* CI = dyn_cast<CallInst>(*UI++))
192 {
193 // Do the optimization on the LibCallOptimization.
194 if (CO->OptimizeCall(CI,*this))
195 {
196 ++SimplifiedLibCalls;
197 found_optimization = result = true;
198#ifndef NDEBUG
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000199 CO->succeeded();
Reid Spencere249a822005-04-27 07:54:40 +0000200#endif
201 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000202 }
203 }
204 }
Reid Spencere249a822005-04-27 07:54:40 +0000205 } while (found_optimization);
206 return result;
207 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000208
Reid Spencere249a822005-04-27 07:54:40 +0000209 /// @brief Return the *current* module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000210 Module* getModule() const { return M; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000211
Reid Spencere249a822005-04-27 07:54:40 +0000212 /// @brief Return the *current* target data for the module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000213 TargetData* getTargetData() const { return TD; }
214
215 /// @brief Return the size_t type -- syntactic shortcut
216 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
217
218 /// @brief Return a Function* for the fputc libcall
Reid Spencer4c444fe2005-04-30 03:17:54 +0000219 Function* get_fputc(const Type* FILEptr_type)
Reid Spencer93616972005-04-29 09:39:47 +0000220 {
221 if (!fputc_func)
222 {
223 std::vector<const Type*> args;
224 args.push_back(Type::IntTy);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000225 args.push_back(FILEptr_type);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000226 FunctionType* fputc_type =
Reid Spencer93616972005-04-29 09:39:47 +0000227 FunctionType::get(Type::IntTy, args, false);
228 fputc_func = M->getOrInsertFunction("fputc",fputc_type);
229 }
230 return fputc_func;
231 }
232
233 /// @brief Return a Function* for the fwrite libcall
Reid Spencer4c444fe2005-04-30 03:17:54 +0000234 Function* get_fwrite(const Type* FILEptr_type)
Reid Spencer93616972005-04-29 09:39:47 +0000235 {
236 if (!fwrite_func)
237 {
238 std::vector<const Type*> args;
239 args.push_back(PointerType::get(Type::SByteTy));
240 args.push_back(TD->getIntPtrType());
241 args.push_back(TD->getIntPtrType());
Reid Spencer4c444fe2005-04-30 03:17:54 +0000242 args.push_back(FILEptr_type);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000243 FunctionType* fwrite_type =
Reid Spencer93616972005-04-29 09:39:47 +0000244 FunctionType::get(TD->getIntPtrType(), args, false);
245 fwrite_func = M->getOrInsertFunction("fwrite",fwrite_type);
246 }
247 return fwrite_func;
248 }
249
250 /// @brief Return a Function* for the sqrt libcall
251 Function* get_sqrt()
252 {
253 if (!sqrt_func)
254 {
255 std::vector<const Type*> args;
256 args.push_back(Type::DoubleTy);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000257 FunctionType* sqrt_type =
Reid Spencer93616972005-04-29 09:39:47 +0000258 FunctionType::get(Type::DoubleTy, args, false);
259 sqrt_func = M->getOrInsertFunction("sqrt",sqrt_type);
260 }
261 return sqrt_func;
262 }
Reid Spencere249a822005-04-27 07:54:40 +0000263
264 /// @brief Return a Function* for the strlen libcall
Reid Spencer1e520fd2005-05-04 03:20:21 +0000265 Function* get_strcpy()
266 {
267 if (!strcpy_func)
268 {
269 std::vector<const Type*> args;
270 args.push_back(PointerType::get(Type::SByteTy));
271 args.push_back(PointerType::get(Type::SByteTy));
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000272 FunctionType* strcpy_type =
Reid Spencer1e520fd2005-05-04 03:20:21 +0000273 FunctionType::get(PointerType::get(Type::SByteTy), args, false);
274 strcpy_func = M->getOrInsertFunction("strcpy",strcpy_type);
275 }
276 return strcpy_func;
277 }
278
279 /// @brief Return a Function* for the strlen libcall
Reid Spencere249a822005-04-27 07:54:40 +0000280 Function* get_strlen()
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000281 {
Reid Spencere249a822005-04-27 07:54:40 +0000282 if (!strlen_func)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000283 {
284 std::vector<const Type*> args;
285 args.push_back(PointerType::get(Type::SByteTy));
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000286 FunctionType* strlen_type =
Reid Spencere249a822005-04-27 07:54:40 +0000287 FunctionType::get(TD->getIntPtrType(), args, false);
288 strlen_func = M->getOrInsertFunction("strlen",strlen_type);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000289 }
Reid Spencere249a822005-04-27 07:54:40 +0000290 return strlen_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000291 }
292
Reid Spencer38cabd72005-05-03 07:23:44 +0000293 /// @brief Return a Function* for the memchr libcall
294 Function* get_memchr()
295 {
296 if (!memchr_func)
297 {
298 std::vector<const Type*> args;
299 args.push_back(PointerType::get(Type::SByteTy));
300 args.push_back(Type::IntTy);
301 args.push_back(TD->getIntPtrType());
302 FunctionType* memchr_type = FunctionType::get(
303 PointerType::get(Type::SByteTy), args, false);
304 memchr_func = M->getOrInsertFunction("memchr",memchr_type);
305 }
306 return memchr_func;
307 }
308
Reid Spencere249a822005-04-27 07:54:40 +0000309 /// @brief Return a Function* for the memcpy libcall
Chris Lattner4201cd12005-08-24 17:22:17 +0000310 Function* get_memcpy() {
311 if (!memcpy_func) {
312 const Type *SBP = PointerType::get(Type::SByteTy);
313 memcpy_func = M->getOrInsertFunction("llvm.memcpy", Type::VoidTy,SBP, SBP,
314 Type::UIntTy, Type::UIntTy, 0);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000315 }
Reid Spencere249a822005-04-27 07:54:40 +0000316 return memcpy_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000317 }
Reid Spencer76dab9a2005-04-26 05:24:00 +0000318
Chris Lattner4201cd12005-08-24 17:22:17 +0000319 Function* get_floorf() {
320 if (!floorf_func)
321 floorf_func = M->getOrInsertFunction("floorf", Type::FloatTy,
322 Type::FloatTy, 0);
323 return floorf_func;
324 }
325
Reid Spencere249a822005-04-27 07:54:40 +0000326private:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000327 /// @brief Reset our cached data for a new Module
Reid Spencere249a822005-04-27 07:54:40 +0000328 void reset(Module& mod)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000329 {
Reid Spencere249a822005-04-27 07:54:40 +0000330 M = &mod;
331 TD = &getAnalysis<TargetData>();
Reid Spencer93616972005-04-29 09:39:47 +0000332 fputc_func = 0;
333 fwrite_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000334 memcpy_func = 0;
Reid Spencer38cabd72005-05-03 07:23:44 +0000335 memchr_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000336 sqrt_func = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +0000337 strcpy_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000338 strlen_func = 0;
Chris Lattner4201cd12005-08-24 17:22:17 +0000339 floorf_func = 0;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000340 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000341
Reid Spencere249a822005-04-27 07:54:40 +0000342private:
Reid Spencer93616972005-04-29 09:39:47 +0000343 Function* fputc_func; ///< Cached fputc function
344 Function* fwrite_func; ///< Cached fwrite function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000345 Function* memcpy_func; ///< Cached llvm.memcpy function
Reid Spencer38cabd72005-05-03 07:23:44 +0000346 Function* memchr_func; ///< Cached memchr function
Reid Spencer93616972005-04-29 09:39:47 +0000347 Function* sqrt_func; ///< Cached sqrt function
Reid Spencer1e520fd2005-05-04 03:20:21 +0000348 Function* strcpy_func; ///< Cached strcpy function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000349 Function* strlen_func; ///< Cached strlen function
Chris Lattner4201cd12005-08-24 17:22:17 +0000350 Function* floorf_func; ///< Cached floorf function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000351 Module* M; ///< Cached Module
352 TargetData* TD; ///< Cached TargetData
Reid Spencere249a822005-04-27 07:54:40 +0000353};
354
355// Register the pass
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000356RegisterOpt<SimplifyLibCalls>
Reid Spencere249a822005-04-27 07:54:40 +0000357X("simplify-libcalls","Simplify well-known library calls");
358
359} // anonymous namespace
360
361// The only public symbol in this file which just instantiates the pass object
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000362ModulePass *llvm::createSimplifyLibCallsPass()
363{
364 return new SimplifyLibCalls();
Reid Spencere249a822005-04-27 07:54:40 +0000365}
366
367// Classes below here, in the anonymous namespace, are all subclasses of the
368// LibCallOptimization class, each implementing all optimizations possible for a
369// single well-known library call. Each has a static singleton instance that
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000370// auto registers it into the "optlist" global above.
Reid Spencere249a822005-04-27 07:54:40 +0000371namespace {
372
Reid Spencera7828ba2005-06-18 17:46:28 +0000373// Forward declare utility functions.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000374bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
Reid Spencera7828ba2005-06-18 17:46:28 +0000375Value *CastToCStr(Value *V, Instruction &IP);
Reid Spencere249a822005-04-27 07:54:40 +0000376
377/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000378/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000379/// the same value passed to the exit function. When this is done, it splits the
380/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000381/// @brief Replace calls to exit in main with a simple return
Reid Spencere249a822005-04-27 07:54:40 +0000382struct ExitInMainOptimization : public LibCallOptimization
Reid Spencer39a762d2005-04-25 02:53:12 +0000383{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000384 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000385 "Number of 'exit' calls simplified") {}
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000386 virtual ~ExitInMainOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000387
388 // Make sure the called function looks like exit (int argument, int return
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000389 // type, external linkage, not varargs).
Reid Spencere249a822005-04-27 07:54:40 +0000390 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000391 {
Reid Spencerb4f7b832005-04-26 07:45:18 +0000392 if (f->arg_size() >= 1)
393 if (f->arg_begin()->getType()->isInteger())
394 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +0000395 return false;
396 }
397
Reid Spencere249a822005-04-27 07:54:40 +0000398 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000399 {
Reid Spencerf2534c72005-04-25 21:11:48 +0000400 // To be careful, we check that the call to exit is coming from "main", that
401 // main has external linkage, and the return type of main and the argument
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000402 // to exit have the same type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000403 Function *from = ci->getParent()->getParent();
404 if (from->hasExternalLinkage())
405 if (from->getReturnType() == ci->getOperand(1)->getType())
406 if (from->getName() == "main")
407 {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000408 // Okay, time to actually do the optimization. First, get the basic
Reid Spencerf2534c72005-04-25 21:11:48 +0000409 // block of the call instruction
410 BasicBlock* bb = ci->getParent();
Reid Spencer39a762d2005-04-25 02:53:12 +0000411
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000412 // Create a return instruction that we'll replace the call with.
413 // Note that the argument of the return is the argument of the call
Reid Spencerf2534c72005-04-25 21:11:48 +0000414 // instruction.
415 ReturnInst* ri = new ReturnInst(ci->getOperand(1), ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000416
Reid Spencerf2534c72005-04-25 21:11:48 +0000417 // Split the block at the call instruction which places it in a new
418 // basic block.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000419 bb->splitBasicBlock(ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000420
Reid Spencerf2534c72005-04-25 21:11:48 +0000421 // The block split caused a branch instruction to be inserted into
422 // the end of the original block, right after the return instruction
423 // that we put there. That's not a valid block, so delete the branch
424 // instruction.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000425 bb->getInstList().pop_back();
Reid Spencer39a762d2005-04-25 02:53:12 +0000426
Reid Spencerf2534c72005-04-25 21:11:48 +0000427 // Now we can finally get rid of the call instruction which now lives
428 // in the new basic block.
429 ci->eraseFromParent();
430
431 // Optimization succeeded, return true.
432 return true;
433 }
434 // We didn't pass the criteria for this optimization so return false
435 return false;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000436 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000437} ExitInMainOptimizer;
438
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000439/// This LibCallOptimization will simplify a call to the strcat library
440/// function. The simplification is possible only if the string being
441/// concatenated is a constant array or a constant expression that results in
442/// a constant string. In this case we can replace it with strlen + llvm.memcpy
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000443/// of the constant string. Both of these calls are further reduced, if possible
444/// on subsequent passes.
Reid Spencerf2534c72005-04-25 21:11:48 +0000445/// @brief Simplify the strcat library function.
Reid Spencere249a822005-04-27 07:54:40 +0000446struct StrCatOptimization : public LibCallOptimization
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000447{
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000448public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000449 /// @brief Default constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +0000450 StrCatOptimization() : LibCallOptimization("strcat",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000451 "Number of 'strcat' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000452
453public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000454 /// @breif Destructor
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000455 virtual ~StrCatOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000456
457 /// @brief Make sure that the "strcat" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000458 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000459 {
460 if (f->getReturnType() == PointerType::get(Type::SByteTy))
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000461 if (f->arg_size() == 2)
Reid Spencerf2534c72005-04-25 21:11:48 +0000462 {
463 Function::const_arg_iterator AI = f->arg_begin();
464 if (AI++->getType() == PointerType::get(Type::SByteTy))
465 if (AI->getType() == PointerType::get(Type::SByteTy))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000466 {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000467 // Indicate this is a suitable call type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000468 return true;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000469 }
Reid Spencerf2534c72005-04-25 21:11:48 +0000470 }
471 return false;
472 }
473
Reid Spencere249a822005-04-27 07:54:40 +0000474 /// @brief Optimize the strcat library function
475 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000476 {
Reid Spencer08b49402005-04-27 17:46:54 +0000477 // Extract some information from the instruction
478 Module* M = ci->getParent()->getParent()->getParent();
479 Value* dest = ci->getOperand(1);
480 Value* src = ci->getOperand(2);
481
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000482 // Extract the initializer (while making numerous checks) from the
Reid Spencer76dab9a2005-04-26 05:24:00 +0000483 // source operand of the call to strcat. If we get null back, one of
484 // a variety of checks in get_GVInitializer failed
Reid Spencerb4f7b832005-04-26 07:45:18 +0000485 uint64_t len = 0;
Reid Spencer08b49402005-04-27 17:46:54 +0000486 if (!getConstantStringLength(src,len))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000487 return false;
488
Reid Spencerb4f7b832005-04-26 07:45:18 +0000489 // Handle the simple, do-nothing case
490 if (len == 0)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000491 {
Reid Spencer08b49402005-04-27 17:46:54 +0000492 ci->replaceAllUsesWith(dest);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000493 ci->eraseFromParent();
494 return true;
495 }
496
Reid Spencerb4f7b832005-04-26 07:45:18 +0000497 // Increment the length because we actually want to memcpy the null
498 // terminator as well.
499 len++;
Reid Spencerf2534c72005-04-25 21:11:48 +0000500
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000501 // We need to find the end of the destination string. That's where the
502 // memory is to be moved to. We just generate a call to strlen (further
503 // optimized in another pass). Note that the SLC.get_strlen() call
Reid Spencerb4f7b832005-04-26 07:45:18 +0000504 // caches the Function* for us.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000505 CallInst* strlen_inst =
Reid Spencer08b49402005-04-27 17:46:54 +0000506 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000507
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000508 // Now that we have the destination's length, we must index into the
Reid Spencerb4f7b832005-04-26 07:45:18 +0000509 // destination's pointer to get the actual memcpy destination (end of
510 // the string .. we're concatenating).
511 std::vector<Value*> idx;
512 idx.push_back(strlen_inst);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000513 GetElementPtrInst* gep =
Reid Spencer08b49402005-04-27 17:46:54 +0000514 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000515
516 // We have enough information to now generate the memcpy call to
517 // do the concatenation for us.
518 std::vector<Value*> vals;
519 vals.push_back(gep); // destination
520 vals.push_back(ci->getOperand(2)); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000521 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
522 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000523 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000524
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000525 // Finally, substitute the first operand of the strcat call for the
526 // strcat call itself since strcat returns its first operand; and,
Reid Spencerb4f7b832005-04-26 07:45:18 +0000527 // kill the strcat CallInst.
Reid Spencer08b49402005-04-27 17:46:54 +0000528 ci->replaceAllUsesWith(dest);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000529 ci->eraseFromParent();
530 return true;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000531 }
532} StrCatOptimizer;
533
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000534/// This LibCallOptimization will simplify a call to the strchr library
Reid Spencer38cabd72005-05-03 07:23:44 +0000535/// function. It optimizes out cases where the arguments are both constant
536/// and the result can be determined statically.
537/// @brief Simplify the strcmp library function.
538struct StrChrOptimization : public LibCallOptimization
539{
540public:
541 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000542 "Number of 'strchr' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +0000543 virtual ~StrChrOptimization() {}
544
545 /// @brief Make sure that the "strchr" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000546 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer38cabd72005-05-03 07:23:44 +0000547 {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000548 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
Reid Spencer38cabd72005-05-03 07:23:44 +0000549 f->arg_size() == 2)
550 return true;
551 return false;
552 }
553
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000554 /// @brief Perform the strchr optimizations
Reid Spencer38cabd72005-05-03 07:23:44 +0000555 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
556 {
557 // If there aren't three operands, bail
558 if (ci->getNumOperands() != 3)
559 return false;
560
561 // Check that the first argument to strchr is a constant array of sbyte.
562 // If it is, get the length and data, otherwise return false.
563 uint64_t len = 0;
564 ConstantArray* CA;
565 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
566 return false;
567
568 // Check that the second argument to strchr is a constant int, return false
569 // if it isn't
570 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
571 if (!CSI)
572 {
573 // Just lower this to memchr since we know the length of the string as
574 // it is constant.
575 Function* f = SLC.get_memchr();
576 std::vector<Value*> args;
577 args.push_back(ci->getOperand(1));
578 args.push_back(ci->getOperand(2));
579 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
580 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
581 ci->eraseFromParent();
582 return true;
583 }
584
585 // Get the character we're looking for
586 int64_t chr = CSI->getValue();
587
588 // Compute the offset
589 uint64_t offset = 0;
590 bool char_found = false;
591 for (uint64_t i = 0; i < len; ++i)
592 {
593 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
594 {
595 // Check for the null terminator
596 if (CI->isNullValue())
597 break; // we found end of string
598 else if (CI->getValue() == chr)
599 {
600 char_found = true;
601 offset = i;
602 break;
603 }
604 }
605 }
606
607 // strchr(s,c) -> offset_of_in(c,s)
608 // (if c is a constant integer and s is a constant string)
609 if (char_found)
610 {
611 std::vector<Value*> indices;
612 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
613 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
614 ci->getOperand(1)->getName()+".strchr",ci);
615 ci->replaceAllUsesWith(GEP);
616 }
617 else
618 ci->replaceAllUsesWith(
619 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
620
621 ci->eraseFromParent();
622 return true;
623 }
624} StrChrOptimizer;
625
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000626/// This LibCallOptimization will simplify a call to the strcmp library
Reid Spencer4c444fe2005-04-30 03:17:54 +0000627/// function. It optimizes out cases where one or both arguments are constant
628/// and the result can be determined statically.
629/// @brief Simplify the strcmp library function.
630struct StrCmpOptimization : public LibCallOptimization
631{
632public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000633 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000634 "Number of 'strcmp' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +0000635 virtual ~StrCmpOptimization() {}
636
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000637 /// @brief Make sure that the "strcmp" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000638 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer4c444fe2005-04-30 03:17:54 +0000639 {
640 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
641 return true;
642 return false;
643 }
644
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000645 /// @brief Perform the strcmp optimization
Reid Spencer4c444fe2005-04-30 03:17:54 +0000646 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
647 {
648 // First, check to see if src and destination are the same. If they are,
Reid Spencer16449a92005-04-30 06:45:47 +0000649 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000650 // because the call is a no-op.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000651 Value* s1 = ci->getOperand(1);
652 Value* s2 = ci->getOperand(2);
653 if (s1 == s2)
654 {
655 // strcmp(x,x) -> 0
656 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
657 ci->eraseFromParent();
658 return true;
659 }
660
661 bool isstr_1 = false;
662 uint64_t len_1 = 0;
663 ConstantArray* A1;
664 if (getConstantStringLength(s1,len_1,&A1))
665 {
666 isstr_1 = true;
667 if (len_1 == 0)
668 {
669 // strcmp("",x) -> *x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000670 LoadInst* load =
Reid Spencera7828ba2005-06-18 17:46:28 +0000671 new LoadInst(CastToCStr(s2,*ci), ci->getName()+".load",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000672 CastInst* cast =
Reid Spencer4c444fe2005-04-30 03:17:54 +0000673 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
674 ci->replaceAllUsesWith(cast);
675 ci->eraseFromParent();
676 return true;
677 }
678 }
679
680 bool isstr_2 = false;
681 uint64_t len_2 = 0;
682 ConstantArray* A2;
683 if (getConstantStringLength(s2,len_2,&A2))
684 {
685 isstr_2 = true;
686 if (len_2 == 0)
687 {
688 // strcmp(x,"") -> *x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000689 LoadInst* load =
Reid Spencera7828ba2005-06-18 17:46:28 +0000690 new LoadInst(CastToCStr(s1,*ci),ci->getName()+".val",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000691 CastInst* cast =
Reid Spencer4c444fe2005-04-30 03:17:54 +0000692 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
693 ci->replaceAllUsesWith(cast);
694 ci->eraseFromParent();
695 return true;
696 }
697 }
698
699 if (isstr_1 && isstr_2)
700 {
701 // strcmp(x,y) -> cnst (if both x and y are constant strings)
702 std::string str1 = A1->getAsString();
703 std::string str2 = A2->getAsString();
704 int result = strcmp(str1.c_str(), str2.c_str());
705 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
706 ci->eraseFromParent();
707 return true;
708 }
709 return false;
710 }
711} StrCmpOptimizer;
712
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000713/// This LibCallOptimization will simplify a call to the strncmp library
Reid Spencer49fa07042005-05-03 01:43:45 +0000714/// function. It optimizes out cases where one or both arguments are constant
715/// and the result can be determined statically.
716/// @brief Simplify the strncmp library function.
717struct StrNCmpOptimization : public LibCallOptimization
718{
719public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000720 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000721 "Number of 'strncmp' calls simplified") {}
Reid Spencer49fa07042005-05-03 01:43:45 +0000722 virtual ~StrNCmpOptimization() {}
723
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000724 /// @brief Make sure that the "strncmp" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000725 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer49fa07042005-05-03 01:43:45 +0000726 {
727 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
728 return true;
729 return false;
730 }
731
732 /// @brief Perform the strncpy optimization
733 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
734 {
735 // First, check to see if src and destination are the same. If they are,
736 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000737 // because the call is a no-op.
Reid Spencer49fa07042005-05-03 01:43:45 +0000738 Value* s1 = ci->getOperand(1);
739 Value* s2 = ci->getOperand(2);
740 if (s1 == s2)
741 {
742 // strncmp(x,x,l) -> 0
743 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
744 ci->eraseFromParent();
745 return true;
746 }
747
748 // Check the length argument, if it is Constant zero then the strings are
749 // considered equal.
750 uint64_t len_arg = 0;
751 bool len_arg_is_const = false;
752 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
753 {
754 len_arg_is_const = true;
755 len_arg = len_CI->getRawValue();
756 if (len_arg == 0)
757 {
758 // strncmp(x,y,0) -> 0
759 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
760 ci->eraseFromParent();
761 return true;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000762 }
Reid Spencer49fa07042005-05-03 01:43:45 +0000763 }
764
765 bool isstr_1 = false;
766 uint64_t len_1 = 0;
767 ConstantArray* A1;
768 if (getConstantStringLength(s1,len_1,&A1))
769 {
770 isstr_1 = true;
771 if (len_1 == 0)
772 {
773 // strncmp("",x) -> *x
774 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000775 CastInst* cast =
Reid Spencer49fa07042005-05-03 01:43:45 +0000776 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
777 ci->replaceAllUsesWith(cast);
778 ci->eraseFromParent();
779 return true;
780 }
781 }
782
783 bool isstr_2 = false;
784 uint64_t len_2 = 0;
785 ConstantArray* A2;
786 if (getConstantStringLength(s2,len_2,&A2))
787 {
788 isstr_2 = true;
789 if (len_2 == 0)
790 {
791 // strncmp(x,"") -> *x
792 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000793 CastInst* cast =
Reid Spencer49fa07042005-05-03 01:43:45 +0000794 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
795 ci->replaceAllUsesWith(cast);
796 ci->eraseFromParent();
797 return true;
798 }
799 }
800
801 if (isstr_1 && isstr_2 && len_arg_is_const)
802 {
803 // strncmp(x,y,const) -> constant
804 std::string str1 = A1->getAsString();
805 std::string str2 = A2->getAsString();
806 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
807 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
808 ci->eraseFromParent();
809 return true;
810 }
811 return false;
812 }
813} StrNCmpOptimizer;
814
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000815/// This LibCallOptimization will simplify a call to the strcpy library
816/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000817/// (1) If src and dest are the same and not volatile, just return dest
818/// (2) If the src is a constant then we can convert to llvm.memmove
819/// @brief Simplify the strcpy library function.
820struct StrCpyOptimization : public LibCallOptimization
821{
822public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000823 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000824 "Number of 'strcpy' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000825 virtual ~StrCpyOptimization() {}
826
827 /// @brief Make sure that the "strcpy" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000828 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencere249a822005-04-27 07:54:40 +0000829 {
830 if (f->getReturnType() == PointerType::get(Type::SByteTy))
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000831 if (f->arg_size() == 2)
Reid Spencere249a822005-04-27 07:54:40 +0000832 {
833 Function::const_arg_iterator AI = f->arg_begin();
834 if (AI++->getType() == PointerType::get(Type::SByteTy))
835 if (AI->getType() == PointerType::get(Type::SByteTy))
836 {
837 // Indicate this is a suitable call type.
838 return true;
839 }
840 }
841 return false;
842 }
843
844 /// @brief Perform the strcpy optimization
845 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
846 {
847 // First, check to see if src and destination are the same. If they are,
848 // then the optimization is to replace the CallInst with the destination
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000849 // because the call is a no-op. Note that this corresponds to the
Reid Spencere249a822005-04-27 07:54:40 +0000850 // degenerate strcpy(X,X) case which should have "undefined" results
851 // according to the C specification. However, it occurs sometimes and
852 // we optimize it as a no-op.
853 Value* dest = ci->getOperand(1);
854 Value* src = ci->getOperand(2);
855 if (dest == src)
856 {
857 ci->replaceAllUsesWith(dest);
858 ci->eraseFromParent();
859 return true;
860 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000861
Reid Spencere249a822005-04-27 07:54:40 +0000862 // Get the length of the constant string referenced by the second operand,
863 // the "src" parameter. Fail the optimization if we can't get the length
864 // (note that getConstantStringLength does lots of checks to make sure this
865 // is valid).
866 uint64_t len = 0;
867 if (!getConstantStringLength(ci->getOperand(2),len))
868 return false;
869
870 // If the constant string's length is zero we can optimize this by just
871 // doing a store of 0 at the first byte of the destination
872 if (len == 0)
873 {
874 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
875 ci->replaceAllUsesWith(dest);
876 ci->eraseFromParent();
877 return true;
878 }
879
880 // Increment the length because we actually want to memcpy the null
881 // terminator as well.
882 len++;
883
884 // Extract some information from the instruction
885 Module* M = ci->getParent()->getParent()->getParent();
886
887 // We have enough information to now generate the memcpy call to
888 // do the concatenation for us.
889 std::vector<Value*> vals;
890 vals.push_back(dest); // destination
891 vals.push_back(src); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000892 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
893 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000894 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencere249a822005-04-27 07:54:40 +0000895
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000896 // Finally, substitute the first operand of the strcat call for the
897 // strcat call itself since strcat returns its first operand; and,
Reid Spencere249a822005-04-27 07:54:40 +0000898 // kill the strcat CallInst.
899 ci->replaceAllUsesWith(dest);
900 ci->eraseFromParent();
901 return true;
902 }
903} StrCpyOptimizer;
904
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000905/// This LibCallOptimization will simplify a call to the strlen library
906/// function by replacing it with a constant value if the string provided to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000907/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000908/// @brief Simplify the strlen library function.
Reid Spencere249a822005-04-27 07:54:40 +0000909struct StrLenOptimization : public LibCallOptimization
Reid Spencer76dab9a2005-04-26 05:24:00 +0000910{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000911 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000912 "Number of 'strlen' calls simplified") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000913 virtual ~StrLenOptimization() {}
914
915 /// @brief Make sure that the "strlen" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000916 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000917 {
Reid Spencere249a822005-04-27 07:54:40 +0000918 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000919 if (f->arg_size() == 1)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000920 if (Function::const_arg_iterator AI = f->arg_begin())
921 if (AI->getType() == PointerType::get(Type::SByteTy))
922 return true;
923 return false;
924 }
925
926 /// @brief Perform the strlen optimization
Reid Spencere249a822005-04-27 07:54:40 +0000927 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000928 {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000929 // Make sure we're dealing with an sbyte* here.
930 Value* str = ci->getOperand(1);
931 if (str->getType() != PointerType::get(Type::SByteTy))
932 return false;
933
934 // Does the call to strlen have exactly one use?
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000935 if (ci->hasOneUse())
Reid Spencer170ae7f2005-05-07 20:15:59 +0000936 // Is that single use a binary operator?
937 if (BinaryOperator* bop = dyn_cast<BinaryOperator>(ci->use_back()))
938 // Is it compared against a constant integer?
939 if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
940 {
941 // Get the value the strlen result is compared to
942 uint64_t val = CI->getRawValue();
943
944 // If its compared against length 0 with == or !=
945 if (val == 0 &&
946 (bop->getOpcode() == Instruction::SetEQ ||
947 bop->getOpcode() == Instruction::SetNE))
948 {
949 // strlen(x) != 0 -> *x != 0
950 // strlen(x) == 0 -> *x == 0
951 LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
952 BinaryOperator* rbop = BinaryOperator::create(bop->getOpcode(),
953 load, ConstantSInt::get(Type::SByteTy,0),
954 bop->getName()+".strlen", ci);
955 bop->replaceAllUsesWith(rbop);
956 bop->eraseFromParent();
957 ci->eraseFromParent();
958 return true;
959 }
960 }
961
962 // Get the length of the constant string operand
Reid Spencerb4f7b832005-04-26 07:45:18 +0000963 uint64_t len = 0;
964 if (!getConstantStringLength(ci->getOperand(1),len))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000965 return false;
966
Reid Spencer170ae7f2005-05-07 20:15:59 +0000967 // strlen("xyz") -> 3 (for example)
Chris Lattnere17c5d02005-08-01 16:52:50 +0000968 const Type *Ty = SLC.getTargetData()->getIntPtrType();
969 if (Ty->isSigned())
970 ci->replaceAllUsesWith(ConstantSInt::get(Ty, len));
971 else
972 ci->replaceAllUsesWith(ConstantUInt::get(Ty, len));
973
Reid Spencerb4f7b832005-04-26 07:45:18 +0000974 ci->eraseFromParent();
975 return true;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000976 }
977} StrLenOptimizer;
978
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000979/// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
980/// is equal or not-equal to zero.
981static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
982 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
983 UI != E; ++UI) {
984 Instruction *User = cast<Instruction>(*UI);
985 if (User->getOpcode() == Instruction::SetNE ||
986 User->getOpcode() == Instruction::SetEQ) {
987 if (isa<Constant>(User->getOperand(1)) &&
988 cast<Constant>(User->getOperand(1))->isNullValue())
989 continue;
990 } else if (CastInst *CI = dyn_cast<CastInst>(User))
991 if (CI->getType() == Type::BoolTy)
992 continue;
993 // Unknown instruction.
994 return false;
995 }
996 return true;
997}
998
999/// This memcmpOptimization will simplify a call to the memcmp library
1000/// function.
1001struct memcmpOptimization : public LibCallOptimization {
1002 /// @brief Default Constructor
1003 memcmpOptimization()
1004 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
1005
1006 /// @brief Make sure that the "memcmp" function has the right prototype
1007 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
1008 Function::const_arg_iterator AI = F->arg_begin();
1009 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
1010 if (!isa<PointerType>((++AI)->getType())) return false;
1011 if (!(++AI)->getType()->isInteger()) return false;
1012 if (!F->getReturnType()->isInteger()) return false;
1013 return true;
1014 }
1015
1016 /// Because of alignment and instruction information that we don't have, we
1017 /// leave the bulk of this to the code generators.
1018 ///
1019 /// Note that we could do much more if we could force alignment on otherwise
1020 /// small aligned allocas, or if we could indicate that loads have a small
1021 /// alignment.
1022 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
1023 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
1024
1025 // If the two operands are the same, return zero.
1026 if (LHS == RHS) {
1027 // memcmp(s,s,x) -> 0
1028 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1029 CI->eraseFromParent();
1030 return true;
1031 }
1032
1033 // Make sure we have a constant length.
1034 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1035 if (!LenC) return false;
1036 uint64_t Len = LenC->getRawValue();
1037
1038 // If the length is zero, this returns 0.
1039 switch (Len) {
1040 case 0:
1041 // memcmp(s1,s2,0) -> 0
1042 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1043 CI->eraseFromParent();
1044 return true;
1045 case 1: {
1046 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
1047 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1048 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1049 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1050 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
1051 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
1052 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
1053 if (RV->getType() != CI->getType())
1054 RV = new CastInst(RV, CI->getType(), RV->getName(), CI);
1055 CI->replaceAllUsesWith(RV);
1056 CI->eraseFromParent();
1057 return true;
1058 }
1059 case 2:
1060 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
1061 // TODO: IF both are aligned, use a short load/compare.
1062
1063 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
1064 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1065 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1066 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1067 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
1068 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
1069 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
1070 CI->getName()+".d1", CI);
1071 Constant *One = ConstantInt::get(Type::IntTy, 1);
1072 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
1073 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
1074 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
1075 Value *S2V2 = new LoadInst(G1, RHS->getName()+".val2", CI);
1076 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
1077 CI->getName()+".d1", CI);
1078 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
1079 if (Or->getType() != CI->getType())
1080 Or = new CastInst(Or, CI->getType(), Or->getName(), CI);
1081 CI->replaceAllUsesWith(Or);
1082 CI->eraseFromParent();
1083 return true;
1084 }
1085 break;
1086 default:
1087 break;
1088 }
1089
1090
1091
1092 return false;
1093 }
1094} memcmpOptimizer;
1095
1096
1097
1098
1099
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001100/// This LibCallOptimization will simplify a call to the memcpy library
1101/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001102/// bytes depending on the length of the string and the alignment. Additional
1103/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +00001104/// @brief Simplify the memcpy library function.
Reid Spencer38cabd72005-05-03 07:23:44 +00001105struct LLVMMemCpyOptimization : public LibCallOptimization
Reid Spencerf2534c72005-04-25 21:11:48 +00001106{
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001107 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +00001108 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
Reid Spencer95d8efd2005-05-03 02:54:54 +00001109 "Number of 'llvm.memcpy' calls simplified") {}
1110
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001111protected:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001112 /// @brief Subclass Constructor
Reid Spencer170ae7f2005-05-07 20:15:59 +00001113 LLVMMemCpyOptimization(const char* fname, const char* desc)
1114 : LibCallOptimization(fname, desc) {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001115public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001116 /// @brief Destructor
Reid Spencer38cabd72005-05-03 07:23:44 +00001117 virtual ~LLVMMemCpyOptimization() {}
Reid Spencerf2534c72005-04-25 21:11:48 +00001118
1119 /// @brief Make sure that the "memcpy" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +00001120 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +00001121 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001122 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +00001123 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +00001124 }
1125
Reid Spencerb4f7b832005-04-26 07:45:18 +00001126 /// Because of alignment and instruction information that we don't have, we
1127 /// leave the bulk of this to the code generators. The optimization here just
1128 /// deals with a few degenerate cases where the length of the string and the
1129 /// alignment match the sizes of our intrinsic types so we can do a load and
1130 /// store instead of the memcpy call.
1131 /// @brief Perform the memcpy optimization.
Reid Spencere249a822005-04-27 07:54:40 +00001132 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +00001133 {
Reid Spencer4855ebf2005-04-26 19:55:57 +00001134 // Make sure we have constant int values to work with
1135 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1136 if (!LEN)
1137 return false;
1138 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1139 if (!ALIGN)
1140 return false;
1141
1142 // If the length is larger than the alignment, we can't optimize
1143 uint64_t len = LEN->getRawValue();
1144 uint64_t alignment = ALIGN->getRawValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001145 if (alignment == 0)
1146 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001147 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +00001148 return false;
1149
Reid Spencer08b49402005-04-27 17:46:54 +00001150 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +00001151 Value* dest = ci->getOperand(1);
1152 Value* src = ci->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +00001153 Type* castType = 0;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001154 switch (len)
1155 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001156 case 0:
Reid Spencer93616972005-04-29 09:39:47 +00001157 // memcpy(d,s,0,a) -> noop
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001158 ci->eraseFromParent();
1159 return true;
Reid Spencer08b49402005-04-27 17:46:54 +00001160 case 1: castType = Type::SByteTy; break;
1161 case 2: castType = Type::ShortTy; break;
1162 case 4: castType = Type::IntTy; break;
1163 case 8: castType = Type::LongTy; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001164 default:
1165 return false;
1166 }
Reid Spencer08b49402005-04-27 17:46:54 +00001167
1168 // Cast source and dest to the right sized primitive and then load/store
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001169 CastInst* SrcCast =
Reid Spencer08b49402005-04-27 17:46:54 +00001170 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001171 CastInst* DestCast =
Reid Spencer08b49402005-04-27 17:46:54 +00001172 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1173 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001174 StoreInst* SI = new StoreInst(LI, DestCast, ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001175 ci->eraseFromParent();
1176 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +00001177 }
Reid Spencer38cabd72005-05-03 07:23:44 +00001178} LLVMMemCpyOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001179
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001180/// This LibCallOptimization will simplify a call to the memmove library
1181/// function. It is identical to MemCopyOptimization except for the name of
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001182/// the intrinsic.
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001183/// @brief Simplify the memmove library function.
Reid Spencer38cabd72005-05-03 07:23:44 +00001184struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001185{
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001186 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +00001187 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
Reid Spencer95d8efd2005-05-03 02:54:54 +00001188 "Number of 'llvm.memmove' calls simplified") {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001189
Reid Spencer38cabd72005-05-03 07:23:44 +00001190} LLVMMemMoveOptimizer;
1191
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001192/// This LibCallOptimization will simplify a call to the memset library
1193/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1194/// bytes depending on the length argument.
Reid Spencer38cabd72005-05-03 07:23:44 +00001195struct LLVMMemSetOptimization : public LibCallOptimization
1196{
1197 /// @brief Default Constructor
1198 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
Reid Spencer38cabd72005-05-03 07:23:44 +00001199 "Number of 'llvm.memset' calls simplified") {}
1200
1201public:
1202 /// @brief Destructor
1203 virtual ~LLVMMemSetOptimization() {}
1204
1205 /// @brief Make sure that the "memset" function has the right prototype
1206 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1207 {
1208 // Just make sure this has 3 arguments per LLVM spec.
1209 return (f->arg_size() == 4);
1210 }
1211
1212 /// Because of alignment and instruction information that we don't have, we
1213 /// leave the bulk of this to the code generators. The optimization here just
1214 /// deals with a few degenerate cases where the length parameter is constant
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001215 /// and the alignment matches the sizes of our intrinsic types so we can do
Reid Spencer38cabd72005-05-03 07:23:44 +00001216 /// store instead of the memcpy call. Other calls are transformed into the
1217 /// llvm.memset intrinsic.
1218 /// @brief Perform the memset optimization.
1219 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1220 {
1221 // Make sure we have constant int values to work with
1222 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1223 if (!LEN)
1224 return false;
1225 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1226 if (!ALIGN)
1227 return false;
1228
1229 // Extract the length and alignment
1230 uint64_t len = LEN->getRawValue();
1231 uint64_t alignment = ALIGN->getRawValue();
1232
1233 // Alignment 0 is identity for alignment 1
1234 if (alignment == 0)
1235 alignment = 1;
1236
1237 // If the length is zero, this is a no-op
1238 if (len == 0)
1239 {
1240 // memset(d,c,0,a) -> noop
1241 ci->eraseFromParent();
1242 return true;
1243 }
1244
1245 // If the length is larger than the alignment, we can't optimize
1246 if (len > alignment)
1247 return false;
1248
1249 // Make sure we have a constant ubyte to work with so we can extract
1250 // the value to be filled.
1251 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1252 if (!FILL)
1253 return false;
1254 if (FILL->getType() != Type::UByteTy)
1255 return false;
1256
1257 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001258
Reid Spencer38cabd72005-05-03 07:23:44 +00001259 // Extract the fill character
1260 uint64_t fill_char = FILL->getValue();
1261 uint64_t fill_value = fill_char;
1262
1263 // Get the type we will cast to, based on size of memory area to fill, and
1264 // and the value we will store there.
1265 Value* dest = ci->getOperand(1);
1266 Type* castType = 0;
1267 switch (len)
1268 {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001269 case 1:
1270 castType = Type::UByteTy;
Reid Spencer38cabd72005-05-03 07:23:44 +00001271 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001272 case 2:
1273 castType = Type::UShortTy;
Reid Spencer38cabd72005-05-03 07:23:44 +00001274 fill_value |= fill_char << 8;
1275 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001276 case 4:
Reid Spencer38cabd72005-05-03 07:23:44 +00001277 castType = Type::UIntTy;
1278 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1279 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001280 case 8:
Reid Spencer38cabd72005-05-03 07:23:44 +00001281 castType = Type::ULongTy;
1282 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1283 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1284 fill_value |= fill_char << 56;
1285 break;
1286 default:
1287 return false;
1288 }
1289
1290 // Cast dest to the right sized primitive and then load/store
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001291 CastInst* DestCast =
Reid Spencer38cabd72005-05-03 07:23:44 +00001292 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1293 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1294 ci->eraseFromParent();
1295 return true;
1296 }
1297} LLVMMemSetOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001298
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001299/// This LibCallOptimization will simplify calls to the "pow" library
1300/// function. It looks for cases where the result of pow is well known and
Reid Spencer93616972005-04-29 09:39:47 +00001301/// substitutes the appropriate value.
1302/// @brief Simplify the pow library function.
1303struct PowOptimization : public LibCallOptimization
1304{
1305public:
1306 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001307 PowOptimization() : LibCallOptimization("pow",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001308 "Number of 'pow' calls simplified") {}
Reid Spencer95d8efd2005-05-03 02:54:54 +00001309
Reid Spencer93616972005-04-29 09:39:47 +00001310 /// @brief Destructor
1311 virtual ~PowOptimization() {}
1312
1313 /// @brief Make sure that the "pow" function has the right prototype
1314 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1315 {
1316 // Just make sure this has 2 arguments
1317 return (f->arg_size() == 2);
1318 }
1319
1320 /// @brief Perform the pow optimization.
1321 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1322 {
1323 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1324 Value* base = ci->getOperand(1);
1325 Value* expn = ci->getOperand(2);
1326 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1327 double Op1V = Op1->getValue();
1328 if (Op1V == 1.0)
1329 {
1330 // pow(1.0,x) -> 1.0
1331 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1332 ci->eraseFromParent();
1333 return true;
1334 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001335 }
1336 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
Reid Spencer93616972005-04-29 09:39:47 +00001337 {
1338 double Op2V = Op2->getValue();
1339 if (Op2V == 0.0)
1340 {
1341 // pow(x,0.0) -> 1.0
1342 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1343 ci->eraseFromParent();
1344 return true;
1345 }
1346 else if (Op2V == 0.5)
1347 {
1348 // pow(x,0.5) -> sqrt(x)
1349 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1350 ci->getName()+".pow",ci);
1351 ci->replaceAllUsesWith(sqrt_inst);
1352 ci->eraseFromParent();
1353 return true;
1354 }
1355 else if (Op2V == 1.0)
1356 {
1357 // pow(x,1.0) -> x
1358 ci->replaceAllUsesWith(base);
1359 ci->eraseFromParent();
1360 return true;
1361 }
1362 else if (Op2V == -1.0)
1363 {
1364 // pow(x,-1.0) -> 1.0/x
Chris Lattner4201cd12005-08-24 17:22:17 +00001365 BinaryOperator* div_inst= BinaryOperator::createDiv(
Reid Spencer93616972005-04-29 09:39:47 +00001366 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1367 ci->replaceAllUsesWith(div_inst);
1368 ci->eraseFromParent();
1369 return true;
1370 }
1371 }
1372 return false; // opt failed
1373 }
1374} PowOptimizer;
1375
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001376/// This LibCallOptimization will simplify calls to the "fprintf" library
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001377/// function. It looks for cases where the result of fprintf is not used and the
1378/// operation can be reduced to something simpler.
1379/// @brief Simplify the pow library function.
1380struct FPrintFOptimization : public LibCallOptimization
1381{
1382public:
1383 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001384 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001385 "Number of 'fprintf' calls simplified") {}
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001386
1387 /// @brief Destructor
1388 virtual ~FPrintFOptimization() {}
1389
1390 /// @brief Make sure that the "fprintf" function has the right prototype
1391 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1392 {
1393 // Just make sure this has at least 2 arguments
1394 return (f->arg_size() >= 2);
1395 }
1396
1397 /// @brief Perform the fprintf optimization.
1398 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1399 {
1400 // If the call has more than 3 operands, we can't optimize it
1401 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1402 return false;
1403
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001404 // If the result of the fprintf call is used, none of these optimizations
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001405 // can be made.
Chris Lattner175463a2005-09-24 22:17:06 +00001406 if (!ci->use_empty())
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001407 return false;
1408
1409 // All the optimizations depend on the length of the second argument and the
1410 // fact that it is a constant string array. Check that now
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001411 uint64_t len = 0;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001412 ConstantArray* CA = 0;
1413 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1414 return false;
1415
1416 if (ci->getNumOperands() == 3)
1417 {
1418 // Make sure there's no % in the constant array
1419 for (unsigned i = 0; i < len; ++i)
1420 {
1421 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1422 {
1423 // Check for the null terminator
1424 if (CI->getRawValue() == '%')
1425 return false; // we found end of string
1426 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001427 else
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001428 return false;
1429 }
1430
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001431 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001432 const Type* FILEptr_type = ci->getOperand(1)->getType();
1433 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1434 if (!fwrite_func)
1435 return false;
John Criswell4642afd2005-06-29 15:03:18 +00001436
1437 // Make sure that the fprintf() and fwrite() functions both take the
1438 // same type of char pointer.
1439 if (ci->getOperand(2)->getType() !=
1440 fwrite_func->getFunctionType()->getParamType(0))
John Criswell4642afd2005-06-29 15:03:18 +00001441 return false;
John Criswell4642afd2005-06-29 15:03:18 +00001442
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001443 std::vector<Value*> args;
1444 args.push_back(ci->getOperand(2));
1445 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1446 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1447 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001448 new CallInst(fwrite_func,args,ci->getName(),ci);
1449 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001450 ci->eraseFromParent();
1451 return true;
1452 }
1453
1454 // The remaining optimizations require the format string to be length 2
1455 // "%s" or "%c".
1456 if (len != 2)
1457 return false;
1458
1459 // The first character has to be a %
1460 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1461 if (CI->getRawValue() != '%')
1462 return false;
1463
1464 // Get the second character and switch on its value
1465 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1466 switch (CI->getRawValue())
1467 {
1468 case 's':
1469 {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001470 uint64_t len = 0;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001471 ConstantArray* CA = 0;
1472 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1473 return false;
1474
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001475 // fprintf(file,"%s",str) -> fwrite(fmt,strlen(fmt),1,file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001476 const Type* FILEptr_type = ci->getOperand(1)->getType();
1477 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1478 if (!fwrite_func)
1479 return false;
1480 std::vector<Value*> args;
Reid Spencer45bb4af2005-05-21 00:39:30 +00001481 args.push_back(CastToCStr(ci->getOperand(3), *ci));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001482 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1483 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1484 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001485 new CallInst(fwrite_func,args,ci->getName(),ci);
1486 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001487 break;
1488 }
1489 case 'c':
1490 {
1491 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1492 if (!CI)
1493 return false;
1494
1495 const Type* FILEptr_type = ci->getOperand(1)->getType();
1496 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1497 if (!fputc_func)
1498 return false;
1499 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1500 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
Reid Spencer1e520fd2005-05-04 03:20:21 +00001501 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001502 break;
1503 }
1504 default:
1505 return false;
1506 }
1507 ci->eraseFromParent();
1508 return true;
1509 }
1510} FPrintFOptimizer;
1511
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001512/// This LibCallOptimization will simplify calls to the "sprintf" library
Reid Spencer1e520fd2005-05-04 03:20:21 +00001513/// function. It looks for cases where the result of sprintf is not used and the
1514/// operation can be reduced to something simpler.
1515/// @brief Simplify the pow library function.
1516struct SPrintFOptimization : public LibCallOptimization
1517{
1518public:
1519 /// @brief Default Constructor
1520 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001521 "Number of 'sprintf' calls simplified") {}
Reid Spencer1e520fd2005-05-04 03:20:21 +00001522
1523 /// @brief Destructor
1524 virtual ~SPrintFOptimization() {}
1525
1526 /// @brief Make sure that the "fprintf" function has the right prototype
1527 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1528 {
1529 // Just make sure this has at least 2 arguments
1530 return (f->getReturnType() == Type::IntTy && f->arg_size() >= 2);
1531 }
1532
1533 /// @brief Perform the sprintf optimization.
1534 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1535 {
1536 // If the call has more than 3 operands, we can't optimize it
1537 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1538 return false;
1539
1540 // All the optimizations depend on the length of the second argument and the
1541 // fact that it is a constant string array. Check that now
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001542 uint64_t len = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001543 ConstantArray* CA = 0;
1544 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1545 return false;
1546
1547 if (ci->getNumOperands() == 3)
1548 {
1549 if (len == 0)
1550 {
1551 // If the length is 0, we just need to store a null byte
1552 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
1553 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1554 ci->eraseFromParent();
1555 return true;
1556 }
1557
1558 // Make sure there's no % in the constant array
1559 for (unsigned i = 0; i < len; ++i)
1560 {
1561 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1562 {
1563 // Check for the null terminator
1564 if (CI->getRawValue() == '%')
1565 return false; // we found a %, can't optimize
1566 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001567 else
Reid Spencer1e520fd2005-05-04 03:20:21 +00001568 return false; // initializer is not constant int, can't optimize
1569 }
1570
1571 // Increment length because we want to copy the null byte too
1572 len++;
1573
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001574 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
Reid Spencer1e520fd2005-05-04 03:20:21 +00001575 Function* memcpy_func = SLC.get_memcpy();
1576 if (!memcpy_func)
1577 return false;
1578 std::vector<Value*> args;
1579 args.push_back(ci->getOperand(1));
1580 args.push_back(ci->getOperand(2));
1581 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1582 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1583 new CallInst(memcpy_func,args,"",ci);
1584 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1585 ci->eraseFromParent();
1586 return true;
1587 }
1588
1589 // The remaining optimizations require the format string to be length 2
1590 // "%s" or "%c".
1591 if (len != 2)
1592 return false;
1593
1594 // The first character has to be a %
1595 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1596 if (CI->getRawValue() != '%')
1597 return false;
1598
1599 // Get the second character and switch on its value
1600 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
Chris Lattner175463a2005-09-24 22:17:06 +00001601 switch (CI->getRawValue()) {
1602 case 's': {
1603 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1604 Function* strlen_func = SLC.get_strlen();
1605 Function* memcpy_func = SLC.get_memcpy();
1606 if (!strlen_func || !memcpy_func)
Reid Spencer1e520fd2005-05-04 03:20:21 +00001607 return false;
Chris Lattner175463a2005-09-24 22:17:06 +00001608
1609 Value *Len = new CallInst(strlen_func, CastToCStr(ci->getOperand(3), *ci),
1610 ci->getOperand(3)->getName()+".len", ci);
1611 Value *Len1 = BinaryOperator::createAdd(Len,
1612 ConstantInt::get(Len->getType(), 1),
1613 Len->getName()+"1", ci);
1614 if (Len1->getType() != Type::UIntTy)
1615 Len1 = new CastInst(Len1, Type::UIntTy, Len1->getName(), ci);
1616 std::vector<Value*> args;
1617 args.push_back(CastToCStr(ci->getOperand(1), *ci));
1618 args.push_back(CastToCStr(ci->getOperand(3), *ci));
1619 args.push_back(Len1);
1620 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1621 new CallInst(memcpy_func, args, "", ci);
1622
1623 // The strlen result is the unincremented number of bytes in the string.
Chris Lattnerf4877682005-09-25 07:06:48 +00001624 if (!ci->use_empty()) {
1625 if (Len->getType() != ci->getType())
1626 Len = new CastInst(Len, ci->getType(), Len->getName(), ci);
1627 ci->replaceAllUsesWith(Len);
1628 }
Chris Lattner175463a2005-09-24 22:17:06 +00001629 ci->eraseFromParent();
1630 return true;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001631 }
Chris Lattner175463a2005-09-24 22:17:06 +00001632 case 'c': {
1633 // sprintf(dest,"%c",chr) -> store chr, dest
1634 CastInst* cast = new CastInst(ci->getOperand(3),Type::SByteTy,"char",ci);
1635 new StoreInst(cast, ci->getOperand(1), ci);
1636 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1637 ConstantUInt::get(Type::UIntTy,1),ci->getOperand(1)->getName()+".end",
1638 ci);
1639 new StoreInst(ConstantInt::get(Type::SByteTy,0),gep,ci);
1640 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1641 ci->eraseFromParent();
1642 return true;
1643 }
1644 }
1645 return false;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001646 }
1647} SPrintFOptimizer;
1648
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001649/// This LibCallOptimization will simplify calls to the "fputs" library
Reid Spencer93616972005-04-29 09:39:47 +00001650/// function. It looks for cases where the result of fputs is not used and the
1651/// operation can be reduced to something simpler.
1652/// @brief Simplify the pow library function.
1653struct PutsOptimization : public LibCallOptimization
1654{
1655public:
1656 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001657 PutsOptimization() : LibCallOptimization("fputs",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001658 "Number of 'fputs' calls simplified") {}
Reid Spencer93616972005-04-29 09:39:47 +00001659
1660 /// @brief Destructor
1661 virtual ~PutsOptimization() {}
1662
1663 /// @brief Make sure that the "fputs" function has the right prototype
1664 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1665 {
1666 // Just make sure this has 2 arguments
1667 return (f->arg_size() == 2);
1668 }
1669
1670 /// @brief Perform the fputs optimization.
1671 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1672 {
1673 // If the result is used, none of these optimizations work
Chris Lattner175463a2005-09-24 22:17:06 +00001674 if (!ci->use_empty())
Reid Spencer93616972005-04-29 09:39:47 +00001675 return false;
1676
1677 // All the optimizations depend on the length of the first argument and the
1678 // fact that it is a constant string array. Check that now
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001679 uint64_t len = 0;
Reid Spencer93616972005-04-29 09:39:47 +00001680 if (!getConstantStringLength(ci->getOperand(1), len))
1681 return false;
1682
1683 switch (len)
1684 {
1685 case 0:
1686 // fputs("",F) -> noop
1687 break;
1688 case 1:
1689 {
1690 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001691 const Type* FILEptr_type = ci->getOperand(2)->getType();
1692 Function* fputc_func = SLC.get_fputc(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001693 if (!fputc_func)
1694 return false;
1695 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1696 ci->getOperand(1)->getName()+".byte",ci);
1697 CastInst* casti = new CastInst(loadi,Type::IntTy,
1698 loadi->getName()+".int",ci);
1699 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1700 break;
1701 }
1702 default:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001703 {
Reid Spencer93616972005-04-29 09:39:47 +00001704 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001705 const Type* FILEptr_type = ci->getOperand(2)->getType();
1706 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001707 if (!fwrite_func)
1708 return false;
1709 std::vector<Value*> parms;
1710 parms.push_back(ci->getOperand(1));
1711 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1712 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1713 parms.push_back(ci->getOperand(2));
1714 new CallInst(fwrite_func,parms,"",ci);
1715 break;
1716 }
1717 }
1718 ci->eraseFromParent();
1719 return true; // success
1720 }
1721} PutsOptimizer;
1722
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001723/// This LibCallOptimization will simplify calls to the "isdigit" library
Reid Spencer282d0572005-05-04 18:58:28 +00001724/// function. It simply does range checks the parameter explicitly.
1725/// @brief Simplify the isdigit library function.
1726struct IsDigitOptimization : public LibCallOptimization
1727{
1728public:
1729 /// @brief Default Constructor
1730 IsDigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001731 "Number of 'isdigit' calls simplified") {}
Reid Spencer282d0572005-05-04 18:58:28 +00001732
1733 /// @brief Destructor
1734 virtual ~IsDigitOptimization() {}
1735
1736 /// @brief Make sure that the "fputs" function has the right prototype
1737 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1738 {
1739 // Just make sure this has 1 argument
1740 return (f->arg_size() == 1);
1741 }
1742
1743 /// @brief Perform the toascii optimization.
1744 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1745 {
1746 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1747 {
1748 // isdigit(c) -> 0 or 1, if 'c' is constant
1749 uint64_t val = CI->getRawValue();
1750 if (val >= '0' && val <='9')
1751 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1752 else
1753 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1754 ci->eraseFromParent();
1755 return true;
1756 }
1757
1758 // isdigit(c) -> (unsigned)c - '0' <= 9
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001759 CastInst* cast =
Reid Spencer282d0572005-05-04 18:58:28 +00001760 new CastInst(ci->getOperand(1),Type::UIntTy,
1761 ci->getOperand(1)->getName()+".uint",ci);
Chris Lattner4201cd12005-08-24 17:22:17 +00001762 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
Reid Spencer282d0572005-05-04 18:58:28 +00001763 ConstantUInt::get(Type::UIntTy,0x30),
1764 ci->getOperand(1)->getName()+".sub",ci);
1765 SetCondInst* setcond_inst = new SetCondInst(Instruction::SetLE,sub_inst,
1766 ConstantUInt::get(Type::UIntTy,9),
1767 ci->getOperand(1)->getName()+".cmp",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001768 CastInst* c2 =
Reid Spencer282d0572005-05-04 18:58:28 +00001769 new CastInst(setcond_inst,Type::IntTy,
1770 ci->getOperand(1)->getName()+".isdigit",ci);
1771 ci->replaceAllUsesWith(c2);
1772 ci->eraseFromParent();
1773 return true;
1774 }
1775} IsDigitOptimizer;
1776
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001777/// This LibCallOptimization will simplify calls to the "toascii" library
Reid Spencer4c444fe2005-04-30 03:17:54 +00001778/// function. It simply does the corresponding and operation to restrict the
1779/// range of values to the ASCII character set (0-127).
1780/// @brief Simplify the toascii library function.
1781struct ToAsciiOptimization : public LibCallOptimization
1782{
1783public:
1784 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001785 ToAsciiOptimization() : LibCallOptimization("toascii",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001786 "Number of 'toascii' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +00001787
1788 /// @brief Destructor
1789 virtual ~ToAsciiOptimization() {}
1790
1791 /// @brief Make sure that the "fputs" function has the right prototype
1792 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1793 {
1794 // Just make sure this has 2 arguments
1795 return (f->arg_size() == 1);
1796 }
1797
1798 /// @brief Perform the toascii optimization.
1799 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1800 {
1801 // toascii(c) -> (c & 0x7f)
1802 Value* chr = ci->getOperand(1);
Chris Lattner4201cd12005-08-24 17:22:17 +00001803 BinaryOperator* and_inst = BinaryOperator::createAnd(chr,
Reid Spencer4c444fe2005-04-30 03:17:54 +00001804 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1805 ci->replaceAllUsesWith(and_inst);
1806 ci->eraseFromParent();
1807 return true;
1808 }
1809} ToAsciiOptimizer;
1810
Reid Spencerb195fcd2005-05-14 16:42:52 +00001811/// This LibCallOptimization will simplify calls to the "ffs" library
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001812/// calls which find the first set bit in an int, long, or long long. The
Reid Spencerb195fcd2005-05-14 16:42:52 +00001813/// optimization is to compute the result at compile time if the argument is
1814/// a constant.
1815/// @brief Simplify the ffs library function.
1816struct FFSOptimization : public LibCallOptimization
1817{
1818protected:
1819 /// @brief Subclass Constructor
1820 FFSOptimization(const char* funcName, const char* description)
1821 : LibCallOptimization(funcName, description)
1822 {}
1823
1824public:
1825 /// @brief Default Constructor
1826 FFSOptimization() : LibCallOptimization("ffs",
1827 "Number of 'ffs' calls simplified") {}
1828
1829 /// @brief Destructor
1830 virtual ~FFSOptimization() {}
1831
1832 /// @brief Make sure that the "fputs" function has the right prototype
1833 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1834 {
1835 // Just make sure this has 2 arguments
1836 return (f->arg_size() == 1 && f->getReturnType() == Type::IntTy);
1837 }
1838
1839 /// @brief Perform the ffs optimization.
1840 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1841 {
1842 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1843 {
1844 // ffs(cnst) -> bit#
1845 // ffsl(cnst) -> bit#
Reid Spencer17f77842005-05-15 21:19:45 +00001846 // ffsll(cnst) -> bit#
Reid Spencerb195fcd2005-05-14 16:42:52 +00001847 uint64_t val = CI->getRawValue();
Reid Spencer17f77842005-05-15 21:19:45 +00001848 int result = 0;
1849 while (val != 0) {
1850 result +=1;
1851 if (val&1)
1852 break;
1853 val >>= 1;
1854 }
Reid Spencerb195fcd2005-05-14 16:42:52 +00001855 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy, result));
1856 ci->eraseFromParent();
1857 return true;
1858 }
Reid Spencer17f77842005-05-15 21:19:45 +00001859
1860 // ffs(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1861 // ffsl(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1862 // ffsll(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1863 const Type* arg_type = ci->getOperand(1)->getType();
1864 std::vector<const Type*> args;
1865 args.push_back(arg_type);
1866 FunctionType* llvm_cttz_type = FunctionType::get(arg_type,args,false);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001867 Function* F =
Reid Spencer17f77842005-05-15 21:19:45 +00001868 SLC.getModule()->getOrInsertFunction("llvm.cttz",llvm_cttz_type);
1869 std::string inst_name(ci->getName()+".ffs");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001870 Instruction* call =
Reid Spencer17f77842005-05-15 21:19:45 +00001871 new CallInst(F, ci->getOperand(1), inst_name, ci);
1872 if (arg_type != Type::IntTy)
1873 call = new CastInst(call, Type::IntTy, inst_name, ci);
Chris Lattner4201cd12005-08-24 17:22:17 +00001874 BinaryOperator* add = BinaryOperator::createAdd(call,
Reid Spencer17f77842005-05-15 21:19:45 +00001875 ConstantSInt::get(Type::IntTy,1), inst_name, ci);
1876 SetCondInst* eq = new SetCondInst(Instruction::SetEQ,ci->getOperand(1),
1877 ConstantSInt::get(ci->getOperand(1)->getType(),0),inst_name,ci);
1878 SelectInst* select = new SelectInst(eq,ConstantSInt::get(Type::IntTy,0),add,
1879 inst_name,ci);
1880 ci->replaceAllUsesWith(select);
1881 ci->eraseFromParent();
1882 return true;
Reid Spencerb195fcd2005-05-14 16:42:52 +00001883 }
1884} FFSOptimizer;
1885
1886/// This LibCallOptimization will simplify calls to the "ffsl" library
1887/// calls. It simply uses FFSOptimization for which the transformation is
1888/// identical.
1889/// @brief Simplify the ffsl library function.
1890struct FFSLOptimization : public FFSOptimization
1891{
1892public:
1893 /// @brief Default Constructor
1894 FFSLOptimization() : FFSOptimization("ffsl",
1895 "Number of 'ffsl' calls simplified") {}
1896
1897} FFSLOptimizer;
1898
1899/// This LibCallOptimization will simplify calls to the "ffsll" library
1900/// calls. It simply uses FFSOptimization for which the transformation is
1901/// identical.
1902/// @brief Simplify the ffsl library function.
1903struct FFSLLOptimization : public FFSOptimization
1904{
1905public:
1906 /// @brief Default Constructor
1907 FFSLLOptimization() : FFSOptimization("ffsll",
1908 "Number of 'ffsll' calls simplified") {}
1909
1910} FFSLLOptimizer;
1911
Chris Lattner4201cd12005-08-24 17:22:17 +00001912
1913/// This LibCallOptimization will simplify calls to the "floor" library
1914/// function.
1915/// @brief Simplify the floor library function.
1916struct FloorOptimization : public LibCallOptimization {
1917 FloorOptimization()
1918 : LibCallOptimization("floor", "Number of 'floor' calls simplified") {}
1919
1920 /// @brief Make sure that the "floor" function has the right prototype
1921 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1922 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1923 F->getReturnType() == Type::DoubleTy;
1924 }
1925
1926 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1927 // If this is a float argument passed in, convert to floorf.
1928 // e.g. floor((double)FLT) -> (double)floorf(FLT). There can be no loss of
1929 // precision due to this.
1930 if (CastInst *Cast = dyn_cast<CastInst>(CI->getOperand(1)))
1931 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
1932 Value *New = new CallInst(SLC.get_floorf(), Cast->getOperand(0),
1933 CI->getName(), CI);
1934 New = new CastInst(New, Type::DoubleTy, CI->getName(), CI);
1935 CI->replaceAllUsesWith(New);
1936 CI->eraseFromParent();
1937 if (Cast->use_empty())
1938 Cast->eraseFromParent();
1939 return true;
1940 }
1941 return false; // opt failed
1942 }
1943} FloorOptimizer;
1944
1945
1946
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001947/// A function to compute the length of a null-terminated constant array of
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001948/// integers. This function can't rely on the size of the constant array
1949/// because there could be a null terminator in the middle of the array.
1950/// We also have to bail out if we find a non-integer constant initializer
1951/// of one of the elements or if there is no null-terminator. The logic
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001952/// below checks each of these conditions and will return true only if all
1953/// conditions are met. In that case, the \p len parameter is set to the length
1954/// of the null-terminated string. If false is returned, the conditions were
1955/// not met and len is set to 0.
1956/// @brief Get the length of a constant string (null-terminated array).
Reid Spencer4c444fe2005-04-30 03:17:54 +00001957bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
Reid Spencere249a822005-04-27 07:54:40 +00001958{
1959 assert(V != 0 && "Invalid args to getConstantStringLength");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001960 len = 0; // make sure we initialize this
Reid Spencere249a822005-04-27 07:54:40 +00001961 User* GEP = 0;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001962 // If the value is not a GEP instruction nor a constant expression with a
1963 // GEP instruction, then return false because ConstantArray can't occur
Reid Spencere249a822005-04-27 07:54:40 +00001964 // any other way
1965 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1966 GEP = GEPI;
1967 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1968 if (CE->getOpcode() == Instruction::GetElementPtr)
1969 GEP = CE;
1970 else
1971 return false;
1972 else
1973 return false;
1974
1975 // Make sure the GEP has exactly three arguments.
1976 if (GEP->getNumOperands() != 3)
1977 return false;
1978
1979 // Check to make sure that the first operand of the GEP is an integer and
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001980 // has value 0 so that we are sure we're indexing into the initializer.
Reid Spencere249a822005-04-27 07:54:40 +00001981 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1982 {
1983 if (!op1->isNullValue())
1984 return false;
1985 }
1986 else
1987 return false;
1988
1989 // Ensure that the second operand is a ConstantInt. If it isn't then this
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001990 // GEP is wonky and we're not really sure what were referencing into and
Reid Spencere249a822005-04-27 07:54:40 +00001991 // better of not optimizing it. While we're at it, get the second index
1992 // value. We'll need this later for indexing the ConstantArray.
1993 uint64_t start_idx = 0;
1994 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1995 start_idx = CI->getRawValue();
1996 else
1997 return false;
1998
1999 // The GEP instruction, constant or instruction, must reference a global
2000 // variable that is a constant and is initialized. The referenced constant
2001 // initializer is the array that we'll use for optimization.
2002 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2003 if (!GV || !GV->isConstant() || !GV->hasInitializer())
2004 return false;
2005
2006 // Get the initializer.
2007 Constant* INTLZR = GV->getInitializer();
2008
2009 // Handle the ConstantAggregateZero case
2010 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
2011 {
2012 // This is a degenerate case. The initializer is constant zero so the
2013 // length of the string must be zero.
2014 len = 0;
2015 return true;
2016 }
2017
2018 // Must be a Constant Array
2019 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
2020 if (!A)
2021 return false;
2022
2023 // Get the number of elements in the array
2024 uint64_t max_elems = A->getType()->getNumElements();
2025
2026 // Traverse the constant array from start_idx (derived above) which is
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002027 // the place the GEP refers to in the array.
Reid Spencere249a822005-04-27 07:54:40 +00002028 for ( len = start_idx; len < max_elems; len++)
2029 {
2030 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
2031 {
2032 // Check for the null terminator
2033 if (CI->isNullValue())
2034 break; // we found end of string
2035 }
2036 else
2037 return false; // This array isn't suitable, non-int initializer
2038 }
2039 if (len >= max_elems)
2040 return false; // This array isn't null terminated
2041
2042 // Subtract out the initial value from the length
2043 len -= start_idx;
Reid Spencer4c444fe2005-04-30 03:17:54 +00002044 if (CA)
2045 *CA = A;
Reid Spencere249a822005-04-27 07:54:40 +00002046 return true; // success!
2047}
2048
Reid Spencera7828ba2005-06-18 17:46:28 +00002049/// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
2050/// inserting the cast before IP, and return the cast.
2051/// @brief Cast a value to a "C" string.
2052Value *CastToCStr(Value *V, Instruction &IP) {
2053 const Type *SBPTy = PointerType::get(Type::SByteTy);
2054 if (V->getType() != SBPTy)
2055 return new CastInst(V, SBPTy, V->getName(), &IP);
2056 return V;
2057}
2058
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002059// TODO:
Reid Spencer649ac282005-04-28 04:40:06 +00002060// Additional cases that we need to add to this file:
2061//
Reid Spencer649ac282005-04-28 04:40:06 +00002062// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +00002063// * cbrt(expN(X)) -> expN(x/3)
2064// * cbrt(sqrt(x)) -> pow(x,1/6)
2065// * cbrt(sqrt(x)) -> pow(x,1/9)
2066//
Reid Spencer649ac282005-04-28 04:40:06 +00002067// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +00002068// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +00002069//
2070// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +00002071// * exp(log(x)) -> x
2072//
Reid Spencer649ac282005-04-28 04:40:06 +00002073// isascii:
2074// * isascii(c) -> ((c & ~0x7f) == 0)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002075//
Reid Spencer649ac282005-04-28 04:40:06 +00002076// isdigit:
2077// * isdigit(c) -> (unsigned)(c) - '0' <= 9
2078//
2079// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +00002080// * log(exp(x)) -> x
2081// * log(x**y) -> y*log(x)
2082// * log(exp(y)) -> y*log(e)
2083// * log(exp2(y)) -> y*log(2)
2084// * log(exp10(y)) -> y*log(10)
2085// * log(sqrt(x)) -> 0.5*log(x)
2086// * log(pow(x,y)) -> y*log(x)
2087//
2088// lround, lroundf, lroundl:
2089// * lround(cnst) -> cnst'
2090//
2091// memcmp:
Reid Spencer649ac282005-04-28 04:40:06 +00002092// * memcmp(x,y,l) -> cnst
2093// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer649ac282005-04-28 04:40:06 +00002094//
Reid Spencer649ac282005-04-28 04:40:06 +00002095// memmove:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002096// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
Reid Spencer649ac282005-04-28 04:40:06 +00002097// (if s is a global constant array)
2098//
Reid Spencer649ac282005-04-28 04:40:06 +00002099// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00002100// * pow(exp(x),y) -> exp(x*y)
2101// * pow(sqrt(x),y) -> pow(x,y*0.5)
2102// * pow(pow(x,y),z)-> pow(x,y*z)
2103//
2104// puts:
2105// * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
2106//
2107// round, roundf, roundl:
2108// * round(cnst) -> cnst'
2109//
2110// signbit:
2111// * signbit(cnst) -> cnst'
2112// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2113//
Reid Spencer649ac282005-04-28 04:40:06 +00002114// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00002115// * sqrt(expN(x)) -> expN(x*0.5)
2116// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2117// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2118//
Reid Spencer170ae7f2005-05-07 20:15:59 +00002119// stpcpy:
2120// * stpcpy(str, "literal") ->
2121// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer38cabd72005-05-03 07:23:44 +00002122// strrchr:
Reid Spencer649ac282005-04-28 04:40:06 +00002123// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2124// (if c is a constant integer and s is a constant string)
2125// * strrchr(s1,0) -> strchr(s1,0)
2126//
Reid Spencer649ac282005-04-28 04:40:06 +00002127// strncat:
2128// * strncat(x,y,0) -> x
2129// * strncat(x,y,0) -> x (if strlen(y) = 0)
2130// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2131//
Reid Spencer649ac282005-04-28 04:40:06 +00002132// strncpy:
2133// * strncpy(d,s,0) -> d
2134// * strncpy(d,s,l) -> memcpy(d,s,l,1)
2135// (if s and l are constants)
2136//
2137// strpbrk:
2138// * strpbrk(s,a) -> offset_in_for(s,a)
2139// (if s and a are both constant strings)
2140// * strpbrk(s,"") -> 0
2141// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2142//
2143// strspn, strcspn:
2144// * strspn(s,a) -> const_int (if both args are constant)
2145// * strspn("",a) -> 0
2146// * strspn(s,"") -> 0
2147// * strcspn(s,a) -> const_int (if both args are constant)
2148// * strcspn("",a) -> 0
2149// * strcspn(s,"") -> strlen(a)
2150//
2151// strstr:
2152// * strstr(x,x) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002153// * strstr(s1,s2) -> offset_of_s2_in(s1)
Reid Spencer649ac282005-04-28 04:40:06 +00002154// (if s1 and s2 are constant strings)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002155//
Reid Spencer649ac282005-04-28 04:40:06 +00002156// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00002157// * tan(atan(x)) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002158//
Reid Spencer649ac282005-04-28 04:40:06 +00002159// trunc, truncf, truncl:
2160// * trunc(cnst) -> cnst'
2161//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002162//
Reid Spencer39a762d2005-04-25 02:53:12 +00002163}