blob: 63ab333430c8ed5df59c238ff32e7e1381523561 [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,
Jeff Cohen11e26b52005-10-23 04:37:20 +0000314 Type::UIntTy, Type::UIntTy,
315 (Type *)0);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000316 }
Reid Spencere249a822005-04-27 07:54:40 +0000317 return memcpy_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000318 }
Reid Spencer76dab9a2005-04-26 05:24:00 +0000319
Chris Lattner4201cd12005-08-24 17:22:17 +0000320 Function* get_floorf() {
321 if (!floorf_func)
322 floorf_func = M->getOrInsertFunction("floorf", Type::FloatTy,
Jeff Cohen11e26b52005-10-23 04:37:20 +0000323 Type::FloatTy, (Type *)0);
Chris Lattner4201cd12005-08-24 17:22:17 +0000324 return floorf_func;
325 }
326
Reid Spencere249a822005-04-27 07:54:40 +0000327private:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000328 /// @brief Reset our cached data for a new Module
Reid Spencere249a822005-04-27 07:54:40 +0000329 void reset(Module& mod)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000330 {
Reid Spencere249a822005-04-27 07:54:40 +0000331 M = &mod;
332 TD = &getAnalysis<TargetData>();
Reid Spencer93616972005-04-29 09:39:47 +0000333 fputc_func = 0;
334 fwrite_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000335 memcpy_func = 0;
Reid Spencer38cabd72005-05-03 07:23:44 +0000336 memchr_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000337 sqrt_func = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +0000338 strcpy_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000339 strlen_func = 0;
Chris Lattner4201cd12005-08-24 17:22:17 +0000340 floorf_func = 0;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000341 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000342
Reid Spencere249a822005-04-27 07:54:40 +0000343private:
Reid Spencer93616972005-04-29 09:39:47 +0000344 Function* fputc_func; ///< Cached fputc function
345 Function* fwrite_func; ///< Cached fwrite function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000346 Function* memcpy_func; ///< Cached llvm.memcpy function
Reid Spencer38cabd72005-05-03 07:23:44 +0000347 Function* memchr_func; ///< Cached memchr function
Reid Spencer93616972005-04-29 09:39:47 +0000348 Function* sqrt_func; ///< Cached sqrt function
Reid Spencer1e520fd2005-05-04 03:20:21 +0000349 Function* strcpy_func; ///< Cached strcpy function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000350 Function* strlen_func; ///< Cached strlen function
Chris Lattner4201cd12005-08-24 17:22:17 +0000351 Function* floorf_func; ///< Cached floorf function
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000352 Module* M; ///< Cached Module
353 TargetData* TD; ///< Cached TargetData
Reid Spencere249a822005-04-27 07:54:40 +0000354};
355
356// Register the pass
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000357RegisterOpt<SimplifyLibCalls>
Reid Spencere249a822005-04-27 07:54:40 +0000358X("simplify-libcalls","Simplify well-known library calls");
359
360} // anonymous namespace
361
362// The only public symbol in this file which just instantiates the pass object
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000363ModulePass *llvm::createSimplifyLibCallsPass()
364{
365 return new SimplifyLibCalls();
Reid Spencere249a822005-04-27 07:54:40 +0000366}
367
368// Classes below here, in the anonymous namespace, are all subclasses of the
369// LibCallOptimization class, each implementing all optimizations possible for a
370// single well-known library call. Each has a static singleton instance that
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000371// auto registers it into the "optlist" global above.
Reid Spencere249a822005-04-27 07:54:40 +0000372namespace {
373
Reid Spencera7828ba2005-06-18 17:46:28 +0000374// Forward declare utility functions.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000375bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** A = 0 );
Reid Spencera7828ba2005-06-18 17:46:28 +0000376Value *CastToCStr(Value *V, Instruction &IP);
Reid Spencere249a822005-04-27 07:54:40 +0000377
378/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000379/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000380/// the same value passed to the exit function. When this is done, it splits the
381/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000382/// @brief Replace calls to exit in main with a simple return
Reid Spencere249a822005-04-27 07:54:40 +0000383struct ExitInMainOptimization : public LibCallOptimization
Reid Spencer39a762d2005-04-25 02:53:12 +0000384{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000385 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000386 "Number of 'exit' calls simplified") {}
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 Spencerf2534c72005-04-25 21:11:48 +0000454
455 /// @brief Make sure that the "strcat" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000456 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencerf2534c72005-04-25 21:11:48 +0000457 {
458 if (f->getReturnType() == PointerType::get(Type::SByteTy))
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000459 if (f->arg_size() == 2)
Reid Spencerf2534c72005-04-25 21:11:48 +0000460 {
461 Function::const_arg_iterator AI = f->arg_begin();
462 if (AI++->getType() == PointerType::get(Type::SByteTy))
463 if (AI->getType() == PointerType::get(Type::SByteTy))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000464 {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000465 // Indicate this is a suitable call type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000466 return true;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000467 }
Reid Spencerf2534c72005-04-25 21:11:48 +0000468 }
469 return false;
470 }
471
Reid Spencere249a822005-04-27 07:54:40 +0000472 /// @brief Optimize the strcat library function
473 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000474 {
Reid Spencer08b49402005-04-27 17:46:54 +0000475 // Extract some information from the instruction
476 Module* M = ci->getParent()->getParent()->getParent();
477 Value* dest = ci->getOperand(1);
478 Value* src = ci->getOperand(2);
479
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000480 // Extract the initializer (while making numerous checks) from the
Reid Spencer76dab9a2005-04-26 05:24:00 +0000481 // source operand of the call to strcat. If we get null back, one of
482 // a variety of checks in get_GVInitializer failed
Reid Spencerb4f7b832005-04-26 07:45:18 +0000483 uint64_t len = 0;
Reid Spencer08b49402005-04-27 17:46:54 +0000484 if (!getConstantStringLength(src,len))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000485 return false;
486
Reid Spencerb4f7b832005-04-26 07:45:18 +0000487 // Handle the simple, do-nothing case
488 if (len == 0)
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000489 {
Reid Spencer08b49402005-04-27 17:46:54 +0000490 ci->replaceAllUsesWith(dest);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000491 ci->eraseFromParent();
492 return true;
493 }
494
Reid Spencerb4f7b832005-04-26 07:45:18 +0000495 // Increment the length because we actually want to memcpy the null
496 // terminator as well.
497 len++;
Reid Spencerf2534c72005-04-25 21:11:48 +0000498
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000499 // We need to find the end of the destination string. That's where the
500 // memory is to be moved to. We just generate a call to strlen (further
501 // optimized in another pass). Note that the SLC.get_strlen() call
Reid Spencerb4f7b832005-04-26 07:45:18 +0000502 // caches the Function* for us.
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000503 CallInst* strlen_inst =
Reid Spencer08b49402005-04-27 17:46:54 +0000504 new CallInst(SLC.get_strlen(), dest, dest->getName()+".len",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000505
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000506 // Now that we have the destination's length, we must index into the
Reid Spencerb4f7b832005-04-26 07:45:18 +0000507 // destination's pointer to get the actual memcpy destination (end of
508 // the string .. we're concatenating).
509 std::vector<Value*> idx;
510 idx.push_back(strlen_inst);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000511 GetElementPtrInst* gep =
Reid Spencer08b49402005-04-27 17:46:54 +0000512 new GetElementPtrInst(dest,idx,dest->getName()+".indexed",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000513
514 // We have enough information to now generate the memcpy call to
515 // do the concatenation for us.
516 std::vector<Value*> vals;
517 vals.push_back(gep); // destination
518 vals.push_back(ci->getOperand(2)); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000519 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
520 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000521 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000522
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000523 // Finally, substitute the first operand of the strcat call for the
524 // strcat call itself since strcat returns its first operand; and,
Reid Spencerb4f7b832005-04-26 07:45:18 +0000525 // kill the strcat CallInst.
Reid Spencer08b49402005-04-27 17:46:54 +0000526 ci->replaceAllUsesWith(dest);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000527 ci->eraseFromParent();
528 return true;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000529 }
530} StrCatOptimizer;
531
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000532/// This LibCallOptimization will simplify a call to the strchr library
Reid Spencer38cabd72005-05-03 07:23:44 +0000533/// function. It optimizes out cases where the arguments are both constant
534/// and the result can be determined statically.
535/// @brief Simplify the strcmp library function.
536struct StrChrOptimization : public LibCallOptimization
537{
538public:
539 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000540 "Number of 'strchr' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +0000541
542 /// @brief Make sure that the "strchr" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000543 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer38cabd72005-05-03 07:23:44 +0000544 {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000545 if (f->getReturnType() == PointerType::get(Type::SByteTy) &&
Reid Spencer38cabd72005-05-03 07:23:44 +0000546 f->arg_size() == 2)
547 return true;
548 return false;
549 }
550
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000551 /// @brief Perform the strchr optimizations
Reid Spencer38cabd72005-05-03 07:23:44 +0000552 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
553 {
554 // If there aren't three operands, bail
555 if (ci->getNumOperands() != 3)
556 return false;
557
558 // Check that the first argument to strchr is a constant array of sbyte.
559 // If it is, get the length and data, otherwise return false.
560 uint64_t len = 0;
561 ConstantArray* CA;
562 if (!getConstantStringLength(ci->getOperand(1),len,&CA))
563 return false;
564
565 // Check that the second argument to strchr is a constant int, return false
566 // if it isn't
567 ConstantSInt* CSI = dyn_cast<ConstantSInt>(ci->getOperand(2));
568 if (!CSI)
569 {
570 // Just lower this to memchr since we know the length of the string as
571 // it is constant.
572 Function* f = SLC.get_memchr();
573 std::vector<Value*> args;
574 args.push_back(ci->getOperand(1));
575 args.push_back(ci->getOperand(2));
576 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
577 ci->replaceAllUsesWith( new CallInst(f,args,ci->getName(),ci));
578 ci->eraseFromParent();
579 return true;
580 }
581
582 // Get the character we're looking for
583 int64_t chr = CSI->getValue();
584
585 // Compute the offset
586 uint64_t offset = 0;
587 bool char_found = false;
588 for (uint64_t i = 0; i < len; ++i)
589 {
590 if (ConstantSInt* CI = dyn_cast<ConstantSInt>(CA->getOperand(i)))
591 {
592 // Check for the null terminator
593 if (CI->isNullValue())
594 break; // we found end of string
595 else if (CI->getValue() == chr)
596 {
597 char_found = true;
598 offset = i;
599 break;
600 }
601 }
602 }
603
604 // strchr(s,c) -> offset_of_in(c,s)
605 // (if c is a constant integer and s is a constant string)
606 if (char_found)
607 {
608 std::vector<Value*> indices;
609 indices.push_back(ConstantUInt::get(Type::ULongTy,offset));
610 GetElementPtrInst* GEP = new GetElementPtrInst(ci->getOperand(1),indices,
611 ci->getOperand(1)->getName()+".strchr",ci);
612 ci->replaceAllUsesWith(GEP);
613 }
614 else
615 ci->replaceAllUsesWith(
616 ConstantPointerNull::get(PointerType::get(Type::SByteTy)));
617
618 ci->eraseFromParent();
619 return true;
620 }
621} StrChrOptimizer;
622
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000623/// This LibCallOptimization will simplify a call to the strcmp library
Reid Spencer4c444fe2005-04-30 03:17:54 +0000624/// function. It optimizes out cases where one or both arguments are constant
625/// and the result can be determined statically.
626/// @brief Simplify the strcmp library function.
627struct StrCmpOptimization : public LibCallOptimization
628{
629public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000630 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000631 "Number of 'strcmp' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +0000632
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000633 /// @brief Make sure that the "strcmp" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000634 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer4c444fe2005-04-30 03:17:54 +0000635 {
636 if (f->getReturnType() == Type::IntTy && f->arg_size() == 2)
637 return true;
638 return false;
639 }
640
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000641 /// @brief Perform the strcmp optimization
Reid Spencer4c444fe2005-04-30 03:17:54 +0000642 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
643 {
644 // First, check to see if src and destination are the same. If they are,
Reid Spencer16449a92005-04-30 06:45:47 +0000645 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000646 // because the call is a no-op.
Reid Spencer4c444fe2005-04-30 03:17:54 +0000647 Value* s1 = ci->getOperand(1);
648 Value* s2 = ci->getOperand(2);
649 if (s1 == s2)
650 {
651 // strcmp(x,x) -> 0
652 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
653 ci->eraseFromParent();
654 return true;
655 }
656
657 bool isstr_1 = false;
658 uint64_t len_1 = 0;
659 ConstantArray* A1;
660 if (getConstantStringLength(s1,len_1,&A1))
661 {
662 isstr_1 = true;
663 if (len_1 == 0)
664 {
665 // strcmp("",x) -> *x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000666 LoadInst* load =
Reid Spencera7828ba2005-06-18 17:46:28 +0000667 new LoadInst(CastToCStr(s2,*ci), ci->getName()+".load",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000668 CastInst* cast =
Reid Spencer4c444fe2005-04-30 03:17:54 +0000669 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
670 ci->replaceAllUsesWith(cast);
671 ci->eraseFromParent();
672 return true;
673 }
674 }
675
676 bool isstr_2 = false;
677 uint64_t len_2 = 0;
678 ConstantArray* A2;
679 if (getConstantStringLength(s2,len_2,&A2))
680 {
681 isstr_2 = true;
682 if (len_2 == 0)
683 {
684 // strcmp(x,"") -> *x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000685 LoadInst* load =
Reid Spencera7828ba2005-06-18 17:46:28 +0000686 new LoadInst(CastToCStr(s1,*ci),ci->getName()+".val",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000687 CastInst* cast =
Reid Spencer4c444fe2005-04-30 03:17:54 +0000688 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
689 ci->replaceAllUsesWith(cast);
690 ci->eraseFromParent();
691 return true;
692 }
693 }
694
695 if (isstr_1 && isstr_2)
696 {
697 // strcmp(x,y) -> cnst (if both x and y are constant strings)
698 std::string str1 = A1->getAsString();
699 std::string str2 = A2->getAsString();
700 int result = strcmp(str1.c_str(), str2.c_str());
701 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
702 ci->eraseFromParent();
703 return true;
704 }
705 return false;
706 }
707} StrCmpOptimizer;
708
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000709/// This LibCallOptimization will simplify a call to the strncmp library
Reid Spencer49fa07042005-05-03 01:43:45 +0000710/// function. It optimizes out cases where one or both arguments are constant
711/// and the result can be determined statically.
712/// @brief Simplify the strncmp library function.
713struct StrNCmpOptimization : public LibCallOptimization
714{
715public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000716 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000717 "Number of 'strncmp' calls simplified") {}
Reid Spencer49fa07042005-05-03 01:43:45 +0000718
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000719 /// @brief Make sure that the "strncmp" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000720 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer49fa07042005-05-03 01:43:45 +0000721 {
722 if (f->getReturnType() == Type::IntTy && f->arg_size() == 3)
723 return true;
724 return false;
725 }
726
727 /// @brief Perform the strncpy optimization
728 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
729 {
730 // First, check to see if src and destination are the same. If they are,
731 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000732 // because the call is a no-op.
Reid Spencer49fa07042005-05-03 01:43:45 +0000733 Value* s1 = ci->getOperand(1);
734 Value* s2 = ci->getOperand(2);
735 if (s1 == s2)
736 {
737 // strncmp(x,x,l) -> 0
738 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
739 ci->eraseFromParent();
740 return true;
741 }
742
743 // Check the length argument, if it is Constant zero then the strings are
744 // considered equal.
745 uint64_t len_arg = 0;
746 bool len_arg_is_const = false;
747 if (ConstantInt* len_CI = dyn_cast<ConstantInt>(ci->getOperand(3)))
748 {
749 len_arg_is_const = true;
750 len_arg = len_CI->getRawValue();
751 if (len_arg == 0)
752 {
753 // strncmp(x,y,0) -> 0
754 ci->replaceAllUsesWith(ConstantInt::get(Type::IntTy,0));
755 ci->eraseFromParent();
756 return true;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000757 }
Reid Spencer49fa07042005-05-03 01:43:45 +0000758 }
759
760 bool isstr_1 = false;
761 uint64_t len_1 = 0;
762 ConstantArray* A1;
763 if (getConstantStringLength(s1,len_1,&A1))
764 {
765 isstr_1 = true;
766 if (len_1 == 0)
767 {
768 // strncmp("",x) -> *x
769 LoadInst* load = new LoadInst(s1,ci->getName()+".load",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000770 CastInst* cast =
Reid Spencer49fa07042005-05-03 01:43:45 +0000771 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
772 ci->replaceAllUsesWith(cast);
773 ci->eraseFromParent();
774 return true;
775 }
776 }
777
778 bool isstr_2 = false;
779 uint64_t len_2 = 0;
780 ConstantArray* A2;
781 if (getConstantStringLength(s2,len_2,&A2))
782 {
783 isstr_2 = true;
784 if (len_2 == 0)
785 {
786 // strncmp(x,"") -> *x
787 LoadInst* load = new LoadInst(s2,ci->getName()+".val",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000788 CastInst* cast =
Reid Spencer49fa07042005-05-03 01:43:45 +0000789 new CastInst(load,Type::IntTy,ci->getName()+".int",ci);
790 ci->replaceAllUsesWith(cast);
791 ci->eraseFromParent();
792 return true;
793 }
794 }
795
796 if (isstr_1 && isstr_2 && len_arg_is_const)
797 {
798 // strncmp(x,y,const) -> constant
799 std::string str1 = A1->getAsString();
800 std::string str2 = A2->getAsString();
801 int result = strncmp(str1.c_str(), str2.c_str(), len_arg);
802 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,result));
803 ci->eraseFromParent();
804 return true;
805 }
806 return false;
807 }
808} StrNCmpOptimizer;
809
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000810/// This LibCallOptimization will simplify a call to the strcpy library
811/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000812/// (1) If src and dest are the same and not volatile, just return dest
813/// (2) If the src is a constant then we can convert to llvm.memmove
814/// @brief Simplify the strcpy library function.
815struct StrCpyOptimization : public LibCallOptimization
816{
817public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000818 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000819 "Number of 'strcpy' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000820
821 /// @brief Make sure that the "strcpy" function has the right prototype
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000822 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencere249a822005-04-27 07:54:40 +0000823 {
824 if (f->getReturnType() == PointerType::get(Type::SByteTy))
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000825 if (f->arg_size() == 2)
Reid Spencere249a822005-04-27 07:54:40 +0000826 {
827 Function::const_arg_iterator AI = f->arg_begin();
828 if (AI++->getType() == PointerType::get(Type::SByteTy))
829 if (AI->getType() == PointerType::get(Type::SByteTy))
830 {
831 // Indicate this is a suitable call type.
832 return true;
833 }
834 }
835 return false;
836 }
837
838 /// @brief Perform the strcpy optimization
839 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
840 {
841 // First, check to see if src and destination are the same. If they are,
842 // then the optimization is to replace the CallInst with the destination
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000843 // because the call is a no-op. Note that this corresponds to the
Reid Spencere249a822005-04-27 07:54:40 +0000844 // degenerate strcpy(X,X) case which should have "undefined" results
845 // according to the C specification. However, it occurs sometimes and
846 // we optimize it as a no-op.
847 Value* dest = ci->getOperand(1);
848 Value* src = ci->getOperand(2);
849 if (dest == src)
850 {
851 ci->replaceAllUsesWith(dest);
852 ci->eraseFromParent();
853 return true;
854 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000855
Reid Spencere249a822005-04-27 07:54:40 +0000856 // Get the length of the constant string referenced by the second operand,
857 // the "src" parameter. Fail the optimization if we can't get the length
858 // (note that getConstantStringLength does lots of checks to make sure this
859 // is valid).
860 uint64_t len = 0;
861 if (!getConstantStringLength(ci->getOperand(2),len))
862 return false;
863
864 // If the constant string's length is zero we can optimize this by just
865 // doing a store of 0 at the first byte of the destination
866 if (len == 0)
867 {
868 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
869 ci->replaceAllUsesWith(dest);
870 ci->eraseFromParent();
871 return true;
872 }
873
874 // Increment the length because we actually want to memcpy the null
875 // terminator as well.
876 len++;
877
878 // Extract some information from the instruction
879 Module* M = ci->getParent()->getParent()->getParent();
880
881 // We have enough information to now generate the memcpy call to
882 // do the concatenation for us.
883 std::vector<Value*> vals;
884 vals.push_back(dest); // destination
885 vals.push_back(src); // source
Reid Spencer1e520fd2005-05-04 03:20:21 +0000886 vals.push_back(ConstantUInt::get(Type::UIntTy,len)); // length
887 vals.push_back(ConstantUInt::get(Type::UIntTy,1)); // alignment
Reid Spencer08b49402005-04-27 17:46:54 +0000888 new CallInst(SLC.get_memcpy(), vals, "", ci);
Reid Spencere249a822005-04-27 07:54:40 +0000889
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000890 // Finally, substitute the first operand of the strcat call for the
891 // strcat call itself since strcat returns its first operand; and,
Reid Spencere249a822005-04-27 07:54:40 +0000892 // kill the strcat CallInst.
893 ci->replaceAllUsesWith(dest);
894 ci->eraseFromParent();
895 return true;
896 }
897} StrCpyOptimizer;
898
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000899/// This LibCallOptimization will simplify a call to the strlen library
900/// function by replacing it with a constant value if the string provided to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000901/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000902/// @brief Simplify the strlen library function.
Reid Spencere249a822005-04-27 07:54:40 +0000903struct StrLenOptimization : public LibCallOptimization
Reid Spencer76dab9a2005-04-26 05:24:00 +0000904{
Reid Spencer95d8efd2005-05-03 02:54:54 +0000905 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000906 "Number of 'strlen' calls simplified") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000907
908 /// @brief Make sure that the "strlen" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +0000909 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000910 {
Reid Spencere249a822005-04-27 07:54:40 +0000911 if (f->getReturnType() == SLC.getTargetData()->getIntPtrType())
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000912 if (f->arg_size() == 1)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000913 if (Function::const_arg_iterator AI = f->arg_begin())
914 if (AI->getType() == PointerType::get(Type::SByteTy))
915 return true;
916 return false;
917 }
918
919 /// @brief Perform the strlen optimization
Reid Spencere249a822005-04-27 07:54:40 +0000920 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
Reid Spencer76dab9a2005-04-26 05:24:00 +0000921 {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000922 // Make sure we're dealing with an sbyte* here.
923 Value* str = ci->getOperand(1);
924 if (str->getType() != PointerType::get(Type::SByteTy))
925 return false;
926
927 // Does the call to strlen have exactly one use?
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000928 if (ci->hasOneUse())
Reid Spencer170ae7f2005-05-07 20:15:59 +0000929 // Is that single use a binary operator?
930 if (BinaryOperator* bop = dyn_cast<BinaryOperator>(ci->use_back()))
931 // Is it compared against a constant integer?
932 if (ConstantInt* CI = dyn_cast<ConstantInt>(bop->getOperand(1)))
933 {
934 // Get the value the strlen result is compared to
935 uint64_t val = CI->getRawValue();
936
937 // If its compared against length 0 with == or !=
938 if (val == 0 &&
939 (bop->getOpcode() == Instruction::SetEQ ||
940 bop->getOpcode() == Instruction::SetNE))
941 {
942 // strlen(x) != 0 -> *x != 0
943 // strlen(x) == 0 -> *x == 0
944 LoadInst* load = new LoadInst(str,str->getName()+".first",ci);
945 BinaryOperator* rbop = BinaryOperator::create(bop->getOpcode(),
946 load, ConstantSInt::get(Type::SByteTy,0),
947 bop->getName()+".strlen", ci);
948 bop->replaceAllUsesWith(rbop);
949 bop->eraseFromParent();
950 ci->eraseFromParent();
951 return true;
952 }
953 }
954
955 // Get the length of the constant string operand
Reid Spencerb4f7b832005-04-26 07:45:18 +0000956 uint64_t len = 0;
957 if (!getConstantStringLength(ci->getOperand(1),len))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000958 return false;
959
Reid Spencer170ae7f2005-05-07 20:15:59 +0000960 // strlen("xyz") -> 3 (for example)
Chris Lattnere17c5d02005-08-01 16:52:50 +0000961 const Type *Ty = SLC.getTargetData()->getIntPtrType();
962 if (Ty->isSigned())
963 ci->replaceAllUsesWith(ConstantSInt::get(Ty, len));
964 else
965 ci->replaceAllUsesWith(ConstantUInt::get(Ty, len));
966
Reid Spencerb4f7b832005-04-26 07:45:18 +0000967 ci->eraseFromParent();
968 return true;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000969 }
970} StrLenOptimizer;
971
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000972/// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
973/// is equal or not-equal to zero.
974static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
975 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
976 UI != E; ++UI) {
977 Instruction *User = cast<Instruction>(*UI);
978 if (User->getOpcode() == Instruction::SetNE ||
979 User->getOpcode() == Instruction::SetEQ) {
980 if (isa<Constant>(User->getOperand(1)) &&
981 cast<Constant>(User->getOperand(1))->isNullValue())
982 continue;
983 } else if (CastInst *CI = dyn_cast<CastInst>(User))
984 if (CI->getType() == Type::BoolTy)
985 continue;
986 // Unknown instruction.
987 return false;
988 }
989 return true;
990}
991
992/// This memcmpOptimization will simplify a call to the memcmp library
993/// function.
994struct memcmpOptimization : public LibCallOptimization {
995 /// @brief Default Constructor
996 memcmpOptimization()
997 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
998
999 /// @brief Make sure that the "memcmp" function has the right prototype
1000 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
1001 Function::const_arg_iterator AI = F->arg_begin();
1002 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
1003 if (!isa<PointerType>((++AI)->getType())) return false;
1004 if (!(++AI)->getType()->isInteger()) return false;
1005 if (!F->getReturnType()->isInteger()) return false;
1006 return true;
1007 }
1008
1009 /// Because of alignment and instruction information that we don't have, we
1010 /// leave the bulk of this to the code generators.
1011 ///
1012 /// Note that we could do much more if we could force alignment on otherwise
1013 /// small aligned allocas, or if we could indicate that loads have a small
1014 /// alignment.
1015 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
1016 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
1017
1018 // If the two operands are the same, return zero.
1019 if (LHS == RHS) {
1020 // memcmp(s,s,x) -> 0
1021 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1022 CI->eraseFromParent();
1023 return true;
1024 }
1025
1026 // Make sure we have a constant length.
1027 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1028 if (!LenC) return false;
1029 uint64_t Len = LenC->getRawValue();
1030
1031 // If the length is zero, this returns 0.
1032 switch (Len) {
1033 case 0:
1034 // memcmp(s1,s2,0) -> 0
1035 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
1036 CI->eraseFromParent();
1037 return true;
1038 case 1: {
1039 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
1040 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1041 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1042 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1043 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
1044 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
1045 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
1046 if (RV->getType() != CI->getType())
1047 RV = new CastInst(RV, CI->getType(), RV->getName(), CI);
1048 CI->replaceAllUsesWith(RV);
1049 CI->eraseFromParent();
1050 return true;
1051 }
1052 case 2:
1053 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
1054 // TODO: IF both are aligned, use a short load/compare.
1055
1056 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
1057 const Type *UCharPtr = PointerType::get(Type::UByteTy);
1058 CastInst *Op1Cast = new CastInst(LHS, UCharPtr, LHS->getName(), CI);
1059 CastInst *Op2Cast = new CastInst(RHS, UCharPtr, RHS->getName(), CI);
1060 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
1061 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
1062 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
1063 CI->getName()+".d1", CI);
1064 Constant *One = ConstantInt::get(Type::IntTy, 1);
1065 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
1066 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
1067 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
1068 Value *S2V2 = new LoadInst(G1, RHS->getName()+".val2", CI);
1069 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
1070 CI->getName()+".d1", CI);
1071 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
1072 if (Or->getType() != CI->getType())
1073 Or = new CastInst(Or, CI->getType(), Or->getName(), CI);
1074 CI->replaceAllUsesWith(Or);
1075 CI->eraseFromParent();
1076 return true;
1077 }
1078 break;
1079 default:
1080 break;
1081 }
1082
1083
1084
1085 return false;
1086 }
1087} memcmpOptimizer;
1088
1089
1090
1091
1092
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001093/// This LibCallOptimization will simplify a call to the memcpy library
1094/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001095/// bytes depending on the length of the string and the alignment. Additional
1096/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +00001097/// @brief Simplify the memcpy library function.
Reid Spencer38cabd72005-05-03 07:23:44 +00001098struct LLVMMemCpyOptimization : public LibCallOptimization
Reid Spencerf2534c72005-04-25 21:11:48 +00001099{
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001100 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +00001101 LLVMMemCpyOptimization() : LibCallOptimization("llvm.memcpy",
Reid Spencer95d8efd2005-05-03 02:54:54 +00001102 "Number of 'llvm.memcpy' calls simplified") {}
1103
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001104protected:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001105 /// @brief Subclass Constructor
Reid Spencer170ae7f2005-05-07 20:15:59 +00001106 LLVMMemCpyOptimization(const char* fname, const char* desc)
1107 : LibCallOptimization(fname, desc) {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001108public:
Reid Spencerf2534c72005-04-25 21:11:48 +00001109
1110 /// @brief Make sure that the "memcpy" function has the right prototype
Reid Spencere249a822005-04-27 07:54:40 +00001111 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +00001112 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001113 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +00001114 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +00001115 }
1116
Reid Spencerb4f7b832005-04-26 07:45:18 +00001117 /// Because of alignment and instruction information that we don't have, we
1118 /// leave the bulk of this to the code generators. The optimization here just
1119 /// deals with a few degenerate cases where the length of the string and the
1120 /// alignment match the sizes of our intrinsic types so we can do a load and
1121 /// store instead of the memcpy call.
1122 /// @brief Perform the memcpy optimization.
Reid Spencere249a822005-04-27 07:54:40 +00001123 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
Reid Spencerf2534c72005-04-25 21:11:48 +00001124 {
Reid Spencer4855ebf2005-04-26 19:55:57 +00001125 // Make sure we have constant int values to work with
1126 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1127 if (!LEN)
1128 return false;
1129 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1130 if (!ALIGN)
1131 return false;
1132
1133 // If the length is larger than the alignment, we can't optimize
1134 uint64_t len = LEN->getRawValue();
1135 uint64_t alignment = ALIGN->getRawValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001136 if (alignment == 0)
1137 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001138 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +00001139 return false;
1140
Reid Spencer08b49402005-04-27 17:46:54 +00001141 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +00001142 Value* dest = ci->getOperand(1);
1143 Value* src = ci->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +00001144 Type* castType = 0;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001145 switch (len)
1146 {
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001147 case 0:
Reid Spencer93616972005-04-29 09:39:47 +00001148 // memcpy(d,s,0,a) -> noop
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001149 ci->eraseFromParent();
1150 return true;
Reid Spencer08b49402005-04-27 17:46:54 +00001151 case 1: castType = Type::SByteTy; break;
1152 case 2: castType = Type::ShortTy; break;
1153 case 4: castType = Type::IntTy; break;
1154 case 8: castType = Type::LongTy; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001155 default:
1156 return false;
1157 }
Reid Spencer08b49402005-04-27 17:46:54 +00001158
1159 // Cast source and dest to the right sized primitive and then load/store
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001160 CastInst* SrcCast =
Reid Spencer08b49402005-04-27 17:46:54 +00001161 new CastInst(src,PointerType::get(castType),src->getName()+".cast",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001162 CastInst* DestCast =
Reid Spencer08b49402005-04-27 17:46:54 +00001163 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1164 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001165 StoreInst* SI = new StoreInst(LI, DestCast, ci);
Reid Spencerb4f7b832005-04-26 07:45:18 +00001166 ci->eraseFromParent();
1167 return true;
Reid Spencerf2534c72005-04-25 21:11:48 +00001168 }
Reid Spencer38cabd72005-05-03 07:23:44 +00001169} LLVMMemCpyOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001170
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001171/// This LibCallOptimization will simplify a call to the memmove library
1172/// function. It is identical to MemCopyOptimization except for the name of
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001173/// the intrinsic.
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001174/// @brief Simplify the memmove library function.
Reid Spencer38cabd72005-05-03 07:23:44 +00001175struct LLVMMemMoveOptimization : public LLVMMemCpyOptimization
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001176{
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001177 /// @brief Default Constructor
Reid Spencer38cabd72005-05-03 07:23:44 +00001178 LLVMMemMoveOptimization() : LLVMMemCpyOptimization("llvm.memmove",
Reid Spencer95d8efd2005-05-03 02:54:54 +00001179 "Number of 'llvm.memmove' calls simplified") {}
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001180
Reid Spencer38cabd72005-05-03 07:23:44 +00001181} LLVMMemMoveOptimizer;
1182
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001183/// This LibCallOptimization will simplify a call to the memset library
1184/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1185/// bytes depending on the length argument.
Reid Spencer38cabd72005-05-03 07:23:44 +00001186struct LLVMMemSetOptimization : public LibCallOptimization
1187{
1188 /// @brief Default Constructor
1189 LLVMMemSetOptimization() : LibCallOptimization("llvm.memset",
Reid Spencer38cabd72005-05-03 07:23:44 +00001190 "Number of 'llvm.memset' calls simplified") {}
1191
1192public:
Reid Spencer38cabd72005-05-03 07:23:44 +00001193
1194 /// @brief Make sure that the "memset" function has the right prototype
1195 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD)
1196 {
1197 // Just make sure this has 3 arguments per LLVM spec.
1198 return (f->arg_size() == 4);
1199 }
1200
1201 /// Because of alignment and instruction information that we don't have, we
1202 /// leave the bulk of this to the code generators. The optimization here just
1203 /// deals with a few degenerate cases where the length parameter is constant
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001204 /// and the alignment matches the sizes of our intrinsic types so we can do
Reid Spencer38cabd72005-05-03 07:23:44 +00001205 /// store instead of the memcpy call. Other calls are transformed into the
1206 /// llvm.memset intrinsic.
1207 /// @brief Perform the memset optimization.
1208 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD)
1209 {
1210 // Make sure we have constant int values to work with
1211 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1212 if (!LEN)
1213 return false;
1214 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1215 if (!ALIGN)
1216 return false;
1217
1218 // Extract the length and alignment
1219 uint64_t len = LEN->getRawValue();
1220 uint64_t alignment = ALIGN->getRawValue();
1221
1222 // Alignment 0 is identity for alignment 1
1223 if (alignment == 0)
1224 alignment = 1;
1225
1226 // If the length is zero, this is a no-op
1227 if (len == 0)
1228 {
1229 // memset(d,c,0,a) -> noop
1230 ci->eraseFromParent();
1231 return true;
1232 }
1233
1234 // If the length is larger than the alignment, we can't optimize
1235 if (len > alignment)
1236 return false;
1237
1238 // Make sure we have a constant ubyte to work with so we can extract
1239 // the value to be filled.
1240 ConstantUInt* FILL = dyn_cast<ConstantUInt>(ci->getOperand(2));
1241 if (!FILL)
1242 return false;
1243 if (FILL->getType() != Type::UByteTy)
1244 return false;
1245
1246 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001247
Reid Spencer38cabd72005-05-03 07:23:44 +00001248 // Extract the fill character
1249 uint64_t fill_char = FILL->getValue();
1250 uint64_t fill_value = fill_char;
1251
1252 // Get the type we will cast to, based on size of memory area to fill, and
1253 // and the value we will store there.
1254 Value* dest = ci->getOperand(1);
1255 Type* castType = 0;
1256 switch (len)
1257 {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001258 case 1:
1259 castType = Type::UByteTy;
Reid Spencer38cabd72005-05-03 07:23:44 +00001260 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001261 case 2:
1262 castType = Type::UShortTy;
Reid Spencer38cabd72005-05-03 07:23:44 +00001263 fill_value |= fill_char << 8;
1264 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001265 case 4:
Reid Spencer38cabd72005-05-03 07:23:44 +00001266 castType = Type::UIntTy;
1267 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1268 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001269 case 8:
Reid Spencer38cabd72005-05-03 07:23:44 +00001270 castType = Type::ULongTy;
1271 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1272 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1273 fill_value |= fill_char << 56;
1274 break;
1275 default:
1276 return false;
1277 }
1278
1279 // Cast dest to the right sized primitive and then load/store
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001280 CastInst* DestCast =
Reid Spencer38cabd72005-05-03 07:23:44 +00001281 new CastInst(dest,PointerType::get(castType),dest->getName()+".cast",ci);
1282 new StoreInst(ConstantUInt::get(castType,fill_value),DestCast, ci);
1283 ci->eraseFromParent();
1284 return true;
1285 }
1286} LLVMMemSetOptimizer;
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001287
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001288/// This LibCallOptimization will simplify calls to the "pow" library
1289/// function. It looks for cases where the result of pow is well known and
Reid Spencer93616972005-04-29 09:39:47 +00001290/// substitutes the appropriate value.
1291/// @brief Simplify the pow library function.
1292struct PowOptimization : public LibCallOptimization
1293{
1294public:
1295 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001296 PowOptimization() : LibCallOptimization("pow",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001297 "Number of 'pow' calls simplified") {}
Reid Spencer95d8efd2005-05-03 02:54:54 +00001298
Reid Spencer93616972005-04-29 09:39:47 +00001299 /// @brief Make sure that the "pow" function has the right prototype
1300 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1301 {
1302 // Just make sure this has 2 arguments
1303 return (f->arg_size() == 2);
1304 }
1305
1306 /// @brief Perform the pow optimization.
1307 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1308 {
1309 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
1310 Value* base = ci->getOperand(1);
1311 Value* expn = ci->getOperand(2);
1312 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
1313 double Op1V = Op1->getValue();
1314 if (Op1V == 1.0)
1315 {
1316 // pow(1.0,x) -> 1.0
1317 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1318 ci->eraseFromParent();
1319 return true;
1320 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001321 }
1322 else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn))
Reid Spencer93616972005-04-29 09:39:47 +00001323 {
1324 double Op2V = Op2->getValue();
1325 if (Op2V == 0.0)
1326 {
1327 // pow(x,0.0) -> 1.0
1328 ci->replaceAllUsesWith(ConstantFP::get(Ty,1.0));
1329 ci->eraseFromParent();
1330 return true;
1331 }
1332 else if (Op2V == 0.5)
1333 {
1334 // pow(x,0.5) -> sqrt(x)
1335 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1336 ci->getName()+".pow",ci);
1337 ci->replaceAllUsesWith(sqrt_inst);
1338 ci->eraseFromParent();
1339 return true;
1340 }
1341 else if (Op2V == 1.0)
1342 {
1343 // pow(x,1.0) -> x
1344 ci->replaceAllUsesWith(base);
1345 ci->eraseFromParent();
1346 return true;
1347 }
1348 else if (Op2V == -1.0)
1349 {
1350 // pow(x,-1.0) -> 1.0/x
Chris Lattner4201cd12005-08-24 17:22:17 +00001351 BinaryOperator* div_inst= BinaryOperator::createDiv(
Reid Spencer93616972005-04-29 09:39:47 +00001352 ConstantFP::get(Ty,1.0), base, ci->getName()+".pow", ci);
1353 ci->replaceAllUsesWith(div_inst);
1354 ci->eraseFromParent();
1355 return true;
1356 }
1357 }
1358 return false; // opt failed
1359 }
1360} PowOptimizer;
1361
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001362/// This LibCallOptimization will simplify calls to the "fprintf" library
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001363/// function. It looks for cases where the result of fprintf is not used and the
1364/// operation can be reduced to something simpler.
1365/// @brief Simplify the pow library function.
1366struct FPrintFOptimization : public LibCallOptimization
1367{
1368public:
1369 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001370 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001371 "Number of 'fprintf' calls simplified") {}
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001372
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001373 /// @brief Make sure that the "fprintf" function has the right prototype
1374 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1375 {
1376 // Just make sure this has at least 2 arguments
1377 return (f->arg_size() >= 2);
1378 }
1379
1380 /// @brief Perform the fprintf optimization.
1381 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1382 {
1383 // If the call has more than 3 operands, we can't optimize it
1384 if (ci->getNumOperands() > 4 || ci->getNumOperands() <= 2)
1385 return false;
1386
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001387 // If the result of the fprintf call is used, none of these optimizations
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001388 // can be made.
Chris Lattner175463a2005-09-24 22:17:06 +00001389 if (!ci->use_empty())
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001390 return false;
1391
1392 // All the optimizations depend on the length of the second argument and the
1393 // fact that it is a constant string array. Check that now
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001394 uint64_t len = 0;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001395 ConstantArray* CA = 0;
1396 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1397 return false;
1398
1399 if (ci->getNumOperands() == 3)
1400 {
1401 // Make sure there's no % in the constant array
1402 for (unsigned i = 0; i < len; ++i)
1403 {
1404 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1405 {
1406 // Check for the null terminator
1407 if (CI->getRawValue() == '%')
1408 return false; // we found end of string
1409 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001410 else
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001411 return false;
1412 }
1413
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001414 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001415 const Type* FILEptr_type = ci->getOperand(1)->getType();
1416 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1417 if (!fwrite_func)
1418 return false;
John Criswell4642afd2005-06-29 15:03:18 +00001419
1420 // Make sure that the fprintf() and fwrite() functions both take the
1421 // same type of char pointer.
1422 if (ci->getOperand(2)->getType() !=
1423 fwrite_func->getFunctionType()->getParamType(0))
John Criswell4642afd2005-06-29 15:03:18 +00001424 return false;
John Criswell4642afd2005-06-29 15:03:18 +00001425
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001426 std::vector<Value*> args;
1427 args.push_back(ci->getOperand(2));
1428 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1429 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1430 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001431 new CallInst(fwrite_func,args,ci->getName(),ci);
1432 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001433 ci->eraseFromParent();
1434 return true;
1435 }
1436
1437 // The remaining optimizations require the format string to be length 2
1438 // "%s" or "%c".
1439 if (len != 2)
1440 return false;
1441
1442 // The first character has to be a %
1443 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1444 if (CI->getRawValue() != '%')
1445 return false;
1446
1447 // Get the second character and switch on its value
1448 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
1449 switch (CI->getRawValue())
1450 {
1451 case 's':
1452 {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001453 uint64_t len = 0;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001454 ConstantArray* CA = 0;
1455 if (!getConstantStringLength(ci->getOperand(3), len, &CA))
1456 return false;
1457
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001458 // fprintf(file,"%s",str) -> fwrite(fmt,strlen(fmt),1,file)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001459 const Type* FILEptr_type = ci->getOperand(1)->getType();
1460 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
1461 if (!fwrite_func)
1462 return false;
1463 std::vector<Value*> args;
Reid Spencer45bb4af2005-05-21 00:39:30 +00001464 args.push_back(CastToCStr(ci->getOperand(3), *ci));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001465 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1466 args.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1467 args.push_back(ci->getOperand(1));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001468 new CallInst(fwrite_func,args,ci->getName(),ci);
1469 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001470 break;
1471 }
1472 case 'c':
1473 {
1474 ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(3));
1475 if (!CI)
1476 return false;
1477
1478 const Type* FILEptr_type = ci->getOperand(1)->getType();
1479 Function* fputc_func = SLC.get_fputc(FILEptr_type);
1480 if (!fputc_func)
1481 return false;
1482 CastInst* cast = new CastInst(CI,Type::IntTy,CI->getName()+".int",ci);
1483 new CallInst(fputc_func,cast,ci->getOperand(1),"",ci);
Reid Spencer1e520fd2005-05-04 03:20:21 +00001484 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001485 break;
1486 }
1487 default:
1488 return false;
1489 }
1490 ci->eraseFromParent();
1491 return true;
1492 }
1493} FPrintFOptimizer;
1494
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001495/// This LibCallOptimization will simplify calls to the "sprintf" library
Reid Spencer1e520fd2005-05-04 03:20:21 +00001496/// function. It looks for cases where the result of sprintf is not used and the
1497/// operation can be reduced to something simpler.
1498/// @brief Simplify the pow library function.
1499struct SPrintFOptimization : public LibCallOptimization
1500{
1501public:
1502 /// @brief Default Constructor
1503 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001504 "Number of 'sprintf' calls simplified") {}
Reid Spencer1e520fd2005-05-04 03:20:21 +00001505
Reid Spencer1e520fd2005-05-04 03:20:21 +00001506 /// @brief Make sure that the "fprintf" function has the right prototype
1507 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1508 {
1509 // Just make sure this has at least 2 arguments
1510 return (f->getReturnType() == Type::IntTy && f->arg_size() >= 2);
1511 }
1512
1513 /// @brief Perform the sprintf optimization.
1514 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1515 {
1516 // If the call has more than 3 operands, we can't optimize it
1517 if (ci->getNumOperands() > 4 || ci->getNumOperands() < 3)
1518 return false;
1519
1520 // All the optimizations depend on the length of the second argument and the
1521 // fact that it is a constant string array. Check that now
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001522 uint64_t len = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001523 ConstantArray* CA = 0;
1524 if (!getConstantStringLength(ci->getOperand(2), len, &CA))
1525 return false;
1526
1527 if (ci->getNumOperands() == 3)
1528 {
1529 if (len == 0)
1530 {
1531 // If the length is 0, we just need to store a null byte
1532 new StoreInst(ConstantInt::get(Type::SByteTy,0),ci->getOperand(1),ci);
1533 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1534 ci->eraseFromParent();
1535 return true;
1536 }
1537
1538 // Make sure there's no % in the constant array
1539 for (unsigned i = 0; i < len; ++i)
1540 {
1541 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(i)))
1542 {
1543 // Check for the null terminator
1544 if (CI->getRawValue() == '%')
1545 return false; // we found a %, can't optimize
1546 }
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001547 else
Reid Spencer1e520fd2005-05-04 03:20:21 +00001548 return false; // initializer is not constant int, can't optimize
1549 }
1550
1551 // Increment length because we want to copy the null byte too
1552 len++;
1553
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001554 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
Reid Spencer1e520fd2005-05-04 03:20:21 +00001555 Function* memcpy_func = SLC.get_memcpy();
1556 if (!memcpy_func)
1557 return false;
1558 std::vector<Value*> args;
1559 args.push_back(ci->getOperand(1));
1560 args.push_back(ci->getOperand(2));
1561 args.push_back(ConstantUInt::get(Type::UIntTy,len));
1562 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1563 new CallInst(memcpy_func,args,"",ci);
1564 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,len));
1565 ci->eraseFromParent();
1566 return true;
1567 }
1568
1569 // The remaining optimizations require the format string to be length 2
1570 // "%s" or "%c".
1571 if (len != 2)
1572 return false;
1573
1574 // The first character has to be a %
1575 if (ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(0)))
1576 if (CI->getRawValue() != '%')
1577 return false;
1578
1579 // Get the second character and switch on its value
1580 ConstantInt* CI = dyn_cast<ConstantInt>(CA->getOperand(1));
Chris Lattner175463a2005-09-24 22:17:06 +00001581 switch (CI->getRawValue()) {
1582 case 's': {
1583 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1584 Function* strlen_func = SLC.get_strlen();
1585 Function* memcpy_func = SLC.get_memcpy();
1586 if (!strlen_func || !memcpy_func)
Reid Spencer1e520fd2005-05-04 03:20:21 +00001587 return false;
Chris Lattner175463a2005-09-24 22:17:06 +00001588
1589 Value *Len = new CallInst(strlen_func, CastToCStr(ci->getOperand(3), *ci),
1590 ci->getOperand(3)->getName()+".len", ci);
1591 Value *Len1 = BinaryOperator::createAdd(Len,
1592 ConstantInt::get(Len->getType(), 1),
1593 Len->getName()+"1", ci);
1594 if (Len1->getType() != Type::UIntTy)
1595 Len1 = new CastInst(Len1, Type::UIntTy, Len1->getName(), ci);
1596 std::vector<Value*> args;
1597 args.push_back(CastToCStr(ci->getOperand(1), *ci));
1598 args.push_back(CastToCStr(ci->getOperand(3), *ci));
1599 args.push_back(Len1);
1600 args.push_back(ConstantUInt::get(Type::UIntTy,1));
1601 new CallInst(memcpy_func, args, "", ci);
1602
1603 // The strlen result is the unincremented number of bytes in the string.
Chris Lattnerf4877682005-09-25 07:06:48 +00001604 if (!ci->use_empty()) {
1605 if (Len->getType() != ci->getType())
1606 Len = new CastInst(Len, ci->getType(), Len->getName(), ci);
1607 ci->replaceAllUsesWith(Len);
1608 }
Chris Lattner175463a2005-09-24 22:17:06 +00001609 ci->eraseFromParent();
1610 return true;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001611 }
Chris Lattner175463a2005-09-24 22:17:06 +00001612 case 'c': {
1613 // sprintf(dest,"%c",chr) -> store chr, dest
1614 CastInst* cast = new CastInst(ci->getOperand(3),Type::SByteTy,"char",ci);
1615 new StoreInst(cast, ci->getOperand(1), ci);
1616 GetElementPtrInst* gep = new GetElementPtrInst(ci->getOperand(1),
1617 ConstantUInt::get(Type::UIntTy,1),ci->getOperand(1)->getName()+".end",
1618 ci);
1619 new StoreInst(ConstantInt::get(Type::SByteTy,0),gep,ci);
1620 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1621 ci->eraseFromParent();
1622 return true;
1623 }
1624 }
1625 return false;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001626 }
1627} SPrintFOptimizer;
1628
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001629/// This LibCallOptimization will simplify calls to the "fputs" library
Reid Spencer93616972005-04-29 09:39:47 +00001630/// function. It looks for cases where the result of fputs is not used and the
1631/// operation can be reduced to something simpler.
1632/// @brief Simplify the pow library function.
1633struct PutsOptimization : public LibCallOptimization
1634{
1635public:
1636 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001637 PutsOptimization() : LibCallOptimization("fputs",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001638 "Number of 'fputs' calls simplified") {}
Reid Spencer93616972005-04-29 09:39:47 +00001639
Reid Spencer93616972005-04-29 09:39:47 +00001640 /// @brief Make sure that the "fputs" function has the right prototype
1641 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1642 {
1643 // Just make sure this has 2 arguments
1644 return (f->arg_size() == 2);
1645 }
1646
1647 /// @brief Perform the fputs optimization.
1648 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1649 {
1650 // If the result is used, none of these optimizations work
Chris Lattner175463a2005-09-24 22:17:06 +00001651 if (!ci->use_empty())
Reid Spencer93616972005-04-29 09:39:47 +00001652 return false;
1653
1654 // All the optimizations depend on the length of the first argument and the
1655 // fact that it is a constant string array. Check that now
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001656 uint64_t len = 0;
Reid Spencer93616972005-04-29 09:39:47 +00001657 if (!getConstantStringLength(ci->getOperand(1), len))
1658 return false;
1659
1660 switch (len)
1661 {
1662 case 0:
1663 // fputs("",F) -> noop
1664 break;
1665 case 1:
1666 {
1667 // fputs(s,F) -> fputc(s[0],F) (if s is constant and strlen(s) == 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001668 const Type* FILEptr_type = ci->getOperand(2)->getType();
1669 Function* fputc_func = SLC.get_fputc(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001670 if (!fputc_func)
1671 return false;
1672 LoadInst* loadi = new LoadInst(ci->getOperand(1),
1673 ci->getOperand(1)->getName()+".byte",ci);
1674 CastInst* casti = new CastInst(loadi,Type::IntTy,
1675 loadi->getName()+".int",ci);
1676 new CallInst(fputc_func,casti,ci->getOperand(2),"",ci);
1677 break;
1678 }
1679 default:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001680 {
Reid Spencer93616972005-04-29 09:39:47 +00001681 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
Reid Spencer4c444fe2005-04-30 03:17:54 +00001682 const Type* FILEptr_type = ci->getOperand(2)->getType();
1683 Function* fwrite_func = SLC.get_fwrite(FILEptr_type);
Reid Spencer93616972005-04-29 09:39:47 +00001684 if (!fwrite_func)
1685 return false;
1686 std::vector<Value*> parms;
1687 parms.push_back(ci->getOperand(1));
1688 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),len));
1689 parms.push_back(ConstantUInt::get(SLC.getIntPtrType(),1));
1690 parms.push_back(ci->getOperand(2));
1691 new CallInst(fwrite_func,parms,"",ci);
1692 break;
1693 }
1694 }
1695 ci->eraseFromParent();
1696 return true; // success
1697 }
1698} PutsOptimizer;
1699
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001700/// This LibCallOptimization will simplify calls to the "isdigit" library
Reid Spencer282d0572005-05-04 18:58:28 +00001701/// function. It simply does range checks the parameter explicitly.
1702/// @brief Simplify the isdigit library function.
Chris Lattner5f6035f2005-09-29 06:16:11 +00001703struct isdigitOptimization : public LibCallOptimization {
Reid Spencer282d0572005-05-04 18:58:28 +00001704public:
Chris Lattner5f6035f2005-09-29 06:16:11 +00001705 isdigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001706 "Number of 'isdigit' calls simplified") {}
Reid Spencer282d0572005-05-04 18:58:28 +00001707
Chris Lattner5f6035f2005-09-29 06:16:11 +00001708 /// @brief Make sure that the "isdigit" function has the right prototype
Reid Spencer282d0572005-05-04 18:58:28 +00001709 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1710 {
1711 // Just make sure this has 1 argument
1712 return (f->arg_size() == 1);
1713 }
1714
1715 /// @brief Perform the toascii optimization.
1716 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1717 {
1718 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1719 {
1720 // isdigit(c) -> 0 or 1, if 'c' is constant
1721 uint64_t val = CI->getRawValue();
1722 if (val >= '0' && val <='9')
1723 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,1));
1724 else
1725 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy,0));
1726 ci->eraseFromParent();
1727 return true;
1728 }
1729
1730 // isdigit(c) -> (unsigned)c - '0' <= 9
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001731 CastInst* cast =
Reid Spencer282d0572005-05-04 18:58:28 +00001732 new CastInst(ci->getOperand(1),Type::UIntTy,
1733 ci->getOperand(1)->getName()+".uint",ci);
Chris Lattner4201cd12005-08-24 17:22:17 +00001734 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
Reid Spencer282d0572005-05-04 18:58:28 +00001735 ConstantUInt::get(Type::UIntTy,0x30),
1736 ci->getOperand(1)->getName()+".sub",ci);
1737 SetCondInst* setcond_inst = new SetCondInst(Instruction::SetLE,sub_inst,
1738 ConstantUInt::get(Type::UIntTy,9),
1739 ci->getOperand(1)->getName()+".cmp",ci);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001740 CastInst* c2 =
Reid Spencer282d0572005-05-04 18:58:28 +00001741 new CastInst(setcond_inst,Type::IntTy,
1742 ci->getOperand(1)->getName()+".isdigit",ci);
1743 ci->replaceAllUsesWith(c2);
1744 ci->eraseFromParent();
1745 return true;
1746 }
Chris Lattner5f6035f2005-09-29 06:16:11 +00001747} isdigitOptimizer;
1748
Chris Lattner87ef9432005-09-29 06:17:27 +00001749struct isasciiOptimization : public LibCallOptimization {
1750public:
1751 isasciiOptimization()
1752 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1753
1754 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1755 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1756 F->getReturnType()->isInteger();
1757 }
1758
1759 /// @brief Perform the isascii optimization.
1760 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1761 // isascii(c) -> (unsigned)c < 128
1762 Value *V = CI->getOperand(1);
1763 if (V->getType()->isSigned())
1764 V = new CastInst(V, V->getType()->getUnsignedVersion(), V->getName(), CI);
1765 Value *Cmp = BinaryOperator::createSetLT(V, ConstantUInt::get(V->getType(),
1766 128),
1767 V->getName()+".isascii", CI);
1768 if (Cmp->getType() != CI->getType())
1769 Cmp = new CastInst(Cmp, CI->getType(), Cmp->getName(), CI);
1770 CI->replaceAllUsesWith(Cmp);
1771 CI->eraseFromParent();
1772 return true;
1773 }
1774} isasciiOptimizer;
Chris Lattner5f6035f2005-09-29 06:16:11 +00001775
Reid Spencer282d0572005-05-04 18:58:28 +00001776
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
Reid Spencer4c444fe2005-04-30 03:17:54 +00001788 /// @brief Make sure that the "fputs" function has the right prototype
1789 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1790 {
1791 // Just make sure this has 2 arguments
1792 return (f->arg_size() == 1);
1793 }
1794
1795 /// @brief Perform the toascii optimization.
1796 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1797 {
1798 // toascii(c) -> (c & 0x7f)
1799 Value* chr = ci->getOperand(1);
Chris Lattner4201cd12005-08-24 17:22:17 +00001800 BinaryOperator* and_inst = BinaryOperator::createAnd(chr,
Reid Spencer4c444fe2005-04-30 03:17:54 +00001801 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
1802 ci->replaceAllUsesWith(and_inst);
1803 ci->eraseFromParent();
1804 return true;
1805 }
1806} ToAsciiOptimizer;
1807
Reid Spencerb195fcd2005-05-14 16:42:52 +00001808/// This LibCallOptimization will simplify calls to the "ffs" library
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001809/// calls which find the first set bit in an int, long, or long long. The
Reid Spencerb195fcd2005-05-14 16:42:52 +00001810/// optimization is to compute the result at compile time if the argument is
1811/// a constant.
1812/// @brief Simplify the ffs library function.
1813struct FFSOptimization : public LibCallOptimization
1814{
1815protected:
1816 /// @brief Subclass Constructor
1817 FFSOptimization(const char* funcName, const char* description)
1818 : LibCallOptimization(funcName, description)
1819 {}
1820
1821public:
1822 /// @brief Default Constructor
1823 FFSOptimization() : LibCallOptimization("ffs",
1824 "Number of 'ffs' calls simplified") {}
1825
Reid Spencerb195fcd2005-05-14 16:42:52 +00001826 /// @brief Make sure that the "fputs" function has the right prototype
1827 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC)
1828 {
1829 // Just make sure this has 2 arguments
1830 return (f->arg_size() == 1 && f->getReturnType() == Type::IntTy);
1831 }
1832
1833 /// @brief Perform the ffs optimization.
1834 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC)
1835 {
1836 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1)))
1837 {
1838 // ffs(cnst) -> bit#
1839 // ffsl(cnst) -> bit#
Reid Spencer17f77842005-05-15 21:19:45 +00001840 // ffsll(cnst) -> bit#
Reid Spencerb195fcd2005-05-14 16:42:52 +00001841 uint64_t val = CI->getRawValue();
Reid Spencer17f77842005-05-15 21:19:45 +00001842 int result = 0;
1843 while (val != 0) {
1844 result +=1;
1845 if (val&1)
1846 break;
1847 val >>= 1;
1848 }
Reid Spencerb195fcd2005-05-14 16:42:52 +00001849 ci->replaceAllUsesWith(ConstantSInt::get(Type::IntTy, result));
1850 ci->eraseFromParent();
1851 return true;
1852 }
Reid Spencer17f77842005-05-15 21:19:45 +00001853
1854 // ffs(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1855 // ffsl(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1856 // ffsll(x) -> ( x == 0 ? 0 : llvm.cttz(x)+1)
1857 const Type* arg_type = ci->getOperand(1)->getType();
1858 std::vector<const Type*> args;
1859 args.push_back(arg_type);
1860 FunctionType* llvm_cttz_type = FunctionType::get(arg_type,args,false);
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001861 Function* F =
Reid Spencer17f77842005-05-15 21:19:45 +00001862 SLC.getModule()->getOrInsertFunction("llvm.cttz",llvm_cttz_type);
1863 std::string inst_name(ci->getName()+".ffs");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001864 Instruction* call =
Reid Spencer17f77842005-05-15 21:19:45 +00001865 new CallInst(F, ci->getOperand(1), inst_name, ci);
1866 if (arg_type != Type::IntTy)
1867 call = new CastInst(call, Type::IntTy, inst_name, ci);
Chris Lattner4201cd12005-08-24 17:22:17 +00001868 BinaryOperator* add = BinaryOperator::createAdd(call,
Reid Spencer17f77842005-05-15 21:19:45 +00001869 ConstantSInt::get(Type::IntTy,1), inst_name, ci);
1870 SetCondInst* eq = new SetCondInst(Instruction::SetEQ,ci->getOperand(1),
1871 ConstantSInt::get(ci->getOperand(1)->getType(),0),inst_name,ci);
1872 SelectInst* select = new SelectInst(eq,ConstantSInt::get(Type::IntTy,0),add,
1873 inst_name,ci);
1874 ci->replaceAllUsesWith(select);
1875 ci->eraseFromParent();
1876 return true;
Reid Spencerb195fcd2005-05-14 16:42:52 +00001877 }
1878} FFSOptimizer;
1879
1880/// This LibCallOptimization will simplify calls to the "ffsl" library
1881/// calls. It simply uses FFSOptimization for which the transformation is
1882/// identical.
1883/// @brief Simplify the ffsl library function.
1884struct FFSLOptimization : public FFSOptimization
1885{
1886public:
1887 /// @brief Default Constructor
1888 FFSLOptimization() : FFSOptimization("ffsl",
1889 "Number of 'ffsl' calls simplified") {}
1890
1891} FFSLOptimizer;
1892
1893/// This LibCallOptimization will simplify calls to the "ffsll" library
1894/// calls. It simply uses FFSOptimization for which the transformation is
1895/// identical.
1896/// @brief Simplify the ffsl library function.
1897struct FFSLLOptimization : public FFSOptimization
1898{
1899public:
1900 /// @brief Default Constructor
1901 FFSLLOptimization() : FFSOptimization("ffsll",
1902 "Number of 'ffsll' calls simplified") {}
1903
1904} FFSLLOptimizer;
1905
Chris Lattner4201cd12005-08-24 17:22:17 +00001906
1907/// This LibCallOptimization will simplify calls to the "floor" library
1908/// function.
1909/// @brief Simplify the floor library function.
1910struct FloorOptimization : public LibCallOptimization {
1911 FloorOptimization()
1912 : LibCallOptimization("floor", "Number of 'floor' calls simplified") {}
1913
1914 /// @brief Make sure that the "floor" function has the right prototype
1915 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1916 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1917 F->getReturnType() == Type::DoubleTy;
1918 }
1919
1920 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1921 // If this is a float argument passed in, convert to floorf.
1922 // e.g. floor((double)FLT) -> (double)floorf(FLT). There can be no loss of
1923 // precision due to this.
1924 if (CastInst *Cast = dyn_cast<CastInst>(CI->getOperand(1)))
1925 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
1926 Value *New = new CallInst(SLC.get_floorf(), Cast->getOperand(0),
1927 CI->getName(), CI);
1928 New = new CastInst(New, Type::DoubleTy, CI->getName(), CI);
1929 CI->replaceAllUsesWith(New);
1930 CI->eraseFromParent();
1931 if (Cast->use_empty())
1932 Cast->eraseFromParent();
1933 return true;
1934 }
1935 return false; // opt failed
1936 }
1937} FloorOptimizer;
1938
1939
1940
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001941/// A function to compute the length of a null-terminated constant array of
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001942/// integers. This function can't rely on the size of the constant array
1943/// because there could be a null terminator in the middle of the array.
1944/// We also have to bail out if we find a non-integer constant initializer
1945/// of one of the elements or if there is no null-terminator. The logic
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001946/// below checks each of these conditions and will return true only if all
1947/// conditions are met. In that case, the \p len parameter is set to the length
1948/// of the null-terminated string. If false is returned, the conditions were
1949/// not met and len is set to 0.
1950/// @brief Get the length of a constant string (null-terminated array).
Reid Spencer4c444fe2005-04-30 03:17:54 +00001951bool getConstantStringLength(Value* V, uint64_t& len, ConstantArray** CA )
Reid Spencere249a822005-04-27 07:54:40 +00001952{
1953 assert(V != 0 && "Invalid args to getConstantStringLength");
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001954 len = 0; // make sure we initialize this
Reid Spencere249a822005-04-27 07:54:40 +00001955 User* GEP = 0;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001956 // If the value is not a GEP instruction nor a constant expression with a
1957 // GEP instruction, then return false because ConstantArray can't occur
Reid Spencere249a822005-04-27 07:54:40 +00001958 // any other way
1959 if (GetElementPtrInst* GEPI = dyn_cast<GetElementPtrInst>(V))
1960 GEP = GEPI;
1961 else if (ConstantExpr* CE = dyn_cast<ConstantExpr>(V))
1962 if (CE->getOpcode() == Instruction::GetElementPtr)
1963 GEP = CE;
1964 else
1965 return false;
1966 else
1967 return false;
1968
1969 // Make sure the GEP has exactly three arguments.
1970 if (GEP->getNumOperands() != 3)
1971 return false;
1972
1973 // Check to make sure that the first operand of the GEP is an integer and
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001974 // has value 0 so that we are sure we're indexing into the initializer.
Reid Spencere249a822005-04-27 07:54:40 +00001975 if (ConstantInt* op1 = dyn_cast<ConstantInt>(GEP->getOperand(1)))
1976 {
1977 if (!op1->isNullValue())
1978 return false;
1979 }
1980 else
1981 return false;
1982
1983 // Ensure that the second operand is a ConstantInt. If it isn't then this
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001984 // GEP is wonky and we're not really sure what were referencing into and
Reid Spencere249a822005-04-27 07:54:40 +00001985 // better of not optimizing it. While we're at it, get the second index
1986 // value. We'll need this later for indexing the ConstantArray.
1987 uint64_t start_idx = 0;
1988 if (ConstantInt* CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1989 start_idx = CI->getRawValue();
1990 else
1991 return false;
1992
1993 // The GEP instruction, constant or instruction, must reference a global
1994 // variable that is a constant and is initialized. The referenced constant
1995 // initializer is the array that we'll use for optimization.
1996 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1997 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1998 return false;
1999
2000 // Get the initializer.
2001 Constant* INTLZR = GV->getInitializer();
2002
2003 // Handle the ConstantAggregateZero case
2004 if (ConstantAggregateZero* CAZ = dyn_cast<ConstantAggregateZero>(INTLZR))
2005 {
2006 // This is a degenerate case. The initializer is constant zero so the
2007 // length of the string must be zero.
2008 len = 0;
2009 return true;
2010 }
2011
2012 // Must be a Constant Array
2013 ConstantArray* A = dyn_cast<ConstantArray>(INTLZR);
2014 if (!A)
2015 return false;
2016
2017 // Get the number of elements in the array
2018 uint64_t max_elems = A->getType()->getNumElements();
2019
2020 // Traverse the constant array from start_idx (derived above) which is
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002021 // the place the GEP refers to in the array.
Reid Spencere249a822005-04-27 07:54:40 +00002022 for ( len = start_idx; len < max_elems; len++)
2023 {
2024 if (ConstantInt* CI = dyn_cast<ConstantInt>(A->getOperand(len)))
2025 {
2026 // Check for the null terminator
2027 if (CI->isNullValue())
2028 break; // we found end of string
2029 }
2030 else
2031 return false; // This array isn't suitable, non-int initializer
2032 }
2033 if (len >= max_elems)
2034 return false; // This array isn't null terminated
2035
2036 // Subtract out the initial value from the length
2037 len -= start_idx;
Reid Spencer4c444fe2005-04-30 03:17:54 +00002038 if (CA)
2039 *CA = A;
Reid Spencere249a822005-04-27 07:54:40 +00002040 return true; // success!
2041}
2042
Reid Spencera7828ba2005-06-18 17:46:28 +00002043/// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
2044/// inserting the cast before IP, and return the cast.
2045/// @brief Cast a value to a "C" string.
2046Value *CastToCStr(Value *V, Instruction &IP) {
2047 const Type *SBPTy = PointerType::get(Type::SByteTy);
2048 if (V->getType() != SBPTy)
2049 return new CastInst(V, SBPTy, V->getName(), &IP);
2050 return V;
2051}
2052
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002053// TODO:
Reid Spencer649ac282005-04-28 04:40:06 +00002054// Additional cases that we need to add to this file:
2055//
Reid Spencer649ac282005-04-28 04:40:06 +00002056// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +00002057// * cbrt(expN(X)) -> expN(x/3)
2058// * cbrt(sqrt(x)) -> pow(x,1/6)
2059// * cbrt(sqrt(x)) -> pow(x,1/9)
2060//
Reid Spencer649ac282005-04-28 04:40:06 +00002061// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +00002062// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +00002063//
2064// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +00002065// * exp(log(x)) -> x
2066//
Reid Spencer649ac282005-04-28 04:40:06 +00002067// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +00002068// * log(exp(x)) -> x
2069// * log(x**y) -> y*log(x)
2070// * log(exp(y)) -> y*log(e)
2071// * log(exp2(y)) -> y*log(2)
2072// * log(exp10(y)) -> y*log(10)
2073// * log(sqrt(x)) -> 0.5*log(x)
2074// * log(pow(x,y)) -> y*log(x)
2075//
2076// lround, lroundf, lroundl:
2077// * lround(cnst) -> cnst'
2078//
2079// memcmp:
Reid Spencer649ac282005-04-28 04:40:06 +00002080// * memcmp(x,y,l) -> cnst
2081// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer649ac282005-04-28 04:40:06 +00002082//
Reid Spencer649ac282005-04-28 04:40:06 +00002083// memmove:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002084// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
Reid Spencer649ac282005-04-28 04:40:06 +00002085// (if s is a global constant array)
2086//
Reid Spencer649ac282005-04-28 04:40:06 +00002087// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00002088// * pow(exp(x),y) -> exp(x*y)
2089// * pow(sqrt(x),y) -> pow(x,y*0.5)
2090// * pow(pow(x,y),z)-> pow(x,y*z)
2091//
2092// puts:
2093// * puts("") -> fputc("\n",stdout) (how do we get "stdout"?)
2094//
2095// round, roundf, roundl:
2096// * round(cnst) -> cnst'
2097//
2098// signbit:
2099// * signbit(cnst) -> cnst'
2100// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2101//
Reid Spencer649ac282005-04-28 04:40:06 +00002102// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00002103// * sqrt(expN(x)) -> expN(x*0.5)
2104// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2105// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2106//
Reid Spencer170ae7f2005-05-07 20:15:59 +00002107// stpcpy:
2108// * stpcpy(str, "literal") ->
2109// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer38cabd72005-05-03 07:23:44 +00002110// strrchr:
Reid Spencer649ac282005-04-28 04:40:06 +00002111// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2112// (if c is a constant integer and s is a constant string)
2113// * strrchr(s1,0) -> strchr(s1,0)
2114//
Reid Spencer649ac282005-04-28 04:40:06 +00002115// strncat:
2116// * strncat(x,y,0) -> x
2117// * strncat(x,y,0) -> x (if strlen(y) = 0)
2118// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2119//
Reid Spencer649ac282005-04-28 04:40:06 +00002120// strncpy:
2121// * strncpy(d,s,0) -> d
2122// * strncpy(d,s,l) -> memcpy(d,s,l,1)
2123// (if s and l are constants)
2124//
2125// strpbrk:
2126// * strpbrk(s,a) -> offset_in_for(s,a)
2127// (if s and a are both constant strings)
2128// * strpbrk(s,"") -> 0
2129// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2130//
2131// strspn, strcspn:
2132// * strspn(s,a) -> const_int (if both args are constant)
2133// * strspn("",a) -> 0
2134// * strspn(s,"") -> 0
2135// * strcspn(s,a) -> const_int (if both args are constant)
2136// * strcspn("",a) -> 0
2137// * strcspn(s,"") -> strlen(a)
2138//
2139// strstr:
2140// * strstr(x,x) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002141// * strstr(s1,s2) -> offset_of_s2_in(s1)
Reid Spencer649ac282005-04-28 04:40:06 +00002142// (if s1 and s2 are constant strings)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002143//
Reid Spencer649ac282005-04-28 04:40:06 +00002144// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00002145// * tan(atan(x)) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002146//
Reid Spencer649ac282005-04-28 04:40:06 +00002147// trunc, truncf, truncl:
2148// * trunc(cnst) -> cnst'
2149//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002150//
Reid Spencer39a762d2005-04-25 02:53:12 +00002151}