blob: f5252a02f1bb958fbfda193304e91bdf3072342b [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//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// 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"
Reid Spencerade18212006-01-19 08:36:56 +000028#include "llvm/Config/config.h"
Reid Spencer557ab152007-02-05 23:32:05 +000029#include "llvm/Support/Compiler.h"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000030#include "llvm/Support/Debug.h"
Reid Spencerbb92b4f2005-04-26 19:13:17 +000031#include "llvm/Target/TargetData.h"
Reid Spencer2bc7a4f2005-04-26 23:02:16 +000032#include "llvm/Transforms/IPO.h"
Reid Spencer39a762d2005-04-25 02:53:12 +000033using namespace llvm;
34
Reid Spencere249a822005-04-27 07:54:40 +000035/// This statistic keeps track of the total number of library calls that have
36/// been simplified regardless of which call it is.
Chris Lattner1631bcb2006-12-19 22:09:18 +000037STATISTIC(SimplifiedLibCalls, "Number of library calls simplified");
Reid Spencer39a762d2005-04-25 02:53:12 +000038
Chris Lattner1631bcb2006-12-19 22:09:18 +000039namespace {
40 // Forward declarations
41 class LibCallOptimization;
42 class SimplifyLibCalls;
43
Chris Lattner33081b42006-01-22 23:10:26 +000044/// This list is populated by the constructor for LibCallOptimization class.
Reid Spencer9fbad132005-05-21 01:27:04 +000045/// Therefore all subclasses are registered here at static initialization time
46/// and this list is what the SimplifyLibCalls pass uses to apply the individual
47/// optimizations to the call sites.
Reid Spencer7ddcfb32005-04-27 21:29:20 +000048/// @brief The list of optimizations deriving from LibCallOptimization
Chris Lattner33081b42006-01-22 23:10:26 +000049static LibCallOptimization *OptList = 0;
Reid Spencer39a762d2005-04-25 02:53:12 +000050
Reid Spencere249a822005-04-27 07:54:40 +000051/// This class is the abstract base class for the set of optimizations that
Reid Spencer7ddcfb32005-04-27 21:29:20 +000052/// corresponds to one library call. The SimplifyLibCalls pass will call the
Reid Spencere249a822005-04-27 07:54:40 +000053/// ValidateCalledFunction method to ask the optimization if a given Function
Reid Spencer7ddcfb32005-04-27 21:29:20 +000054/// is the kind that the optimization can handle. If the subclass returns true,
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000055/// then SImplifyLibCalls will also call the OptimizeCall method to perform,
Reid Spencer7ddcfb32005-04-27 21:29:20 +000056/// or attempt to perform, the optimization(s) for the library call. Otherwise,
57/// OptimizeCall won't be called. Subclasses are responsible for providing the
58/// name of the library call (strlen, strcpy, etc.) to the LibCallOptimization
59/// constructor. This is used to efficiently select which call instructions to
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000060/// optimize. The criteria for a "lib call" is "anything with well known
Reid Spencer7ddcfb32005-04-27 21:29:20 +000061/// semantics", typically a library function that is defined by an international
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000062/// standard. Because the semantics are well known, the optimizations can
Reid Spencer7ddcfb32005-04-27 21:29:20 +000063/// generally short-circuit actually calling the function if there's a simpler
64/// way (e.g. strlen(X) can be reduced to a constant if X is a constant global).
Reid Spencere249a822005-04-27 07:54:40 +000065/// @brief Base class for library call optimizations
Reid Spencer557ab152007-02-05 23:32:05 +000066class VISIBILITY_HIDDEN LibCallOptimization {
Chris Lattner33081b42006-01-22 23:10:26 +000067 LibCallOptimization **Prev, *Next;
68 const char *FunctionName; ///< Name of the library call we optimize
69#ifndef NDEBUG
Chris Lattner700b8732006-12-06 17:46:33 +000070 Statistic occurrences; ///< debug statistic (-debug-only=simplify-libcalls)
Chris Lattner33081b42006-01-22 23:10:26 +000071#endif
Jeff Cohen4bc952f2005-04-29 03:05:44 +000072public:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +000073 /// The \p fname argument must be the name of the library function being
Reid Spencer7ddcfb32005-04-27 21:29:20 +000074 /// optimized by the subclass.
75 /// @brief Constructor that registers the optimization.
Chris Lattner33081b42006-01-22 23:10:26 +000076 LibCallOptimization(const char *FName, const char *Description)
Chris Lattner575d3212006-12-19 23:16:47 +000077 : FunctionName(FName) {
78
Reid Spencere95a6472005-04-27 00:05:45 +000079#ifndef NDEBUG
Chris Lattner575d3212006-12-19 23:16:47 +000080 occurrences.construct("simplify-libcalls", Description);
Reid Spencere95a6472005-04-27 00:05:45 +000081#endif
Chris Lattner33081b42006-01-22 23:10:26 +000082 // Register this optimizer in the list of optimizations.
83 Next = OptList;
84 OptList = this;
85 Prev = &OptList;
86 if (Next) Next->Prev = &Next;
Reid Spencer39a762d2005-04-25 02:53:12 +000087 }
Chris Lattner33081b42006-01-22 23:10:26 +000088
89 /// getNext - All libcall optimizations are chained together into a list,
90 /// return the next one in the list.
91 LibCallOptimization *getNext() { return Next; }
Reid Spencer39a762d2005-04-25 02:53:12 +000092
Reid Spencer7ddcfb32005-04-27 21:29:20 +000093 /// @brief Deregister from the optlist
Chris Lattner33081b42006-01-22 23:10:26 +000094 virtual ~LibCallOptimization() {
95 *Prev = Next;
96 if (Next) Next->Prev = Prev;
97 }
Reid Spencer8ee5aac2005-04-26 03:26:15 +000098
Reid Spencere249a822005-04-27 07:54:40 +000099 /// The implementation of this function in subclasses should determine if
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000100 /// \p F is suitable for the optimization. This method is called by
101 /// SimplifyLibCalls::runOnModule to short circuit visiting all the call
102 /// sites of such a function if that function is not suitable in the first
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000103 /// place. If the called function is suitabe, this method should return true;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000104 /// false, otherwise. This function should also perform any lazy
105 /// initialization that the LibCallOptimization needs to do, if its to return
Reid Spencere249a822005-04-27 07:54:40 +0000106 /// true. This avoids doing initialization until the optimizer is actually
107 /// going to be called upon to do some optimization.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000108 /// @brief Determine if the function is suitable for optimization
Reid Spencere249a822005-04-27 07:54:40 +0000109 virtual bool ValidateCalledFunction(
110 const Function* F, ///< The function that is the target of call sites
111 SimplifyLibCalls& SLC ///< The pass object invoking us
112 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000113
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000114 /// The implementations of this function in subclasses is the heart of the
115 /// SimplifyLibCalls algorithm. Sublcasses of this class implement
Reid Spencere249a822005-04-27 07:54:40 +0000116 /// OptimizeCall to determine if (a) the conditions are right for optimizing
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000117 /// the call and (b) to perform the optimization. If an action is taken
Reid Spencere249a822005-04-27 07:54:40 +0000118 /// against ci, the subclass is responsible for returning true and ensuring
119 /// that ci is erased from its parent.
Reid Spencere249a822005-04-27 07:54:40 +0000120 /// @brief Optimize a call, if possible.
121 virtual bool OptimizeCall(
122 CallInst* ci, ///< The call instruction that should be optimized.
123 SimplifyLibCalls& SLC ///< The pass object invoking us
124 ) = 0;
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000125
Reid Spencere249a822005-04-27 07:54:40 +0000126 /// @brief Get the name of the library call being optimized
Chris Lattner33081b42006-01-22 23:10:26 +0000127 const char *getFunctionName() const { return FunctionName; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000128
Chris Lattner485b6412007-04-07 00:42:32 +0000129 bool ReplaceCallWith(CallInst *CI, Value *V) {
130 if (!CI->use_empty())
131 CI->replaceAllUsesWith(V);
132 CI->eraseFromParent();
133 return true;
134 }
135
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000136 /// @brief Called by SimplifyLibCalls to update the occurrences statistic.
Chris Lattner33081b42006-01-22 23:10:26 +0000137 void succeeded() {
Reid Spencere249a822005-04-27 07:54:40 +0000138#ifndef NDEBUG
Chris Lattner33081b42006-01-22 23:10:26 +0000139 DEBUG(++occurrences);
Reid Spencere249a822005-04-27 07:54:40 +0000140#endif
Chris Lattner33081b42006-01-22 23:10:26 +0000141 }
Reid Spencere249a822005-04-27 07:54:40 +0000142};
143
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000144/// This class is an LLVM Pass that applies each of the LibCallOptimization
Reid Spencere249a822005-04-27 07:54:40 +0000145/// instances to all the call sites in a module, relatively efficiently. The
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000146/// purpose of this pass is to provide optimizations for calls to well-known
Reid Spencere249a822005-04-27 07:54:40 +0000147/// functions with well-known semantics, such as those in the c library. The
Chris Lattner4201cd12005-08-24 17:22:17 +0000148/// class provides the basic infrastructure for handling runOnModule. Whenever
149/// this pass finds a function call, it asks the appropriate optimizer to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000150/// validate the call (ValidateLibraryCall). If it is validated, then
151/// the OptimizeCall method is also called.
Reid Spencere249a822005-04-27 07:54:40 +0000152/// @brief A ModulePass for optimizing well-known function calls.
Reid Spencer557ab152007-02-05 23:32:05 +0000153class VISIBILITY_HIDDEN SimplifyLibCalls : public ModulePass {
Jeff Cohen4bc952f2005-04-29 03:05:44 +0000154public:
Nick Lewyckye7da2d62007-05-06 13:37:16 +0000155 static char ID; // Pass identification, replacement for typeid
Devang Patel09f162c2007-05-01 21:15:47 +0000156 SimplifyLibCalls() : ModulePass((intptr_t)&ID) {}
157
Reid Spencere249a822005-04-27 07:54:40 +0000158 /// We need some target data for accurate signature details that are
159 /// target dependent. So we require target data in our AnalysisUsage.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000160 /// @brief Require TargetData from AnalysisUsage.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000161 virtual void getAnalysisUsage(AnalysisUsage& Info) const {
Reid Spencere249a822005-04-27 07:54:40 +0000162 // Ask that the TargetData analysis be performed before us so we can use
163 // the target data.
164 Info.addRequired<TargetData>();
165 }
166
167 /// For this pass, process all of the function calls in the module, calling
168 /// ValidateLibraryCall and OptimizeCall as appropriate.
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000169 /// @brief Run all the lib call optimizations on a Module.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000170 virtual bool runOnModule(Module &M) {
Reid Spencere249a822005-04-27 07:54:40 +0000171 reset(M);
172
173 bool result = false;
Chris Lattner33081b42006-01-22 23:10:26 +0000174 hash_map<std::string, LibCallOptimization*> OptznMap;
175 for (LibCallOptimization *Optzn = OptList; Optzn; Optzn = Optzn->getNext())
176 OptznMap[Optzn->getFunctionName()] = Optzn;
Reid Spencere249a822005-04-27 07:54:40 +0000177
178 // The call optimizations can be recursive. That is, the optimization might
179 // generate a call to another function which can also be optimized. This way
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000180 // we make the LibCallOptimization instances very specific to the case they
181 // handle. It also means we need to keep running over the function calls in
Reid Spencere249a822005-04-27 07:54:40 +0000182 // the module until we don't get any more optimizations possible.
183 bool found_optimization = false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000184 do {
Reid Spencere249a822005-04-27 07:54:40 +0000185 found_optimization = false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000186 for (Module::iterator FI = M.begin(), FE = M.end(); FI != FE; ++FI) {
Reid Spencere249a822005-04-27 07:54:40 +0000187 // All the "well-known" functions are external and have external linkage
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000188 // because they live in a runtime library somewhere and were (probably)
189 // not compiled by LLVM. So, we only act on external functions that
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000190 // have external or dllimport linkage and non-empty uses.
Reid Spencer5301e7c2007-01-30 20:08:39 +0000191 if (!FI->isDeclaration() ||
Anton Korobeynikovd61d39e2006-09-14 18:23:27 +0000192 !(FI->hasExternalLinkage() || FI->hasDLLImportLinkage()) ||
193 FI->use_empty())
Reid Spencere249a822005-04-27 07:54:40 +0000194 continue;
195
196 // Get the optimization class that pertains to this function
Chris Lattner33081b42006-01-22 23:10:26 +0000197 hash_map<std::string, LibCallOptimization*>::iterator OMI =
198 OptznMap.find(FI->getName());
199 if (OMI == OptznMap.end()) continue;
200
201 LibCallOptimization *CO = OMI->second;
Reid Spencere249a822005-04-27 07:54:40 +0000202
203 // Make sure the called function is suitable for the optimization
Chris Lattner33081b42006-01-22 23:10:26 +0000204 if (!CO->ValidateCalledFunction(FI, *this))
Reid Spencere249a822005-04-27 07:54:40 +0000205 continue;
206
207 // Loop over each of the uses of the function
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000208 for (Value::use_iterator UI = FI->use_begin(), UE = FI->use_end();
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000209 UI != UE ; ) {
Reid Spencere249a822005-04-27 07:54:40 +0000210 // If the use of the function is a call instruction
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000211 if (CallInst* CI = dyn_cast<CallInst>(*UI++)) {
Reid Spencere249a822005-04-27 07:54:40 +0000212 // Do the optimization on the LibCallOptimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000213 if (CO->OptimizeCall(CI, *this)) {
Reid Spencere249a822005-04-27 07:54:40 +0000214 ++SimplifiedLibCalls;
215 found_optimization = result = true;
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000216 CO->succeeded();
Reid Spencere249a822005-04-27 07:54:40 +0000217 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000218 }
219 }
220 }
Reid Spencere249a822005-04-27 07:54:40 +0000221 } while (found_optimization);
Chris Lattner33081b42006-01-22 23:10:26 +0000222
Reid Spencere249a822005-04-27 07:54:40 +0000223 return result;
224 }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000225
Reid Spencere249a822005-04-27 07:54:40 +0000226 /// @brief Return the *current* module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000227 Module* getModule() const { return M; }
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000228
Reid Spencere249a822005-04-27 07:54:40 +0000229 /// @brief Return the *current* target data for the module we're working on.
Reid Spencer93616972005-04-29 09:39:47 +0000230 TargetData* getTargetData() const { return TD; }
231
232 /// @brief Return the size_t type -- syntactic shortcut
233 const Type* getIntPtrType() const { return TD->getIntPtrType(); }
234
Evan Cheng1fc40252006-06-16 08:36:35 +0000235 /// @brief Return a Function* for the putchar libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000236 Constant *get_putchar() {
Evan Cheng1fc40252006-06-16 08:36:35 +0000237 if (!putchar_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000238 putchar_func =
239 M->getOrInsertFunction("putchar", Type::Int32Ty, Type::Int32Ty, NULL);
Evan Cheng1fc40252006-06-16 08:36:35 +0000240 return putchar_func;
241 }
242
243 /// @brief Return a Function* for the puts libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000244 Constant *get_puts() {
Evan Cheng1fc40252006-06-16 08:36:35 +0000245 if (!puts_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000246 puts_func = M->getOrInsertFunction("puts", Type::Int32Ty,
Christopher Lambedf07882007-12-17 01:12:55 +0000247 PointerType::getUnqual(Type::Int8Ty),
Evan Cheng1fc40252006-06-16 08:36:35 +0000248 NULL);
249 return puts_func;
250 }
251
Reid Spencer93616972005-04-29 09:39:47 +0000252 /// @brief Return a Function* for the fputc libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000253 Constant *get_fputc(const Type* FILEptr_type) {
Reid Spencer93616972005-04-29 09:39:47 +0000254 if (!fputc_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000255 fputc_func = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000256 FILEptr_type, NULL);
Reid Spencer93616972005-04-29 09:39:47 +0000257 return fputc_func;
258 }
259
Evan Chengf2ea5872006-06-16 04:52:30 +0000260 /// @brief Return a Function* for the fputs libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000261 Constant *get_fputs(const Type* FILEptr_type) {
Evan Chengf2ea5872006-06-16 04:52:30 +0000262 if (!fputs_func)
Reid Spencerc635f472006-12-31 05:48:39 +0000263 fputs_func = M->getOrInsertFunction("fputs", Type::Int32Ty,
Christopher Lambedf07882007-12-17 01:12:55 +0000264 PointerType::getUnqual(Type::Int8Ty),
Evan Chengf2ea5872006-06-16 04:52:30 +0000265 FILEptr_type, NULL);
266 return fputs_func;
267 }
268
Reid Spencer93616972005-04-29 09:39:47 +0000269 /// @brief Return a Function* for the fwrite libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000270 Constant *get_fwrite(const Type* FILEptr_type) {
Reid Spencer93616972005-04-29 09:39:47 +0000271 if (!fwrite_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000272 fwrite_func = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
Christopher Lambedf07882007-12-17 01:12:55 +0000273 PointerType::getUnqual(Type::Int8Ty),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000274 TD->getIntPtrType(),
275 TD->getIntPtrType(),
276 FILEptr_type, NULL);
Reid Spencer93616972005-04-29 09:39:47 +0000277 return fwrite_func;
278 }
279
280 /// @brief Return a Function* for the sqrt libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000281 Constant *get_sqrt() {
Reid Spencer93616972005-04-29 09:39:47 +0000282 if (!sqrt_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000283 sqrt_func = M->getOrInsertFunction("sqrt", Type::DoubleTy,
284 Type::DoubleTy, NULL);
Reid Spencer93616972005-04-29 09:39:47 +0000285 return sqrt_func;
286 }
Reid Spencere249a822005-04-27 07:54:40 +0000287
Owen Andersondfd79ad2007-01-20 10:07:23 +0000288 /// @brief Return a Function* for the strcpy libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000289 Constant *get_strcpy() {
Reid Spencer1e520fd2005-05-04 03:20:21 +0000290 if (!strcpy_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000291 strcpy_func = M->getOrInsertFunction("strcpy",
Christopher Lambedf07882007-12-17 01:12:55 +0000292 PointerType::getUnqual(Type::Int8Ty),
293 PointerType::getUnqual(Type::Int8Ty),
294 PointerType::getUnqual(Type::Int8Ty),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000295 NULL);
Reid Spencer1e520fd2005-05-04 03:20:21 +0000296 return strcpy_func;
297 }
298
299 /// @brief Return a Function* for the strlen libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000300 Constant *get_strlen() {
Reid Spencere249a822005-04-27 07:54:40 +0000301 if (!strlen_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000302 strlen_func = M->getOrInsertFunction("strlen", TD->getIntPtrType(),
Christopher Lambedf07882007-12-17 01:12:55 +0000303 PointerType::getUnqual(Type::Int8Ty),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000304 NULL);
Reid Spencere249a822005-04-27 07:54:40 +0000305 return strlen_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000306 }
307
Reid Spencer38cabd72005-05-03 07:23:44 +0000308 /// @brief Return a Function* for the memchr libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000309 Constant *get_memchr() {
Reid Spencer38cabd72005-05-03 07:23:44 +0000310 if (!memchr_func)
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000311 memchr_func = M->getOrInsertFunction("memchr",
Christopher Lambedf07882007-12-17 01:12:55 +0000312 PointerType::getUnqual(Type::Int8Ty),
313 PointerType::getUnqual(Type::Int8Ty),
Reid Spencerc635f472006-12-31 05:48:39 +0000314 Type::Int32Ty, TD->getIntPtrType(),
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000315 NULL);
Reid Spencer38cabd72005-05-03 07:23:44 +0000316 return memchr_func;
317 }
318
Reid Spencere249a822005-04-27 07:54:40 +0000319 /// @brief Return a Function* for the memcpy libcall
Chris Lattner34acba42007-01-07 08:12:01 +0000320 Constant *get_memcpy() {
Chris Lattner4201cd12005-08-24 17:22:17 +0000321 if (!memcpy_func) {
Christopher Lambedf07882007-12-17 01:12:55 +0000322 const Type *SBP = PointerType::getUnqual(Type::Int8Ty);
Reid Spencerc635f472006-12-31 05:48:39 +0000323 const char *N = TD->getIntPtrType() == Type::Int32Ty ?
Chris Lattnerea7986a2006-03-03 01:30:23 +0000324 "llvm.memcpy.i32" : "llvm.memcpy.i64";
325 memcpy_func = M->getOrInsertFunction(N, Type::VoidTy, SBP, SBP,
Reid Spencerc635f472006-12-31 05:48:39 +0000326 TD->getIntPtrType(), Type::Int32Ty,
Chris Lattnerea7986a2006-03-03 01:30:23 +0000327 NULL);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000328 }
Reid Spencere249a822005-04-27 07:54:40 +0000329 return memcpy_func;
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000330 }
Reid Spencer76dab9a2005-04-26 05:24:00 +0000331
Chris Lattner34acba42007-01-07 08:12:01 +0000332 Constant *getUnaryFloatFunction(const char *Name, Constant *&Cache) {
Chris Lattner57740402006-01-23 06:24:46 +0000333 if (!Cache)
334 Cache = M->getOrInsertFunction(Name, Type::FloatTy, Type::FloatTy, NULL);
335 return Cache;
Chris Lattner4201cd12005-08-24 17:22:17 +0000336 }
337
Chris Lattner34acba42007-01-07 08:12:01 +0000338 Constant *get_floorf() { return getUnaryFloatFunction("floorf", floorf_func);}
339 Constant *get_ceilf() { return getUnaryFloatFunction( "ceilf", ceilf_func);}
340 Constant *get_roundf() { return getUnaryFloatFunction("roundf", roundf_func);}
341 Constant *get_rintf() { return getUnaryFloatFunction( "rintf", rintf_func);}
342 Constant *get_nearbyintf() { return getUnaryFloatFunction("nearbyintf",
Chris Lattner57740402006-01-23 06:24:46 +0000343 nearbyintf_func); }
Reid Spencere249a822005-04-27 07:54:40 +0000344private:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000345 /// @brief Reset our cached data for a new Module
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000346 void reset(Module& mod) {
Reid Spencere249a822005-04-27 07:54:40 +0000347 M = &mod;
348 TD = &getAnalysis<TargetData>();
Evan Cheng1fc40252006-06-16 08:36:35 +0000349 putchar_func = 0;
350 puts_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000351 fputc_func = 0;
Evan Chengf2ea5872006-06-16 04:52:30 +0000352 fputs_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000353 fwrite_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000354 memcpy_func = 0;
Reid Spencer38cabd72005-05-03 07:23:44 +0000355 memchr_func = 0;
Reid Spencer93616972005-04-29 09:39:47 +0000356 sqrt_func = 0;
Reid Spencer1e520fd2005-05-04 03:20:21 +0000357 strcpy_func = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000358 strlen_func = 0;
Chris Lattner4201cd12005-08-24 17:22:17 +0000359 floorf_func = 0;
Chris Lattner57740402006-01-23 06:24:46 +0000360 ceilf_func = 0;
361 roundf_func = 0;
362 rintf_func = 0;
363 nearbyintf_func = 0;
Reid Spencer76dab9a2005-04-26 05:24:00 +0000364 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000365
Reid Spencere249a822005-04-27 07:54:40 +0000366private:
Chris Lattner57740402006-01-23 06:24:46 +0000367 /// Caches for function pointers.
Chris Lattner34acba42007-01-07 08:12:01 +0000368 Constant *putchar_func, *puts_func;
369 Constant *fputc_func, *fputs_func, *fwrite_func;
370 Constant *memcpy_func, *memchr_func;
371 Constant *sqrt_func;
372 Constant *strcpy_func, *strlen_func;
373 Constant *floorf_func, *ceilf_func, *roundf_func;
374 Constant *rintf_func, *nearbyintf_func;
Chris Lattner57740402006-01-23 06:24:46 +0000375 Module *M; ///< Cached Module
376 TargetData *TD; ///< Cached TargetData
Reid Spencere249a822005-04-27 07:54:40 +0000377};
378
Devang Patel8c78a0b2007-05-03 01:11:54 +0000379char SimplifyLibCalls::ID = 0;
Reid Spencere249a822005-04-27 07:54:40 +0000380// Register the pass
Chris Lattnerc2d3d312006-08-27 22:42:52 +0000381RegisterPass<SimplifyLibCalls>
382X("simplify-libcalls", "Simplify well-known library calls");
Reid Spencere249a822005-04-27 07:54:40 +0000383
384} // anonymous namespace
385
386// The only public symbol in this file which just instantiates the pass object
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000387ModulePass *llvm::createSimplifyLibCallsPass() {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000388 return new SimplifyLibCalls();
Reid Spencere249a822005-04-27 07:54:40 +0000389}
390
391// Classes below here, in the anonymous namespace, are all subclasses of the
392// LibCallOptimization class, each implementing all optimizations possible for a
393// single well-known library call. Each has a static singleton instance that
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000394// auto registers it into the "optlist" global above.
Reid Spencere249a822005-04-27 07:54:40 +0000395namespace {
396
Reid Spencera7828ba2005-06-18 17:46:28 +0000397// Forward declare utility functions.
Chris Lattner182a9452007-04-07 21:58:02 +0000398static bool GetConstantStringInfo(Value *V, std::string &Str);
Chris Lattnerbed184c2007-04-07 21:04:50 +0000399static Value *CastToCStr(Value *V, Instruction *IP);
Reid Spencere249a822005-04-27 07:54:40 +0000400
401/// This LibCallOptimization will find instances of a call to "exit" that occurs
Reid Spencer39a762d2005-04-25 02:53:12 +0000402/// within the "main" function and change it to a simple "ret" instruction with
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000403/// the same value passed to the exit function. When this is done, it splits the
404/// basic block at the exit(3) call and deletes the call instruction.
Reid Spencer39a762d2005-04-25 02:53:12 +0000405/// @brief Replace calls to exit in main with a simple return
Reid Spencer557ab152007-02-05 23:32:05 +0000406struct VISIBILITY_HIDDEN ExitInMainOptimization : public LibCallOptimization {
Reid Spencer95d8efd2005-05-03 02:54:54 +0000407 ExitInMainOptimization() : LibCallOptimization("exit",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000408 "Number of 'exit' calls simplified") {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000409
410 // Make sure the called function looks like exit (int argument, int return
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000411 // type, external linkage, not varargs).
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000412 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner03c49532007-01-15 02:27:26 +0000413 return F->arg_size() >= 1 && F->arg_begin()->getType()->isInteger();
Reid Spencerf2534c72005-04-25 21:11:48 +0000414 }
415
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000416 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& SLC) {
Reid Spencerf2534c72005-04-25 21:11:48 +0000417 // To be careful, we check that the call to exit is coming from "main", that
418 // main has external linkage, and the return type of main and the argument
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000419 // to exit have the same type.
Reid Spencerf2534c72005-04-25 21:11:48 +0000420 Function *from = ci->getParent()->getParent();
421 if (from->hasExternalLinkage())
422 if (from->getReturnType() == ci->getOperand(1)->getType())
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000423 if (from->getName() == "main") {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000424 // Okay, time to actually do the optimization. First, get the basic
Reid Spencerf2534c72005-04-25 21:11:48 +0000425 // block of the call instruction
426 BasicBlock* bb = ci->getParent();
Reid Spencer39a762d2005-04-25 02:53:12 +0000427
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000428 // Create a return instruction that we'll replace the call with.
429 // Note that the argument of the return is the argument of the call
Reid Spencerf2534c72005-04-25 21:11:48 +0000430 // instruction.
Chris Lattnercd60d382006-05-12 23:35:26 +0000431 new ReturnInst(ci->getOperand(1), ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000432
Reid Spencerf2534c72005-04-25 21:11:48 +0000433 // Split the block at the call instruction which places it in a new
434 // basic block.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000435 bb->splitBasicBlock(ci);
Reid Spencer39a762d2005-04-25 02:53:12 +0000436
Reid Spencerf2534c72005-04-25 21:11:48 +0000437 // The block split caused a branch instruction to be inserted into
438 // the end of the original block, right after the return instruction
439 // that we put there. That's not a valid block, so delete the branch
440 // instruction.
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000441 bb->getInstList().pop_back();
Reid Spencer39a762d2005-04-25 02:53:12 +0000442
Reid Spencerf2534c72005-04-25 21:11:48 +0000443 // Now we can finally get rid of the call instruction which now lives
444 // in the new basic block.
445 ci->eraseFromParent();
446
447 // Optimization succeeded, return true.
448 return true;
449 }
450 // We didn't pass the criteria for this optimization so return false
451 return false;
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000452 }
Reid Spencer39a762d2005-04-25 02:53:12 +0000453} ExitInMainOptimizer;
454
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000455/// This LibCallOptimization will simplify a call to the strcat library
456/// function. The simplification is possible only if the string being
457/// concatenated is a constant array or a constant expression that results in
458/// a constant string. In this case we can replace it with strlen + llvm.memcpy
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000459/// of the constant string. Both of these calls are further reduced, if possible
460/// on subsequent passes.
Reid Spencerf2534c72005-04-25 21:11:48 +0000461/// @brief Simplify the strcat library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000462struct VISIBILITY_HIDDEN StrCatOptimization : public LibCallOptimization {
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000463public:
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000464 /// @brief Default constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +0000465 StrCatOptimization() : LibCallOptimization("strcat",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000466 "Number of 'strcat' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000467
468public:
Reid Spencerf2534c72005-04-25 21:11:48 +0000469
470 /// @brief Make sure that the "strcat" function has the right prototype
Chris Lattner182a9452007-04-07 21:58:02 +0000471 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
472 const FunctionType *FT = F->getFunctionType();
473 return FT->getNumParams() == 2 &&
Christopher Lambedf07882007-12-17 01:12:55 +0000474 FT->getReturnType() == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner182a9452007-04-07 21:58:02 +0000475 FT->getParamType(0) == FT->getReturnType() &&
476 FT->getParamType(1) == FT->getReturnType();
Reid Spencerf2534c72005-04-25 21:11:48 +0000477 }
478
Reid Spencere249a822005-04-27 07:54:40 +0000479 /// @brief Optimize the strcat library function
Chris Lattner56b7fc72007-04-06 22:59:33 +0000480 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer08b49402005-04-27 17:46:54 +0000481 // Extract some information from the instruction
Chris Lattner56b7fc72007-04-06 22:59:33 +0000482 Value *Dst = CI->getOperand(1);
483 Value *Src = CI->getOperand(2);
Reid Spencer08b49402005-04-27 17:46:54 +0000484
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000485 // Extract the initializer (while making numerous checks) from the
Chris Lattner56b7fc72007-04-06 22:59:33 +0000486 // source operand of the call to strcat.
Chris Lattner182a9452007-04-07 21:58:02 +0000487 std::string SrcStr;
488 if (!GetConstantStringInfo(Src, SrcStr))
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000489 return false;
490
Reid Spencerb4f7b832005-04-26 07:45:18 +0000491 // Handle the simple, do-nothing case
Chris Lattner182a9452007-04-07 21:58:02 +0000492 if (SrcStr.empty())
Chris Lattner485b6412007-04-07 00:42:32 +0000493 return ReplaceCallWith(CI, Dst);
Reid Spencer8ee5aac2005-04-26 03:26:15 +0000494
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000495 // We need to find the end of the destination string. That's where the
Chris Lattner182a9452007-04-07 21:58:02 +0000496 // memory is to be moved to. We just generate a call to strlen.
Chris Lattner56b7fc72007-04-06 22:59:33 +0000497 CallInst *DstLen = new CallInst(SLC.get_strlen(), Dst,
498 Dst->getName()+".len", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000499
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000500 // Now that we have the destination's length, we must index into the
Reid Spencerb4f7b832005-04-26 07:45:18 +0000501 // destination's pointer to get the actual memcpy destination (end of
502 // the string .. we're concatenating).
Chris Lattner56b7fc72007-04-06 22:59:33 +0000503 Dst = new GetElementPtrInst(Dst, DstLen, Dst->getName()+".indexed", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000504
505 // We have enough information to now generate the memcpy call to
506 // do the concatenation for us.
Chris Lattner56b7fc72007-04-06 22:59:33 +0000507 Value *Vals[] = {
508 Dst, Src,
Chris Lattner182a9452007-04-07 21:58:02 +0000509 ConstantInt::get(SLC.getIntPtrType(), SrcStr.size()+1), // copy nul byte.
Chris Lattner56b7fc72007-04-06 22:59:33 +0000510 ConstantInt::get(Type::Int32Ty, 1) // alignment
511 };
David Greene17a5dfe2007-08-01 03:43:44 +0000512 new CallInst(SLC.get_memcpy(), Vals, Vals + 4, "", CI);
Reid Spencerb4f7b832005-04-26 07:45:18 +0000513
Chris Lattner485b6412007-04-07 00:42:32 +0000514 return ReplaceCallWith(CI, Dst);
Reid Spencer9bbaa2a2005-04-25 03:59:26 +0000515 }
516} StrCatOptimizer;
517
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000518/// This LibCallOptimization will simplify a call to the strchr library
Reid Spencer38cabd72005-05-03 07:23:44 +0000519/// function. It optimizes out cases where the arguments are both constant
520/// and the result can be determined statically.
521/// @brief Simplify the strcmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000522struct VISIBILITY_HIDDEN StrChrOptimization : public LibCallOptimization {
Reid Spencer38cabd72005-05-03 07:23:44 +0000523public:
524 StrChrOptimization() : LibCallOptimization("strchr",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000525 "Number of 'strchr' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +0000526
527 /// @brief Make sure that the "strchr" function has the right prototype
Chris Lattner39f0bb92007-04-06 23:38:55 +0000528 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
529 const FunctionType *FT = F->getFunctionType();
530 return FT->getNumParams() == 2 &&
Christopher Lambedf07882007-12-17 01:12:55 +0000531 FT->getReturnType() == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner39f0bb92007-04-06 23:38:55 +0000532 FT->getParamType(0) == FT->getReturnType() &&
533 isa<IntegerType>(FT->getParamType(1));
Reid Spencer38cabd72005-05-03 07:23:44 +0000534 }
535
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000536 /// @brief Perform the strchr optimizations
Chris Lattner39f0bb92007-04-06 23:38:55 +0000537 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer38cabd72005-05-03 07:23:44 +0000538 // Check that the first argument to strchr is a constant array of sbyte.
Chris Lattner182a9452007-04-07 21:58:02 +0000539 std::string Str;
540 if (!GetConstantStringInfo(CI->getOperand(1), Str))
Reid Spencer38cabd72005-05-03 07:23:44 +0000541 return false;
542
Chris Lattner39f0bb92007-04-06 23:38:55 +0000543 // If the second operand is not constant, just lower this to memchr since we
544 // know the length of the input string.
545 ConstantInt *CSI = dyn_cast<ConstantInt>(CI->getOperand(2));
Reid Spencerc635f472006-12-31 05:48:39 +0000546 if (!CSI) {
Chris Lattner39f0bb92007-04-06 23:38:55 +0000547 Value *Args[3] = {
548 CI->getOperand(1),
549 CI->getOperand(2),
Chris Lattner182a9452007-04-07 21:58:02 +0000550 ConstantInt::get(SLC.getIntPtrType(), Str.size()+1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +0000551 };
David Greene17a5dfe2007-08-01 03:43:44 +0000552 return ReplaceCallWith(CI, new CallInst(SLC.get_memchr(), Args, Args + 3,
Chris Lattner485b6412007-04-07 00:42:32 +0000553 CI->getName(), CI));
Reid Spencer38cabd72005-05-03 07:23:44 +0000554 }
555
Chris Lattner182a9452007-04-07 21:58:02 +0000556 // strchr can find the nul character.
557 Str += '\0';
Chris Lattner39f0bb92007-04-06 23:38:55 +0000558
Chris Lattner182a9452007-04-07 21:58:02 +0000559 // Get the character we're looking for
560 char CharValue = CSI->getSExtValue();
561
Reid Spencer38cabd72005-05-03 07:23:44 +0000562 // Compute the offset
Chris Lattner39f0bb92007-04-06 23:38:55 +0000563 uint64_t i = 0;
564 while (1) {
Chris Lattner182a9452007-04-07 21:58:02 +0000565 if (i == Str.size()) // Didn't find the char. strchr returns null.
566 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
567 // Did we find our match?
568 if (Str[i] == CharValue)
569 break;
Chris Lattner39f0bb92007-04-06 23:38:55 +0000570 ++i;
Reid Spencer38cabd72005-05-03 07:23:44 +0000571 }
572
Chris Lattner39f0bb92007-04-06 23:38:55 +0000573 // strchr(s+n,c) -> gep(s+n+i,c)
Reid Spencer38cabd72005-05-03 07:23:44 +0000574 // (if c is a constant integer and s is a constant string)
Chris Lattner39f0bb92007-04-06 23:38:55 +0000575 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
576 Value *GEP = new GetElementPtrInst(CI->getOperand(1), Idx,
577 CI->getOperand(1)->getName() +
578 ".strchr", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000579 return ReplaceCallWith(CI, GEP);
Reid Spencer38cabd72005-05-03 07:23:44 +0000580 }
581} StrChrOptimizer;
582
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000583/// This LibCallOptimization will simplify a call to the strcmp library
Reid Spencer4c444fe2005-04-30 03:17:54 +0000584/// function. It optimizes out cases where one or both arguments are constant
585/// and the result can be determined statically.
586/// @brief Simplify the strcmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000587struct VISIBILITY_HIDDEN StrCmpOptimization : public LibCallOptimization {
Reid Spencer4c444fe2005-04-30 03:17:54 +0000588public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000589 StrCmpOptimization() : LibCallOptimization("strcmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000590 "Number of 'strcmp' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +0000591
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000592 /// @brief Make sure that the "strcmp" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000593 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000594 const FunctionType *FT = F->getFunctionType();
595 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 2 &&
596 FT->getParamType(0) == FT->getParamType(1) &&
Christopher Lambedf07882007-12-17 01:12:55 +0000597 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000598 }
599
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000600 /// @brief Perform the strcmp optimization
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000601 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer4c444fe2005-04-30 03:17:54 +0000602 // First, check to see if src and destination are the same. If they are,
Reid Spencer16449a92005-04-30 06:45:47 +0000603 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000604 // because the call is a no-op.
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000605 Value *Str1P = CI->getOperand(1);
606 Value *Str2P = CI->getOperand(2);
Chris Lattner485b6412007-04-07 00:42:32 +0000607 if (Str1P == Str2P) // strcmp(x,x) -> 0
608 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Reid Spencer4c444fe2005-04-30 03:17:54 +0000609
Chris Lattner182a9452007-04-07 21:58:02 +0000610 std::string Str1;
611 if (!GetConstantStringInfo(Str1P, Str1))
612 return false;
613 if (Str1.empty()) {
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000614 // strcmp("", x) -> *x
615 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
616 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000617 return ReplaceCallWith(CI, V);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000618 }
619
Chris Lattner182a9452007-04-07 21:58:02 +0000620 std::string Str2;
621 if (!GetConstantStringInfo(Str2P, Str2))
622 return false;
623 if (Str2.empty()) {
Chris Lattnerc9ccc302007-04-07 00:01:51 +0000624 // strcmp(x,"") -> *x
625 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
626 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000627 return ReplaceCallWith(CI, V);
Reid Spencer4c444fe2005-04-30 03:17:54 +0000628 }
629
Chris Lattner182a9452007-04-07 21:58:02 +0000630 // strcmp(x, y) -> cnst (if both x and y are constant strings)
631 int R = strcmp(Str1.c_str(), Str2.c_str());
632 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencer4c444fe2005-04-30 03:17:54 +0000633 }
634} StrCmpOptimizer;
635
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000636/// This LibCallOptimization will simplify a call to the strncmp library
Reid Spencer49fa07042005-05-03 01:43:45 +0000637/// function. It optimizes out cases where one or both arguments are constant
638/// and the result can be determined statically.
639/// @brief Simplify the strncmp library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000640struct VISIBILITY_HIDDEN StrNCmpOptimization : public LibCallOptimization {
Reid Spencer49fa07042005-05-03 01:43:45 +0000641public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000642 StrNCmpOptimization() : LibCallOptimization("strncmp",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000643 "Number of 'strncmp' calls simplified") {}
Reid Spencer49fa07042005-05-03 01:43:45 +0000644
Chris Lattnerf8053ce2005-05-20 22:22:25 +0000645 /// @brief Make sure that the "strncmp" function has the right prototype
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000646 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
647 const FunctionType *FT = F->getFunctionType();
648 return FT->getReturnType() == Type::Int32Ty && FT->getNumParams() == 3 &&
649 FT->getParamType(0) == FT->getParamType(1) &&
Christopher Lambedf07882007-12-17 01:12:55 +0000650 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000651 isa<IntegerType>(FT->getParamType(2));
Reid Spencer49fa07042005-05-03 01:43:45 +0000652 return false;
653 }
654
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000655 /// @brief Perform the strncmp optimization
656 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer49fa07042005-05-03 01:43:45 +0000657 // First, check to see if src and destination are the same. If they are,
658 // then the optimization is to replace the CallInst with a constant 0
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000659 // because the call is a no-op.
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000660 Value *Str1P = CI->getOperand(1);
661 Value *Str2P = CI->getOperand(2);
Chris Lattner182a9452007-04-07 21:58:02 +0000662 if (Str1P == Str2P) // strncmp(x,x, n) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000663 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000664
Reid Spencer49fa07042005-05-03 01:43:45 +0000665 // Check the length argument, if it is Constant zero then the strings are
666 // considered equal.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000667 uint64_t Length;
668 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
669 Length = LengthArg->getZExtValue();
670 else
671 return false;
672
Chris Lattner182a9452007-04-07 21:58:02 +0000673 if (Length == 0) // strncmp(x,y,0) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000674 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000675
Chris Lattner182a9452007-04-07 21:58:02 +0000676 std::string Str1;
677 if (!GetConstantStringInfo(Str1P, Str1))
678 return false;
679 if (Str1.empty()) {
680 // strncmp("", x, n) -> *x
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000681 Value *V = new LoadInst(Str2P, CI->getName()+".load", CI);
682 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000683 return ReplaceCallWith(CI, V);
Reid Spencer49fa07042005-05-03 01:43:45 +0000684 }
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000685
Chris Lattner182a9452007-04-07 21:58:02 +0000686 std::string Str2;
687 if (!GetConstantStringInfo(Str2P, Str2))
688 return false;
689 if (Str2.empty()) {
690 // strncmp(x, "", n) -> *x
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000691 Value *V = new LoadInst(Str1P, CI->getName()+".load", CI);
692 V = new ZExtInst(V, CI->getType(), CI->getName()+".int", CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000693 return ReplaceCallWith(CI, V);
Reid Spencer49fa07042005-05-03 01:43:45 +0000694 }
Chris Lattnerf9ee6472007-04-07 00:06:57 +0000695
Chris Lattner182a9452007-04-07 21:58:02 +0000696 // strncmp(x, y, n) -> cnst (if both x and y are constant strings)
697 int R = strncmp(Str1.c_str(), Str2.c_str(), Length);
698 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), R));
Reid Spencer49fa07042005-05-03 01:43:45 +0000699 }
700} StrNCmpOptimizer;
701
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000702/// This LibCallOptimization will simplify a call to the strcpy library
703/// function. Two optimizations are possible:
Reid Spencere249a822005-04-27 07:54:40 +0000704/// (1) If src and dest are the same and not volatile, just return dest
705/// (2) If the src is a constant then we can convert to llvm.memmove
706/// @brief Simplify the strcpy library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000707struct VISIBILITY_HIDDEN StrCpyOptimization : public LibCallOptimization {
Reid Spencere249a822005-04-27 07:54:40 +0000708public:
Reid Spencer95d8efd2005-05-03 02:54:54 +0000709 StrCpyOptimization() : LibCallOptimization("strcpy",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000710 "Number of 'strcpy' calls simplified") {}
Reid Spencere249a822005-04-27 07:54:40 +0000711
712 /// @brief Make sure that the "strcpy" function has the right prototype
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000713 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
714 const FunctionType *FT = F->getFunctionType();
715 return FT->getNumParams() == 2 &&
716 FT->getParamType(0) == FT->getParamType(1) &&
717 FT->getReturnType() == FT->getParamType(0) &&
Christopher Lambedf07882007-12-17 01:12:55 +0000718 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty);
Reid Spencere249a822005-04-27 07:54:40 +0000719 }
720
721 /// @brief Perform the strcpy optimization
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000722 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencere249a822005-04-27 07:54:40 +0000723 // First, check to see if src and destination are the same. If they are,
724 // then the optimization is to replace the CallInst with the destination
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000725 // because the call is a no-op. Note that this corresponds to the
Reid Spencere249a822005-04-27 07:54:40 +0000726 // degenerate strcpy(X,X) case which should have "undefined" results
727 // according to the C specification. However, it occurs sometimes and
728 // we optimize it as a no-op.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000729 Value *Dst = CI->getOperand(1);
730 Value *Src = CI->getOperand(2);
731 if (Dst == Src) {
732 // strcpy(x, x) -> x
Chris Lattner485b6412007-04-07 00:42:32 +0000733 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000734 }
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000735
736 // Get the length of the constant string referenced by the Src operand.
Chris Lattner182a9452007-04-07 21:58:02 +0000737 std::string SrcStr;
738 if (!GetConstantStringInfo(Src, SrcStr))
Reid Spencere249a822005-04-27 07:54:40 +0000739 return false;
Chris Lattner182a9452007-04-07 21:58:02 +0000740
Reid Spencere249a822005-04-27 07:54:40 +0000741 // If the constant string's length is zero we can optimize this by just
742 // doing a store of 0 at the first byte of the destination
Dan Gohman70de4cb2008-01-29 13:02:09 +0000743 if (SrcStr.empty()) {
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000744 new StoreInst(ConstantInt::get(Type::Int8Ty, 0), Dst, CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000745 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000746 }
747
Reid Spencere249a822005-04-27 07:54:40 +0000748 // We have enough information to now generate the memcpy call to
749 // do the concatenation for us.
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000750 Value *MemcpyOps[] = {
Chris Lattner182a9452007-04-07 21:58:02 +0000751 Dst, Src, // Pass length including nul byte.
752 ConstantInt::get(SLC.getIntPtrType(), SrcStr.size()+1),
Chris Lattnerade1c2b2007-02-13 05:58:53 +0000753 ConstantInt::get(Type::Int32Ty, 1) // alignment
754 };
David Greene17a5dfe2007-08-01 03:43:44 +0000755 new CallInst(SLC.get_memcpy(), MemcpyOps, MemcpyOps + 4, "", CI);
Reid Spencere249a822005-04-27 07:54:40 +0000756
Chris Lattner485b6412007-04-07 00:42:32 +0000757 return ReplaceCallWith(CI, Dst);
Reid Spencere249a822005-04-27 07:54:40 +0000758 }
759} StrCpyOptimizer;
760
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000761/// This LibCallOptimization will simplify a call to the strlen library
762/// function by replacing it with a constant value if the string provided to
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000763/// it is a constant array.
Reid Spencer76dab9a2005-04-26 05:24:00 +0000764/// @brief Simplify the strlen library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000765struct VISIBILITY_HIDDEN StrLenOptimization : public LibCallOptimization {
Reid Spencer95d8efd2005-05-03 02:54:54 +0000766 StrLenOptimization() : LibCallOptimization("strlen",
Reid Spencer170ae7f2005-05-07 20:15:59 +0000767 "Number of 'strlen' calls simplified") {}
Reid Spencer76dab9a2005-04-26 05:24:00 +0000768
769 /// @brief Make sure that the "strlen" function has the right prototype
Chris Lattner6a6c1f12007-04-07 00:26:18 +0000770 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattnere8829aa2007-04-07 01:02:00 +0000771 const FunctionType *FT = F->getFunctionType();
772 return FT->getNumParams() == 1 &&
Christopher Lambedf07882007-12-17 01:12:55 +0000773 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattnere8829aa2007-04-07 01:02:00 +0000774 isa<IntegerType>(FT->getReturnType());
Reid Spencer76dab9a2005-04-26 05:24:00 +0000775 }
776
777 /// @brief Perform the strlen optimization
Chris Lattnere8829aa2007-04-07 01:02:00 +0000778 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000779 // Make sure we're dealing with an sbyte* here.
Chris Lattner182a9452007-04-07 21:58:02 +0000780 Value *Src = CI->getOperand(1);
Reid Spencer170ae7f2005-05-07 20:15:59 +0000781
782 // Does the call to strlen have exactly one use?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000783 if (CI->hasOneUse()) {
Reid Spencer266e42b2006-12-23 06:05:41 +0000784 // Is that single use a icmp operator?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000785 if (ICmpInst *Cmp = dyn_cast<ICmpInst>(CI->use_back()))
Reid Spencer170ae7f2005-05-07 20:15:59 +0000786 // Is it compared against a constant integer?
Chris Lattnere8829aa2007-04-07 01:02:00 +0000787 if (ConstantInt *Cst = dyn_cast<ConstantInt>(Cmp->getOperand(1))) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000788 // If its compared against length 0 with == or !=
Chris Lattnere8829aa2007-04-07 01:02:00 +0000789 if (Cst->getZExtValue() == 0 && Cmp->isEquality()) {
Reid Spencer170ae7f2005-05-07 20:15:59 +0000790 // strlen(x) != 0 -> *x != 0
791 // strlen(x) == 0 -> *x == 0
Chris Lattner182a9452007-04-07 21:58:02 +0000792 Value *V = new LoadInst(Src, Src->getName()+".first", CI);
Chris Lattnere8829aa2007-04-07 01:02:00 +0000793 V = new ICmpInst(Cmp->getPredicate(), V,
794 ConstantInt::get(Type::Int8Ty, 0),
795 Cmp->getName()+".strlen", CI);
796 Cmp->replaceAllUsesWith(V);
797 Cmp->eraseFromParent();
798 return ReplaceCallWith(CI, 0); // no uses.
Reid Spencer170ae7f2005-05-07 20:15:59 +0000799 }
800 }
Chris Lattnere8829aa2007-04-07 01:02:00 +0000801 }
Reid Spencer170ae7f2005-05-07 20:15:59 +0000802
803 // Get the length of the constant string operand
Chris Lattner182a9452007-04-07 21:58:02 +0000804 std::string Str;
805 if (!GetConstantStringInfo(Src, Str))
Reid Spencer76dab9a2005-04-26 05:24:00 +0000806 return false;
Chris Lattner182a9452007-04-07 21:58:02 +0000807
Reid Spencer170ae7f2005-05-07 20:15:59 +0000808 // strlen("xyz") -> 3 (for example)
Chris Lattner182a9452007-04-07 21:58:02 +0000809 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), Str.size()));
Reid Spencer76dab9a2005-04-26 05:24:00 +0000810 }
811} StrLenOptimizer;
812
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000813/// IsOnlyUsedInEqualsComparison - Return true if it only matters that the value
814/// is equal or not-equal to zero.
815static bool IsOnlyUsedInEqualsZeroComparison(Instruction *I) {
816 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
817 UI != E; ++UI) {
Chris Lattner6a36d632007-04-07 01:03:46 +0000818 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
819 if (IC->isEquality())
820 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
821 if (C->isNullValue())
822 continue;
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000823 // Unknown instruction.
824 return false;
825 }
826 return true;
827}
828
829/// This memcmpOptimization will simplify a call to the memcmp library
830/// function.
Reid Spencer557ab152007-02-05 23:32:05 +0000831struct VISIBILITY_HIDDEN memcmpOptimization : public LibCallOptimization {
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000832 /// @brief Default Constructor
833 memcmpOptimization()
834 : LibCallOptimization("memcmp", "Number of 'memcmp' calls simplified") {}
835
836 /// @brief Make sure that the "memcmp" function has the right prototype
837 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
838 Function::const_arg_iterator AI = F->arg_begin();
839 if (F->arg_size() != 3 || !isa<PointerType>(AI->getType())) return false;
840 if (!isa<PointerType>((++AI)->getType())) return false;
Chris Lattner03c49532007-01-15 02:27:26 +0000841 if (!(++AI)->getType()->isInteger()) return false;
842 if (!F->getReturnType()->isInteger()) return false;
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000843 return true;
844 }
845
846 /// Because of alignment and instruction information that we don't have, we
847 /// leave the bulk of this to the code generators.
848 ///
849 /// Note that we could do much more if we could force alignment on otherwise
850 /// small aligned allocas, or if we could indicate that loads have a small
851 /// alignment.
852 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &TD) {
853 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
854
855 // If the two operands are the same, return zero.
856 if (LHS == RHS) {
857 // memcmp(s,s,x) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000858 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000859 }
860
861 // Make sure we have a constant length.
862 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
863 if (!LenC) return false;
Reid Spencere0fc4df2006-10-20 07:07:24 +0000864 uint64_t Len = LenC->getZExtValue();
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000865
866 // If the length is zero, this returns 0.
867 switch (Len) {
868 case 0:
869 // memcmp(s1,s2,0) -> 0
Chris Lattner485b6412007-04-07 00:42:32 +0000870 return ReplaceCallWith(CI, Constant::getNullValue(CI->getType()));
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000871 case 1: {
872 // memcmp(S1,S2,1) -> *(ubyte*)S1 - *(ubyte*)S2
Christopher Lambedf07882007-12-17 01:12:55 +0000873 const Type *UCharPtr = PointerType::getUnqual(Type::Int8Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000874 CastInst *Op1Cast = CastInst::create(
875 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
876 CastInst *Op2Cast = CastInst::create(
877 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000878 Value *S1V = new LoadInst(Op1Cast, LHS->getName()+".val", CI);
879 Value *S2V = new LoadInst(Op2Cast, RHS->getName()+".val", CI);
880 Value *RV = BinaryOperator::createSub(S1V, S2V, CI->getName()+".diff",CI);
881 if (RV->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +0000882 RV = CastInst::createIntegerCast(RV, CI->getType(), false,
883 RV->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000884 return ReplaceCallWith(CI, RV);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000885 }
886 case 2:
887 if (IsOnlyUsedInEqualsZeroComparison(CI)) {
888 // TODO: IF both are aligned, use a short load/compare.
889
890 // memcmp(S1,S2,2) -> S1[0]-S2[0] | S1[1]-S2[1] iff only ==/!= 0 matters
Christopher Lambedf07882007-12-17 01:12:55 +0000891 const Type *UCharPtr = PointerType::getUnqual(Type::Int8Ty);
Reid Spencer6c38f0b2006-11-27 01:05:10 +0000892 CastInst *Op1Cast = CastInst::create(
893 Instruction::BitCast, LHS, UCharPtr, LHS->getName(), CI);
894 CastInst *Op2Cast = CastInst::create(
895 Instruction::BitCast, RHS, UCharPtr, RHS->getName(), CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000896 Value *S1V1 = new LoadInst(Op1Cast, LHS->getName()+".val1", CI);
897 Value *S2V1 = new LoadInst(Op2Cast, RHS->getName()+".val1", CI);
898 Value *D1 = BinaryOperator::createSub(S1V1, S2V1,
899 CI->getName()+".d1", CI);
Reid Spencerc635f472006-12-31 05:48:39 +0000900 Constant *One = ConstantInt::get(Type::Int32Ty, 1);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000901 Value *G1 = new GetElementPtrInst(Op1Cast, One, "next1v", CI);
902 Value *G2 = new GetElementPtrInst(Op2Cast, One, "next2v", CI);
903 Value *S1V2 = new LoadInst(G1, LHS->getName()+".val2", CI);
Chris Lattnercd60d382006-05-12 23:35:26 +0000904 Value *S2V2 = new LoadInst(G2, RHS->getName()+".val2", CI);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000905 Value *D2 = BinaryOperator::createSub(S1V2, S2V2,
906 CI->getName()+".d1", CI);
907 Value *Or = BinaryOperator::createOr(D1, D2, CI->getName()+".res", CI);
908 if (Or->getType() != CI->getType())
Reid Spencerbfe26ff2006-12-13 00:50:17 +0000909 Or = CastInst::createIntegerCast(Or, CI->getType(), false /*ZExt*/,
910 Or->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +0000911 return ReplaceCallWith(CI, Or);
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000912 }
913 break;
914 default:
915 break;
916 }
917
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000918 return false;
919 }
920} memcmpOptimizer;
921
Chris Lattnera8b4a562008-01-28 04:41:43 +0000922/// This LibCallOptimization will simplify a call to the memcpy library
923/// function. It simply converts them into calls to llvm.memcpy.*;
924/// the resulting call should be optimized later.
925/// @brief Simplify the memcpy library function.
926struct VISIBILITY_HIDDEN MemCpyOptimization : public LibCallOptimization {
927public:
928 MemCpyOptimization() : LibCallOptimization("memcpy",
929 "Number of 'memcpy' calls simplified") {}
930
931 /// @brief Make sure that the "memcpy" function has the right prototype
932 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
933 const FunctionType *FT = F->getFunctionType();
934 const Type* voidPtr = PointerType::getUnqual(Type::Int8Ty);
935 return FT->getReturnType() == voidPtr && FT->getNumParams() == 3 &&
936 FT->getParamType(0) == voidPtr &&
937 FT->getParamType(1) == voidPtr &&
938 FT->getParamType(2) == SLC.getIntPtrType();
939 }
940
941 /// @brief Perform the memcpy optimization
942 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
943 Value *MemcpyOps[] = {
944 CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
945 ConstantInt::get(Type::Int32Ty, 1) // align = 1 always.
946 };
947 new CallInst(SLC.get_memcpy(), MemcpyOps, MemcpyOps + 4, "", CI);
948 // memcpy always returns the destination
949 return ReplaceCallWith(CI, CI->getOperand(1));
950 }
951} MemCpyOptimizer;
Chris Lattnerc244e7c2005-09-29 04:54:20 +0000952
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +0000953/// This LibCallOptimization will simplify a call to the memcpy library
954/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
Reid Spencer7ddcfb32005-04-27 21:29:20 +0000955/// bytes depending on the length of the string and the alignment. Additional
956/// optimizations are possible in code generation (sequence of immediate store)
Reid Spencerf2534c72005-04-25 21:11:48 +0000957/// @brief Simplify the memcpy library function.
Reid Spencer557ab152007-02-05 23:32:05 +0000958struct VISIBILITY_HIDDEN LLVMMemCpyMoveOptzn : public LibCallOptimization {
Chris Lattnerea7986a2006-03-03 01:30:23 +0000959 LLVMMemCpyMoveOptzn(const char* fname, const char* desc)
960 : LibCallOptimization(fname, desc) {}
Reid Spencerf2534c72005-04-25 21:11:48 +0000961
962 /// @brief Make sure that the "memcpy" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000963 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& TD) {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000964 // Just make sure this has 4 arguments per LLVM spec.
Reid Spencer2bc7a4f2005-04-26 23:02:16 +0000965 return (f->arg_size() == 4);
Reid Spencerf2534c72005-04-25 21:11:48 +0000966 }
967
Reid Spencerb4f7b832005-04-26 07:45:18 +0000968 /// Because of alignment and instruction information that we don't have, we
969 /// leave the bulk of this to the code generators. The optimization here just
970 /// deals with a few degenerate cases where the length of the string and the
971 /// alignment match the sizes of our intrinsic types so we can do a load and
972 /// store instead of the memcpy call.
973 /// @brief Perform the memcpy optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +0000974 virtual bool OptimizeCall(CallInst* ci, SimplifyLibCalls& TD) {
Reid Spencer4855ebf2005-04-26 19:55:57 +0000975 // Make sure we have constant int values to work with
976 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
977 if (!LEN)
978 return false;
979 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
980 if (!ALIGN)
981 return false;
982
983 // If the length is larger than the alignment, we can't optimize
Reid Spencere0fc4df2006-10-20 07:07:24 +0000984 uint64_t len = LEN->getZExtValue();
985 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +0000986 if (alignment == 0)
987 alignment = 1; // Alignment 0 is identity for alignment 1
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000988 if (len > alignment)
Reid Spencerb4f7b832005-04-26 07:45:18 +0000989 return false;
990
Reid Spencer08b49402005-04-27 17:46:54 +0000991 // Get the type we will cast to, based on size of the string
Reid Spencerb4f7b832005-04-26 07:45:18 +0000992 Value* dest = ci->getOperand(1);
993 Value* src = ci->getOperand(2);
Reid Spencer4f98e622007-01-07 21:45:41 +0000994 const Type* castType = 0;
Chris Lattner485b6412007-04-07 00:42:32 +0000995 switch (len) {
Reid Spencerbb92b4f2005-04-26 19:13:17 +0000996 case 0:
Chris Lattner485b6412007-04-07 00:42:32 +0000997 // memcpy(d,s,0,a) -> d
998 return ReplaceCallWith(ci, 0);
Reid Spencerc635f472006-12-31 05:48:39 +0000999 case 1: castType = Type::Int8Ty; break;
1000 case 2: castType = Type::Int16Ty; break;
1001 case 4: castType = Type::Int32Ty; break;
1002 case 8: castType = Type::Int64Ty; break;
Reid Spencerb4f7b832005-04-26 07:45:18 +00001003 default:
1004 return false;
1005 }
Reid Spencer08b49402005-04-27 17:46:54 +00001006
1007 // Cast source and dest to the right sized primitive and then load/store
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001008 CastInst* SrcCast = CastInst::create(Instruction::BitCast,
Christopher Lambedf07882007-12-17 01:12:55 +00001009 src, PointerType::getUnqual(castType), src->getName()+".cast", ci);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001010 CastInst* DestCast = CastInst::create(Instruction::BitCast,
Christopher Lambedf07882007-12-17 01:12:55 +00001011 dest, PointerType::getUnqual(castType),dest->getName()+".cast", ci);
Reid Spencer08b49402005-04-27 17:46:54 +00001012 LoadInst* LI = new LoadInst(SrcCast,SrcCast->getName()+".val",ci);
Reid Spencerde46e482006-11-02 20:25:50 +00001013 new StoreInst(LI, DestCast, ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001014 return ReplaceCallWith(ci, 0);
Reid Spencerf2534c72005-04-25 21:11:48 +00001015 }
Chris Lattnerea7986a2006-03-03 01:30:23 +00001016};
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001017
Chris Lattnerea7986a2006-03-03 01:30:23 +00001018/// This LibCallOptimization will simplify a call to the memcpy/memmove library
1019/// functions.
1020LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer32("llvm.memcpy.i32",
1021 "Number of 'llvm.memcpy' calls simplified");
1022LLVMMemCpyMoveOptzn LLVMMemCpyOptimizer64("llvm.memcpy.i64",
1023 "Number of 'llvm.memcpy' calls simplified");
1024LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer32("llvm.memmove.i32",
1025 "Number of 'llvm.memmove' calls simplified");
1026LLVMMemCpyMoveOptzn LLVMMemMoveOptimizer64("llvm.memmove.i64",
1027 "Number of 'llvm.memmove' calls simplified");
Reid Spencer38cabd72005-05-03 07:23:44 +00001028
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001029/// This LibCallOptimization will simplify a call to the memset library
1030/// function by expanding it out to a single store of size 0, 1, 2, 4, or 8
1031/// bytes depending on the length argument.
Reid Spencer557ab152007-02-05 23:32:05 +00001032struct VISIBILITY_HIDDEN LLVMMemSetOptimization : public LibCallOptimization {
Reid Spencer38cabd72005-05-03 07:23:44 +00001033 /// @brief Default Constructor
Chris Lattnerea7986a2006-03-03 01:30:23 +00001034 LLVMMemSetOptimization(const char *Name) : LibCallOptimization(Name,
Reid Spencer38cabd72005-05-03 07:23:44 +00001035 "Number of 'llvm.memset' calls simplified") {}
Reid Spencer38cabd72005-05-03 07:23:44 +00001036
1037 /// @brief Make sure that the "memset" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001038 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &TD) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001039 // Just make sure this has 3 arguments per LLVM spec.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001040 return F->arg_size() == 4;
Reid Spencer38cabd72005-05-03 07:23:44 +00001041 }
1042
1043 /// Because of alignment and instruction information that we don't have, we
1044 /// leave the bulk of this to the code generators. The optimization here just
1045 /// deals with a few degenerate cases where the length parameter is constant
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001046 /// and the alignment matches the sizes of our intrinsic types so we can do
Reid Spencer38cabd72005-05-03 07:23:44 +00001047 /// store instead of the memcpy call. Other calls are transformed into the
1048 /// llvm.memset intrinsic.
1049 /// @brief Perform the memset optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001050 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &TD) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001051 // Make sure we have constant int values to work with
1052 ConstantInt* LEN = dyn_cast<ConstantInt>(ci->getOperand(3));
1053 if (!LEN)
1054 return false;
1055 ConstantInt* ALIGN = dyn_cast<ConstantInt>(ci->getOperand(4));
1056 if (!ALIGN)
1057 return false;
1058
1059 // Extract the length and alignment
Reid Spencere0fc4df2006-10-20 07:07:24 +00001060 uint64_t len = LEN->getZExtValue();
1061 uint64_t alignment = ALIGN->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001062
1063 // Alignment 0 is identity for alignment 1
1064 if (alignment == 0)
1065 alignment = 1;
1066
1067 // If the length is zero, this is a no-op
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001068 if (len == 0) {
Reid Spencer38cabd72005-05-03 07:23:44 +00001069 // memset(d,c,0,a) -> noop
Chris Lattner485b6412007-04-07 00:42:32 +00001070 return ReplaceCallWith(ci, 0);
Reid Spencer38cabd72005-05-03 07:23:44 +00001071 }
1072
1073 // If the length is larger than the alignment, we can't optimize
1074 if (len > alignment)
1075 return false;
1076
1077 // Make sure we have a constant ubyte to work with so we can extract
1078 // the value to be filled.
Reid Spencere0fc4df2006-10-20 07:07:24 +00001079 ConstantInt* FILL = dyn_cast<ConstantInt>(ci->getOperand(2));
Reid Spencer38cabd72005-05-03 07:23:44 +00001080 if (!FILL)
1081 return false;
Reid Spencerc635f472006-12-31 05:48:39 +00001082 if (FILL->getType() != Type::Int8Ty)
Reid Spencer38cabd72005-05-03 07:23:44 +00001083 return false;
1084
1085 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001086
Reid Spencer38cabd72005-05-03 07:23:44 +00001087 // Extract the fill character
Reid Spencere0fc4df2006-10-20 07:07:24 +00001088 uint64_t fill_char = FILL->getZExtValue();
Reid Spencer38cabd72005-05-03 07:23:44 +00001089 uint64_t fill_value = fill_char;
1090
1091 // Get the type we will cast to, based on size of memory area to fill, and
1092 // and the value we will store there.
1093 Value* dest = ci->getOperand(1);
Reid Spencer4f98e622007-01-07 21:45:41 +00001094 const Type* castType = 0;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001095 switch (len) {
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001096 case 1:
Reid Spencerc635f472006-12-31 05:48:39 +00001097 castType = Type::Int8Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001098 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001099 case 2:
Reid Spencerc635f472006-12-31 05:48:39 +00001100 castType = Type::Int16Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001101 fill_value |= fill_char << 8;
1102 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001103 case 4:
Reid Spencerc635f472006-12-31 05:48:39 +00001104 castType = Type::Int32Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001105 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1106 break;
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001107 case 8:
Reid Spencerc635f472006-12-31 05:48:39 +00001108 castType = Type::Int64Ty;
Reid Spencer38cabd72005-05-03 07:23:44 +00001109 fill_value |= fill_char << 8 | fill_char << 16 | fill_char << 24;
1110 fill_value |= fill_char << 32 | fill_char << 40 | fill_char << 48;
1111 fill_value |= fill_char << 56;
1112 break;
1113 default:
1114 return false;
1115 }
1116
1117 // Cast dest to the right sized primitive and then load/store
Christopher Lambedf07882007-12-17 01:12:55 +00001118 CastInst* DestCast = new BitCastInst(dest, PointerType::getUnqual(castType),
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001119 dest->getName()+".cast", ci);
Reid Spencere0fc4df2006-10-20 07:07:24 +00001120 new StoreInst(ConstantInt::get(castType,fill_value),DestCast, ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001121 return ReplaceCallWith(ci, 0);
Reid Spencer38cabd72005-05-03 07:23:44 +00001122 }
Chris Lattnerea7986a2006-03-03 01:30:23 +00001123};
1124
1125LLVMMemSetOptimization MemSet32Optimizer("llvm.memset.i32");
1126LLVMMemSetOptimization MemSet64Optimizer("llvm.memset.i64");
1127
Reid Spencerbb92b4f2005-04-26 19:13:17 +00001128
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001129/// This LibCallOptimization will simplify calls to the "pow" library
1130/// function. It looks for cases where the result of pow is well known and
Reid Spencer93616972005-04-29 09:39:47 +00001131/// substitutes the appropriate value.
1132/// @brief Simplify the pow library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001133struct VISIBILITY_HIDDEN PowOptimization : public LibCallOptimization {
Reid Spencer93616972005-04-29 09:39:47 +00001134public:
1135 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001136 PowOptimization() : LibCallOptimization("pow",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001137 "Number of 'pow' calls simplified") {}
Reid Spencer95d8efd2005-05-03 02:54:54 +00001138
Reid Spencer93616972005-04-29 09:39:47 +00001139 /// @brief Make sure that the "pow" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001140 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer93616972005-04-29 09:39:47 +00001141 // Just make sure this has 2 arguments
1142 return (f->arg_size() == 2);
1143 }
1144
1145 /// @brief Perform the pow optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001146 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer93616972005-04-29 09:39:47 +00001147 const Type *Ty = cast<Function>(ci->getOperand(0))->getReturnType();
Dale Johannesen6bf69ed2007-09-28 18:06:58 +00001148 if (Ty!=Type::FloatTy && Ty!=Type::DoubleTy)
1149 return false; // FIXME long double not yet supported
Reid Spencer93616972005-04-29 09:39:47 +00001150 Value* base = ci->getOperand(1);
1151 Value* expn = ci->getOperand(2);
1152 if (ConstantFP *Op1 = dyn_cast<ConstantFP>(base)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001153 if (Op1->isExactlyValue(1.0)) // pow(1.0,x) -> 1.0
1154 return ReplaceCallWith(ci, ConstantFP::get(Ty,
1155 Ty==Type::FloatTy ? APFloat(1.0f) : APFloat(1.0)));
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001156 } else if (ConstantFP* Op2 = dyn_cast<ConstantFP>(expn)) {
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001157 if (Op2->getValueAPF().isZero()) {
Reid Spencer93616972005-04-29 09:39:47 +00001158 // pow(x,0.0) -> 1.0
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001159 return ReplaceCallWith(ci, ConstantFP::get(Ty,
1160 Ty==Type::FloatTy ? APFloat(1.0f) : APFloat(1.0)));
1161 } else if (Op2->isExactlyValue(0.5)) {
Reid Spencer93616972005-04-29 09:39:47 +00001162 // pow(x,0.5) -> sqrt(x)
1163 CallInst* sqrt_inst = new CallInst(SLC.get_sqrt(), base,
1164 ci->getName()+".pow",ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001165 return ReplaceCallWith(ci, sqrt_inst);
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001166 } else if (Op2->isExactlyValue(1.0)) {
Reid Spencer93616972005-04-29 09:39:47 +00001167 // pow(x,1.0) -> x
Chris Lattner485b6412007-04-07 00:42:32 +00001168 return ReplaceCallWith(ci, base);
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001169 } else if (Op2->isExactlyValue(-1.0)) {
Reid Spencer93616972005-04-29 09:39:47 +00001170 // pow(x,-1.0) -> 1.0/x
Chris Lattner485b6412007-04-07 00:42:32 +00001171 Value *div_inst =
Dale Johannesenbed9dc42007-09-06 18:13:44 +00001172 BinaryOperator::createFDiv(ConstantFP::get(Ty,
1173 Ty==Type::FloatTy ? APFloat(1.0f) : APFloat(1.0)),
1174 base, ci->getName()+".pow", ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001175 return ReplaceCallWith(ci, div_inst);
Reid Spencer93616972005-04-29 09:39:47 +00001176 }
1177 }
1178 return false; // opt failed
1179 }
1180} PowOptimizer;
1181
Evan Cheng1fc40252006-06-16 08:36:35 +00001182/// This LibCallOptimization will simplify calls to the "printf" library
1183/// function. It looks for cases where the result of printf is not used and the
1184/// operation can be reduced to something simpler.
1185/// @brief Simplify the printf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001186struct VISIBILITY_HIDDEN PrintfOptimization : public LibCallOptimization {
Evan Cheng1fc40252006-06-16 08:36:35 +00001187public:
1188 /// @brief Default Constructor
1189 PrintfOptimization() : LibCallOptimization("printf",
1190 "Number of 'printf' calls simplified") {}
1191
1192 /// @brief Make sure that the "printf" function has the right prototype
Chris Lattner0f150952007-04-07 01:18:36 +00001193 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner49fa8d22007-04-14 01:17:48 +00001194 // Just make sure this has at least 1 argument and returns an integer or
1195 // void type.
1196 const FunctionType *FT = F->getFunctionType();
1197 return FT->getNumParams() >= 1 &&
1198 (isa<IntegerType>(FT->getReturnType()) ||
1199 FT->getReturnType() == Type::VoidTy);
Evan Cheng1fc40252006-06-16 08:36:35 +00001200 }
1201
1202 /// @brief Perform the printf optimization.
Chris Lattner0f150952007-04-07 01:18:36 +00001203 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Evan Cheng1fc40252006-06-16 08:36:35 +00001204 // All the optimizations depend on the length of the first argument and the
1205 // fact that it is a constant string array. Check that now
Chris Lattner182a9452007-04-07 21:58:02 +00001206 std::string FormatStr;
1207 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
Evan Cheng1fc40252006-06-16 08:36:35 +00001208 return false;
Chris Lattner49fa8d22007-04-14 01:17:48 +00001209
1210 // If this is a simple constant string with no format specifiers that ends
1211 // with a \n, turn it into a puts call.
1212 if (FormatStr.empty()) {
1213 // Tolerate printf's declared void.
1214 if (CI->use_empty()) return ReplaceCallWith(CI, 0);
1215 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
1216 }
1217
1218 if (FormatStr.size() == 1) {
1219 // Turn this into a putchar call, even if it is a %.
1220 Value *V = ConstantInt::get(Type::Int32Ty, FormatStr[0]);
1221 new CallInst(SLC.get_putchar(), V, "", CI);
1222 if (CI->use_empty()) return ReplaceCallWith(CI, 0);
1223 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1224 }
Evan Cheng1fc40252006-06-16 08:36:35 +00001225
Chris Lattner49fa8d22007-04-14 01:17:48 +00001226 // Check to see if the format str is something like "foo\n", in which case
1227 // we convert it to a puts call. We don't allow it to contain any format
1228 // characters.
1229 if (FormatStr[FormatStr.size()-1] == '\n' &&
1230 FormatStr.find('%') == std::string::npos) {
1231 // Create a string literal with no \n on it. We expect the constant merge
1232 // pass to be run after this pass, to merge duplicate strings.
1233 FormatStr.erase(FormatStr.end()-1);
1234 Constant *Init = ConstantArray::get(FormatStr, true);
1235 Constant *GV = new GlobalVariable(Init->getType(), true,
1236 GlobalVariable::InternalLinkage,
1237 Init, "str",
1238 CI->getParent()->getParent()->getParent());
1239 // Cast GV to be a pointer to char.
Christopher Lambedf07882007-12-17 01:12:55 +00001240 GV = ConstantExpr::getBitCast(GV, PointerType::getUnqual(Type::Int8Ty));
Chris Lattner49fa8d22007-04-14 01:17:48 +00001241 new CallInst(SLC.get_puts(), GV, "", CI);
1242
1243 if (CI->use_empty()) return ReplaceCallWith(CI, 0);
Dale Johannesen4d063912007-10-24 20:14:50 +00001244 // The return value from printf includes the \n we just removed, so +1.
Chris Lattner49fa8d22007-04-14 01:17:48 +00001245 return ReplaceCallWith(CI,
Dale Johannesen4d063912007-10-24 20:14:50 +00001246 ConstantInt::get(CI->getType(),
1247 FormatStr.size()+1));
Chris Lattner49fa8d22007-04-14 01:17:48 +00001248 }
1249
1250
Chris Lattner182a9452007-04-07 21:58:02 +00001251 // Only support %c or "%s\n" for now.
1252 if (FormatStr.size() < 2 || FormatStr[0] != '%')
Chris Lattner0f150952007-04-07 01:18:36 +00001253 return false;
Evan Cheng1fc40252006-06-16 08:36:35 +00001254
1255 // Get the second character and switch on its value
Chris Lattner182a9452007-04-07 21:58:02 +00001256 switch (FormatStr[1]) {
Chris Lattner0f150952007-04-07 01:18:36 +00001257 default: return false;
Chris Lattner182a9452007-04-07 21:58:02 +00001258 case 's':
Chris Lattner49fa8d22007-04-14 01:17:48 +00001259 if (FormatStr != "%s\n" || CI->getNumOperands() < 3 ||
Chris Lattner182a9452007-04-07 21:58:02 +00001260 // TODO: could insert strlen call to compute string length.
1261 !CI->use_empty())
Evan Cheng1fc40252006-06-16 08:36:35 +00001262 return false;
Chris Lattner0f150952007-04-07 01:18:36 +00001263
1264 // printf("%s\n",str) -> puts(str)
Chris Lattnerbed184c2007-04-07 21:04:50 +00001265 new CallInst(SLC.get_puts(), CastToCStr(CI->getOperand(2), CI),
Chris Lattner0f150952007-04-07 01:18:36 +00001266 CI->getName(), CI);
1267 return ReplaceCallWith(CI, 0);
Chris Lattner0f150952007-04-07 01:18:36 +00001268 case 'c': {
1269 // printf("%c",c) -> putchar(c)
Chris Lattner49fa8d22007-04-14 01:17:48 +00001270 if (FormatStr.size() != 2 || CI->getNumOperands() < 3)
Chris Lattner0f150952007-04-07 01:18:36 +00001271 return false;
1272
1273 Value *V = CI->getOperand(2);
1274 if (!isa<IntegerType>(V->getType()) ||
Chris Lattner182a9452007-04-07 21:58:02 +00001275 cast<IntegerType>(V->getType())->getBitWidth() > 32)
Chris Lattner0f150952007-04-07 01:18:36 +00001276 return false;
1277
Chris Lattner182a9452007-04-07 21:58:02 +00001278 V = CastInst::createZExtOrBitCast(V, Type::Int32Ty, CI->getName()+".int",
Chris Lattner0f150952007-04-07 01:18:36 +00001279 CI);
1280 new CallInst(SLC.get_putchar(), V, "", CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001281 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
Chris Lattner0f150952007-04-07 01:18:36 +00001282 }
1283 }
Evan Cheng1fc40252006-06-16 08:36:35 +00001284 }
1285} PrintfOptimizer;
1286
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001287/// This LibCallOptimization will simplify calls to the "fprintf" library
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001288/// function. It looks for cases where the result of fprintf is not used and the
1289/// operation can be reduced to something simpler.
Evan Cheng1fc40252006-06-16 08:36:35 +00001290/// @brief Simplify the fprintf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001291struct VISIBILITY_HIDDEN FPrintFOptimization : public LibCallOptimization {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001292public:
1293 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001294 FPrintFOptimization() : LibCallOptimization("fprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001295 "Number of 'fprintf' calls simplified") {}
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001296
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001297 /// @brief Make sure that the "fprintf" function has the right prototype
Chris Lattnerbed184c2007-04-07 21:04:50 +00001298 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1299 const FunctionType *FT = F->getFunctionType();
1300 return FT->getNumParams() == 2 && // two fixed arguments.
Christopher Lambedf07882007-12-17 01:12:55 +00001301 FT->getParamType(1) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattnerbed184c2007-04-07 21:04:50 +00001302 isa<PointerType>(FT->getParamType(0)) &&
1303 isa<IntegerType>(FT->getReturnType());
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001304 }
1305
1306 /// @brief Perform the fprintf optimization.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001307 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001308 // If the call has more than 3 operands, we can't optimize it
Chris Lattnerbed184c2007-04-07 21:04:50 +00001309 if (CI->getNumOperands() != 3 && CI->getNumOperands() != 4)
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001310 return false;
1311
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001312 // All the optimizations depend on the format string.
Chris Lattner182a9452007-04-07 21:58:02 +00001313 std::string FormatStr;
1314 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001315 return false;
1316
Chris Lattner182a9452007-04-07 21:58:02 +00001317 // If this is just a format string, turn it into fwrite.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001318 if (CI->getNumOperands() == 3) {
Chris Lattner182a9452007-04-07 21:58:02 +00001319 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1320 if (FormatStr[i] == '%')
Chris Lattnerbed184c2007-04-07 21:04:50 +00001321 return false; // we found a format specifier
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001322
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001323 // fprintf(file,fmt) -> fwrite(fmt,strlen(fmt),file)
Chris Lattnerbed184c2007-04-07 21:04:50 +00001324 const Type *FILEty = CI->getOperand(1)->getType();
John Criswell4642afd2005-06-29 15:03:18 +00001325
Chris Lattnerbed184c2007-04-07 21:04:50 +00001326 Value *FWriteArgs[] = {
1327 CI->getOperand(2),
Chris Lattner182a9452007-04-07 21:58:02 +00001328 ConstantInt::get(SLC.getIntPtrType(), FormatStr.size()),
Chris Lattnerbed184c2007-04-07 21:04:50 +00001329 ConstantInt::get(SLC.getIntPtrType(), 1),
1330 CI->getOperand(1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001331 };
David Greene17a5dfe2007-08-01 03:43:44 +00001332 new CallInst(SLC.get_fwrite(FILEty), FWriteArgs, FWriteArgs + 4, CI->getName(), CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001333 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(),
1334 FormatStr.size()));
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001335 }
Chris Lattnerbed184c2007-04-07 21:04:50 +00001336
1337 // The remaining optimizations require the format string to be length 2:
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001338 // "%s" or "%c".
Chris Lattner182a9452007-04-07 21:58:02 +00001339 if (FormatStr.size() != 2 || FormatStr[0] != '%')
Chris Lattnerbed184c2007-04-07 21:04:50 +00001340 return false;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001341
1342 // Get the second character and switch on its value
Chris Lattner182a9452007-04-07 21:58:02 +00001343 switch (FormatStr[1]) {
Chris Lattnerbed184c2007-04-07 21:04:50 +00001344 case 'c': {
1345 // fprintf(file,"%c",c) -> fputc(c,file)
1346 const Type *FILETy = CI->getOperand(1)->getType();
1347 Value *C = CastInst::createZExtOrBitCast(CI->getOperand(3), Type::Int32Ty,
1348 CI->getName()+".int", CI);
David Greene17a5dfe2007-08-01 03:43:44 +00001349 SmallVector<Value *, 2> Args;
1350 Args.push_back(C);
1351 Args.push_back(CI->getOperand(1));
1352 new CallInst(SLC.get_fputc(FILETy), Args.begin(), Args.end(), "", CI);
Chris Lattnerbed184c2007-04-07 21:04:50 +00001353 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1354 }
1355 case 's': {
1356 const Type *FILETy = CI->getOperand(1)->getType();
Chris Lattnerbed184c2007-04-07 21:04:50 +00001357
1358 // If the result of the fprintf call is used, we can't do this.
Chris Lattner182a9452007-04-07 21:58:02 +00001359 // TODO: we should insert a strlen call.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001360 if (!CI->use_empty())
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001361 return false;
Chris Lattnerbed184c2007-04-07 21:04:50 +00001362
1363 // fprintf(file,"%s",str) -> fputs(str,file)
David Greene17a5dfe2007-08-01 03:43:44 +00001364 SmallVector<Value *, 2> Args;
1365 Args.push_back(CastToCStr(CI->getOperand(3), CI));
1366 Args.push_back(CI->getOperand(1));
1367 new CallInst(SLC.get_fputs(FILETy), Args.begin(),
1368 Args.end(), CI->getName(), CI);
Chris Lattnerbed184c2007-04-07 21:04:50 +00001369 return ReplaceCallWith(CI, 0);
1370 }
1371 default:
1372 return false;
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001373 }
Reid Spencer2d5c7be2005-05-02 23:59:26 +00001374 }
1375} FPrintFOptimizer;
1376
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001377/// This LibCallOptimization will simplify calls to the "sprintf" library
Reid Spencer1e520fd2005-05-04 03:20:21 +00001378/// function. It looks for cases where the result of sprintf is not used and the
1379/// operation can be reduced to something simpler.
Evan Cheng1fc40252006-06-16 08:36:35 +00001380/// @brief Simplify the sprintf library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001381struct VISIBILITY_HIDDEN SPrintFOptimization : public LibCallOptimization {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001382public:
1383 /// @brief Default Constructor
1384 SPrintFOptimization() : LibCallOptimization("sprintf",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001385 "Number of 'sprintf' calls simplified") {}
Reid Spencer1e520fd2005-05-04 03:20:21 +00001386
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001387 /// @brief Make sure that the "sprintf" function has the right prototype
1388 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1389 const FunctionType *FT = F->getFunctionType();
1390 return FT->getNumParams() == 2 && // two fixed arguments.
Christopher Lambedf07882007-12-17 01:12:55 +00001391 FT->getParamType(1) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001392 FT->getParamType(0) == FT->getParamType(1) &&
1393 isa<IntegerType>(FT->getReturnType());
Reid Spencer1e520fd2005-05-04 03:20:21 +00001394 }
1395
1396 /// @brief Perform the sprintf optimization.
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001397 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001398 // If the call has more than 3 operands, we can't optimize it
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001399 if (CI->getNumOperands() != 3 && CI->getNumOperands() != 4)
Reid Spencer1e520fd2005-05-04 03:20:21 +00001400 return false;
1401
Chris Lattner182a9452007-04-07 21:58:02 +00001402 std::string FormatStr;
1403 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Reid Spencer1e520fd2005-05-04 03:20:21 +00001404 return false;
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001405
1406 if (CI->getNumOperands() == 3) {
Reid Spencer1e520fd2005-05-04 03:20:21 +00001407 // Make sure there's no % in the constant array
Chris Lattner182a9452007-04-07 21:58:02 +00001408 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1409 if (FormatStr[i] == '%')
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001410 return false; // we found a format specifier
1411
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001412 // sprintf(str,fmt) -> llvm.memcpy(str,fmt,strlen(fmt),1)
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001413 Value *MemCpyArgs[] = {
1414 CI->getOperand(1), CI->getOperand(2),
Chris Lattner182a9452007-04-07 21:58:02 +00001415 ConstantInt::get(SLC.getIntPtrType(),
1416 FormatStr.size()+1), // Copy the nul byte.
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001417 ConstantInt::get(Type::Int32Ty, 1)
1418 };
David Greene17a5dfe2007-08-01 03:43:44 +00001419 new CallInst(SLC.get_memcpy(), MemCpyArgs, MemCpyArgs + 4, "", CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001420 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(),
1421 FormatStr.size()));
Reid Spencer1e520fd2005-05-04 03:20:21 +00001422 }
1423
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001424 // The remaining optimizations require the format string to be "%s" or "%c".
Chris Lattner182a9452007-04-07 21:58:02 +00001425 if (FormatStr.size() != 2 || FormatStr[0] != '%')
Reid Spencer1e520fd2005-05-04 03:20:21 +00001426 return false;
1427
Reid Spencer1e520fd2005-05-04 03:20:21 +00001428 // Get the second character and switch on its value
Chris Lattneraa8ad102007-04-08 18:11:26 +00001429 switch (FormatStr[1]) {
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001430 case 'c': {
1431 // sprintf(dest,"%c",chr) -> store chr, dest
1432 Value *V = CastInst::createTruncOrBitCast(CI->getOperand(3),
1433 Type::Int8Ty, "char", CI);
1434 new StoreInst(V, CI->getOperand(1), CI);
1435 Value *Ptr = new GetElementPtrInst(CI->getOperand(1),
1436 ConstantInt::get(Type::Int32Ty, 1),
1437 CI->getOperand(1)->getName()+".end",
1438 CI);
1439 new StoreInst(ConstantInt::get(Type::Int8Ty,0), Ptr, CI);
1440 return ReplaceCallWith(CI, ConstantInt::get(Type::Int32Ty, 1));
1441 }
Chris Lattner175463a2005-09-24 22:17:06 +00001442 case 's': {
1443 // sprintf(dest,"%s",str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
Chris Lattner34acba42007-01-07 08:12:01 +00001444 Value *Len = new CallInst(SLC.get_strlen(),
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001445 CastToCStr(CI->getOperand(3), CI),
1446 CI->getOperand(3)->getName()+".len", CI);
1447 Value *UnincLen = Len;
1448 Len = BinaryOperator::createAdd(Len, ConstantInt::get(Len->getType(), 1),
1449 Len->getName()+"1", CI);
1450 Value *MemcpyArgs[4] = {
1451 CI->getOperand(1),
1452 CastToCStr(CI->getOperand(3), CI),
1453 Len,
1454 ConstantInt::get(Type::Int32Ty, 1)
Chris Lattnerade1c2b2007-02-13 05:58:53 +00001455 };
David Greene17a5dfe2007-08-01 03:43:44 +00001456 new CallInst(SLC.get_memcpy(), MemcpyArgs, MemcpyArgs + 4, "", CI);
Chris Lattner175463a2005-09-24 22:17:06 +00001457
1458 // The strlen result is the unincremented number of bytes in the string.
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001459 if (!CI->use_empty()) {
1460 if (UnincLen->getType() != CI->getType())
1461 UnincLen = CastInst::createIntegerCast(UnincLen, CI->getType(), false,
1462 Len->getName(), CI);
1463 CI->replaceAllUsesWith(UnincLen);
Chris Lattnerf4877682005-09-25 07:06:48 +00001464 }
Chris Lattner08c0b8b32007-04-07 21:17:51 +00001465 return ReplaceCallWith(CI, 0);
Chris Lattner175463a2005-09-24 22:17:06 +00001466 }
1467 }
1468 return false;
Reid Spencer1e520fd2005-05-04 03:20:21 +00001469 }
1470} SPrintFOptimizer;
1471
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001472/// This LibCallOptimization will simplify calls to the "fputs" library
Reid Spencer93616972005-04-29 09:39:47 +00001473/// function. It looks for cases where the result of fputs is not used and the
1474/// operation can be reduced to something simpler.
Chris Lattner57179812007-04-08 07:00:35 +00001475/// @brief Simplify the fputs library function.
Chris Lattner182a9452007-04-07 21:58:02 +00001476struct VISIBILITY_HIDDEN FPutsOptimization : public LibCallOptimization {
Reid Spencer93616972005-04-29 09:39:47 +00001477public:
1478 /// @brief Default Constructor
Chris Lattner182a9452007-04-07 21:58:02 +00001479 FPutsOptimization() : LibCallOptimization("fputs",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001480 "Number of 'fputs' calls simplified") {}
Reid Spencer93616972005-04-29 09:39:47 +00001481
Reid Spencer93616972005-04-29 09:39:47 +00001482 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001483 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencer93616972005-04-29 09:39:47 +00001484 // Just make sure this has 2 arguments
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001485 return F->arg_size() == 2;
Reid Spencer93616972005-04-29 09:39:47 +00001486 }
1487
1488 /// @brief Perform the fputs optimization.
Chris Lattner182a9452007-04-07 21:58:02 +00001489 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1490 // If the result is used, none of these optimizations work.
1491 if (!CI->use_empty())
Reid Spencer93616972005-04-29 09:39:47 +00001492 return false;
1493
1494 // All the optimizations depend on the length of the first argument and the
1495 // fact that it is a constant string array. Check that now
Chris Lattner182a9452007-04-07 21:58:02 +00001496 std::string Str;
1497 if (!GetConstantStringInfo(CI->getOperand(1), Str))
Reid Spencer93616972005-04-29 09:39:47 +00001498 return false;
1499
Chris Lattner182a9452007-04-07 21:58:02 +00001500 const Type *FILETy = CI->getOperand(2)->getType();
Chris Lattner57179812007-04-08 07:00:35 +00001501 // fputs(s,F) -> fwrite(s,1,len,F) (if s is constant and strlen(s) > 1)
1502 Value *FWriteParms[4] = {
1503 CI->getOperand(1),
1504 ConstantInt::get(SLC.getIntPtrType(), Str.size()),
1505 ConstantInt::get(SLC.getIntPtrType(), 1),
1506 CI->getOperand(2)
1507 };
David Greene17a5dfe2007-08-01 03:43:44 +00001508 new CallInst(SLC.get_fwrite(FILETy), FWriteParms, FWriteParms + 4, "", CI);
Chris Lattner182a9452007-04-07 21:58:02 +00001509 return ReplaceCallWith(CI, 0); // Known to have no uses (see above).
Reid Spencer93616972005-04-29 09:39:47 +00001510 }
Chris Lattner57179812007-04-08 07:00:35 +00001511} FPutsOptimizer;
1512
1513/// This LibCallOptimization will simplify calls to the "fwrite" function.
1514struct VISIBILITY_HIDDEN FWriteOptimization : public LibCallOptimization {
1515public:
1516 /// @brief Default Constructor
1517 FWriteOptimization() : LibCallOptimization("fwrite",
1518 "Number of 'fwrite' calls simplified") {}
1519
1520 /// @brief Make sure that the "fputs" function has the right prototype
1521 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1522 const FunctionType *FT = F->getFunctionType();
1523 return FT->getNumParams() == 4 &&
Christopher Lambedf07882007-12-17 01:12:55 +00001524 FT->getParamType(0) == PointerType::getUnqual(Type::Int8Ty) &&
Chris Lattner57179812007-04-08 07:00:35 +00001525 FT->getParamType(1) == FT->getParamType(2) &&
1526 isa<IntegerType>(FT->getParamType(1)) &&
1527 isa<PointerType>(FT->getParamType(3)) &&
1528 isa<IntegerType>(FT->getReturnType());
1529 }
1530
1531 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1532 // Get the element size and count.
1533 uint64_t EltSize, EltCount;
1534 if (ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(2)))
1535 EltSize = C->getZExtValue();
1536 else
1537 return false;
1538 if (ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(3)))
1539 EltCount = C->getZExtValue();
1540 else
1541 return false;
1542
1543 // If this is writing zero records, remove the call (it's a noop).
1544 if (EltSize * EltCount == 0)
1545 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 0));
1546
1547 // If this is writing one byte, turn it into fputc.
1548 if (EltSize == 1 && EltCount == 1) {
David Greene17a5dfe2007-08-01 03:43:44 +00001549 SmallVector<Value *, 2> Args;
Chris Lattner57179812007-04-08 07:00:35 +00001550 // fwrite(s,1,1,F) -> fputc(s[0],F)
1551 Value *Ptr = CI->getOperand(1);
1552 Value *Val = new LoadInst(Ptr, Ptr->getName()+".byte", CI);
David Greene17a5dfe2007-08-01 03:43:44 +00001553 Args.push_back(new ZExtInst(Val, Type::Int32Ty, Val->getName()+".int", CI));
1554 Args.push_back(CI->getOperand(4));
Chris Lattner57179812007-04-08 07:00:35 +00001555 const Type *FILETy = CI->getOperand(4)->getType();
David Greene17a5dfe2007-08-01 03:43:44 +00001556 new CallInst(SLC.get_fputc(FILETy), Args.begin(), Args.end(), "", CI);
Chris Lattner57179812007-04-08 07:00:35 +00001557 return ReplaceCallWith(CI, ConstantInt::get(CI->getType(), 1));
1558 }
1559 return false;
1560 }
1561} FWriteOptimizer;
Reid Spencer93616972005-04-29 09:39:47 +00001562
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001563/// This LibCallOptimization will simplify calls to the "isdigit" library
Reid Spencer282d0572005-05-04 18:58:28 +00001564/// function. It simply does range checks the parameter explicitly.
1565/// @brief Simplify the isdigit library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001566struct VISIBILITY_HIDDEN isdigitOptimization : public LibCallOptimization {
Reid Spencer282d0572005-05-04 18:58:28 +00001567public:
Chris Lattner5f6035f2005-09-29 06:16:11 +00001568 isdigitOptimization() : LibCallOptimization("isdigit",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001569 "Number of 'isdigit' calls simplified") {}
Reid Spencer282d0572005-05-04 18:58:28 +00001570
Chris Lattner5f6035f2005-09-29 06:16:11 +00001571 /// @brief Make sure that the "isdigit" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001572 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer282d0572005-05-04 18:58:28 +00001573 // Just make sure this has 1 argument
1574 return (f->arg_size() == 1);
1575 }
1576
1577 /// @brief Perform the toascii optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001578 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
1579 if (ConstantInt* CI = dyn_cast<ConstantInt>(ci->getOperand(1))) {
Reid Spencer282d0572005-05-04 18:58:28 +00001580 // isdigit(c) -> 0 or 1, if 'c' is constant
Reid Spencere0fc4df2006-10-20 07:07:24 +00001581 uint64_t val = CI->getZExtValue();
Chris Lattner485b6412007-04-07 00:42:32 +00001582 if (val >= '0' && val <= '9')
1583 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 1));
Reid Spencer282d0572005-05-04 18:58:28 +00001584 else
Chris Lattner485b6412007-04-07 00:42:32 +00001585 return ReplaceCallWith(ci, ConstantInt::get(Type::Int32Ty, 0));
Reid Spencer282d0572005-05-04 18:58:28 +00001586 }
1587
1588 // isdigit(c) -> (unsigned)c - '0' <= 9
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001589 CastInst* cast = CastInst::createIntegerCast(ci->getOperand(1),
Reid Spencerc635f472006-12-31 05:48:39 +00001590 Type::Int32Ty, false/*ZExt*/, ci->getOperand(1)->getName()+".uint", ci);
Chris Lattner4201cd12005-08-24 17:22:17 +00001591 BinaryOperator* sub_inst = BinaryOperator::createSub(cast,
Reid Spencerc635f472006-12-31 05:48:39 +00001592 ConstantInt::get(Type::Int32Ty,0x30),
Reid Spencer282d0572005-05-04 18:58:28 +00001593 ci->getOperand(1)->getName()+".sub",ci);
Reid Spencer266e42b2006-12-23 06:05:41 +00001594 ICmpInst* setcond_inst = new ICmpInst(ICmpInst::ICMP_ULE,sub_inst,
Reid Spencerc635f472006-12-31 05:48:39 +00001595 ConstantInt::get(Type::Int32Ty,9),
Reid Spencer282d0572005-05-04 18:58:28 +00001596 ci->getOperand(1)->getName()+".cmp",ci);
Reid Spencerc635f472006-12-31 05:48:39 +00001597 CastInst* c2 = new ZExtInst(setcond_inst, Type::Int32Ty,
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001598 ci->getOperand(1)->getName()+".isdigit", ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001599 return ReplaceCallWith(ci, c2);
Reid Spencer282d0572005-05-04 18:58:28 +00001600 }
Chris Lattner5f6035f2005-09-29 06:16:11 +00001601} isdigitOptimizer;
1602
Reid Spencer557ab152007-02-05 23:32:05 +00001603struct VISIBILITY_HIDDEN isasciiOptimization : public LibCallOptimization {
Chris Lattner87ef9432005-09-29 06:17:27 +00001604public:
1605 isasciiOptimization()
1606 : LibCallOptimization("isascii", "Number of 'isascii' calls simplified") {}
1607
1608 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Chris Lattner03c49532007-01-15 02:27:26 +00001609 return F->arg_size() == 1 && F->arg_begin()->getType()->isInteger() &&
1610 F->getReturnType()->isInteger();
Chris Lattner87ef9432005-09-29 06:17:27 +00001611 }
1612
1613 /// @brief Perform the isascii optimization.
1614 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1615 // isascii(c) -> (unsigned)c < 128
1616 Value *V = CI->getOperand(1);
Reid Spencer266e42b2006-12-23 06:05:41 +00001617 Value *Cmp = new ICmpInst(ICmpInst::ICMP_ULT, V,
1618 ConstantInt::get(V->getType(), 128),
1619 V->getName()+".isascii", CI);
Chris Lattner87ef9432005-09-29 06:17:27 +00001620 if (Cmp->getType() != CI->getType())
Chris Lattnerf8a7bf32007-04-15 05:38:40 +00001621 Cmp = new ZExtInst(Cmp, CI->getType(), Cmp->getName(), CI);
Chris Lattner485b6412007-04-07 00:42:32 +00001622 return ReplaceCallWith(CI, Cmp);
Chris Lattner87ef9432005-09-29 06:17:27 +00001623 }
1624} isasciiOptimizer;
Chris Lattner5f6035f2005-09-29 06:16:11 +00001625
Reid Spencer282d0572005-05-04 18:58:28 +00001626
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001627/// This LibCallOptimization will simplify calls to the "toascii" library
Reid Spencer4c444fe2005-04-30 03:17:54 +00001628/// function. It simply does the corresponding and operation to restrict the
1629/// range of values to the ASCII character set (0-127).
1630/// @brief Simplify the toascii library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001631struct VISIBILITY_HIDDEN ToAsciiOptimization : public LibCallOptimization {
Reid Spencer4c444fe2005-04-30 03:17:54 +00001632public:
1633 /// @brief Default Constructor
Reid Spencer95d8efd2005-05-03 02:54:54 +00001634 ToAsciiOptimization() : LibCallOptimization("toascii",
Reid Spencer170ae7f2005-05-07 20:15:59 +00001635 "Number of 'toascii' calls simplified") {}
Reid Spencer4c444fe2005-04-30 03:17:54 +00001636
Reid Spencer4c444fe2005-04-30 03:17:54 +00001637 /// @brief Make sure that the "fputs" function has the right prototype
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001638 virtual bool ValidateCalledFunction(const Function* f, SimplifyLibCalls& SLC){
Reid Spencer4c444fe2005-04-30 03:17:54 +00001639 // Just make sure this has 2 arguments
1640 return (f->arg_size() == 1);
1641 }
1642
1643 /// @brief Perform the toascii optimization.
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001644 virtual bool OptimizeCall(CallInst *ci, SimplifyLibCalls &SLC) {
Reid Spencer4c444fe2005-04-30 03:17:54 +00001645 // toascii(c) -> (c & 0x7f)
Chris Lattner485b6412007-04-07 00:42:32 +00001646 Value *chr = ci->getOperand(1);
1647 Value *and_inst = BinaryOperator::createAnd(chr,
Reid Spencer4c444fe2005-04-30 03:17:54 +00001648 ConstantInt::get(chr->getType(),0x7F),ci->getName()+".toascii",ci);
Chris Lattner485b6412007-04-07 00:42:32 +00001649 return ReplaceCallWith(ci, and_inst);
Reid Spencer4c444fe2005-04-30 03:17:54 +00001650 }
1651} ToAsciiOptimizer;
1652
Reid Spencerb195fcd2005-05-14 16:42:52 +00001653/// This LibCallOptimization will simplify calls to the "ffs" library
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001654/// calls which find the first set bit in an int, long, or long long. The
Reid Spencerb195fcd2005-05-14 16:42:52 +00001655/// optimization is to compute the result at compile time if the argument is
1656/// a constant.
1657/// @brief Simplify the ffs library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001658struct VISIBILITY_HIDDEN FFSOptimization : public LibCallOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001659protected:
1660 /// @brief Subclass Constructor
1661 FFSOptimization(const char* funcName, const char* description)
Chris Lattner801f4752006-01-17 18:27:17 +00001662 : LibCallOptimization(funcName, description) {}
Reid Spencerb195fcd2005-05-14 16:42:52 +00001663
1664public:
1665 /// @brief Default Constructor
1666 FFSOptimization() : LibCallOptimization("ffs",
1667 "Number of 'ffs' calls simplified") {}
1668
Chris Lattner801f4752006-01-17 18:27:17 +00001669 /// @brief Make sure that the "ffs" function has the right prototype
1670 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
Reid Spencerb195fcd2005-05-14 16:42:52 +00001671 // Just make sure this has 2 arguments
Reid Spencerc635f472006-12-31 05:48:39 +00001672 return F->arg_size() == 1 && F->getReturnType() == Type::Int32Ty;
Reid Spencerb195fcd2005-05-14 16:42:52 +00001673 }
1674
1675 /// @brief Perform the ffs optimization.
Chris Lattner801f4752006-01-17 18:27:17 +00001676 virtual bool OptimizeCall(CallInst *TheCall, SimplifyLibCalls &SLC) {
1677 if (ConstantInt *CI = dyn_cast<ConstantInt>(TheCall->getOperand(1))) {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001678 // ffs(cnst) -> bit#
1679 // ffsl(cnst) -> bit#
Reid Spencer17f77842005-05-15 21:19:45 +00001680 // ffsll(cnst) -> bit#
Reid Spencere0fc4df2006-10-20 07:07:24 +00001681 uint64_t val = CI->getZExtValue();
Reid Spencer17f77842005-05-15 21:19:45 +00001682 int result = 0;
Chris Lattner801f4752006-01-17 18:27:17 +00001683 if (val) {
1684 ++result;
1685 while ((val & 1) == 0) {
1686 ++result;
1687 val >>= 1;
1688 }
Reid Spencer17f77842005-05-15 21:19:45 +00001689 }
Chris Lattner485b6412007-04-07 00:42:32 +00001690 return ReplaceCallWith(TheCall, ConstantInt::get(Type::Int32Ty, result));
Reid Spencerb195fcd2005-05-14 16:42:52 +00001691 }
Reid Spencer17f77842005-05-15 21:19:45 +00001692
Chris Lattner801f4752006-01-17 18:27:17 +00001693 // ffs(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1694 // ffsl(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1695 // ffsll(x) -> x == 0 ? 0 : llvm.cttz(x)+1
1696 const Type *ArgType = TheCall->getOperand(1)->getType();
Chris Lattner801f4752006-01-17 18:27:17 +00001697 const char *CTTZName;
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001698 assert(ArgType->getTypeID() == Type::IntegerTyID &&
1699 "llvm.cttz argument is not an integer?");
1700 unsigned BitWidth = cast<IntegerType>(ArgType)->getBitWidth();
Chris Lattner3b6058c2007-01-12 22:49:11 +00001701 if (BitWidth == 8)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001702 CTTZName = "llvm.cttz.i8";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001703 else if (BitWidth == 16)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001704 CTTZName = "llvm.cttz.i16";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001705 else if (BitWidth == 32)
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001706 CTTZName = "llvm.cttz.i32";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001707 else {
1708 assert(BitWidth == 64 && "Unknown bitwidth");
Reid Spencer7a9c62b2007-01-12 07:05:14 +00001709 CTTZName = "llvm.cttz.i64";
Chris Lattner3b6058c2007-01-12 22:49:11 +00001710 }
Chris Lattner801f4752006-01-17 18:27:17 +00001711
Chris Lattner34acba42007-01-07 08:12:01 +00001712 Constant *F = SLC.getModule()->getOrInsertFunction(CTTZName, ArgType,
Chris Lattner801f4752006-01-17 18:27:17 +00001713 ArgType, NULL);
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001714 Value *V = CastInst::createIntegerCast(TheCall->getOperand(1), ArgType,
1715 false/*ZExt*/, "tmp", TheCall);
Chris Lattner801f4752006-01-17 18:27:17 +00001716 Value *V2 = new CallInst(F, V, "tmp", TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001717 V2 = CastInst::createIntegerCast(V2, Type::Int32Ty, false/*ZExt*/,
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001718 "tmp", TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001719 V2 = BinaryOperator::createAdd(V2, ConstantInt::get(Type::Int32Ty, 1),
Chris Lattner801f4752006-01-17 18:27:17 +00001720 "tmp", TheCall);
Reid Spencer266e42b2006-12-23 06:05:41 +00001721 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, V,
1722 Constant::getNullValue(V->getType()), "tmp",
1723 TheCall);
Reid Spencerc635f472006-12-31 05:48:39 +00001724 V2 = new SelectInst(Cond, ConstantInt::get(Type::Int32Ty, 0), V2,
Chris Lattner801f4752006-01-17 18:27:17 +00001725 TheCall->getName(), TheCall);
Chris Lattner485b6412007-04-07 00:42:32 +00001726 return ReplaceCallWith(TheCall, V2);
Reid Spencerb195fcd2005-05-14 16:42:52 +00001727 }
1728} FFSOptimizer;
1729
1730/// This LibCallOptimization will simplify calls to the "ffsl" library
1731/// calls. It simply uses FFSOptimization for which the transformation is
1732/// identical.
1733/// @brief Simplify the ffsl library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001734struct VISIBILITY_HIDDEN FFSLOptimization : public FFSOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001735public:
1736 /// @brief Default Constructor
1737 FFSLOptimization() : FFSOptimization("ffsl",
1738 "Number of 'ffsl' calls simplified") {}
1739
1740} FFSLOptimizer;
1741
1742/// This LibCallOptimization will simplify calls to the "ffsll" library
1743/// calls. It simply uses FFSOptimization for which the transformation is
1744/// identical.
1745/// @brief Simplify the ffsl library function.
Reid Spencer557ab152007-02-05 23:32:05 +00001746struct VISIBILITY_HIDDEN FFSLLOptimization : public FFSOptimization {
Reid Spencerb195fcd2005-05-14 16:42:52 +00001747public:
1748 /// @brief Default Constructor
1749 FFSLLOptimization() : FFSOptimization("ffsll",
1750 "Number of 'ffsll' calls simplified") {}
1751
1752} FFSLLOptimizer;
1753
Chris Lattner57a28632006-01-23 05:57:36 +00001754/// This optimizes unary functions that take and return doubles.
1755struct UnaryDoubleFPOptimizer : public LibCallOptimization {
1756 UnaryDoubleFPOptimizer(const char *Fn, const char *Desc)
1757 : LibCallOptimization(Fn, Desc) {}
Chris Lattner4201cd12005-08-24 17:22:17 +00001758
Chris Lattner57a28632006-01-23 05:57:36 +00001759 // Make sure that this function has the right prototype
Chris Lattner4201cd12005-08-24 17:22:17 +00001760 virtual bool ValidateCalledFunction(const Function *F, SimplifyLibCalls &SLC){
1761 return F->arg_size() == 1 && F->arg_begin()->getType() == Type::DoubleTy &&
1762 F->getReturnType() == Type::DoubleTy;
1763 }
Chris Lattner57a28632006-01-23 05:57:36 +00001764
1765 /// ShrinkFunctionToFloatVersion - If the input to this function is really a
1766 /// float, strength reduce this to a float version of the function,
1767 /// e.g. floor((double)FLT) -> (double)floorf(FLT). This can only be called
1768 /// when the target supports the destination function and where there can be
1769 /// no precision loss.
1770 static bool ShrinkFunctionToFloatVersion(CallInst *CI, SimplifyLibCalls &SLC,
Chris Lattner34acba42007-01-07 08:12:01 +00001771 Constant *(SimplifyLibCalls::*FP)()){
Chris Lattner485b6412007-04-07 00:42:32 +00001772 if (FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1)))
Chris Lattner4201cd12005-08-24 17:22:17 +00001773 if (Cast->getOperand(0)->getType() == Type::FloatTy) {
Chris Lattner57a28632006-01-23 05:57:36 +00001774 Value *New = new CallInst((SLC.*FP)(), Cast->getOperand(0),
Chris Lattner4201cd12005-08-24 17:22:17 +00001775 CI->getName(), CI);
Reid Spencer6c38f0b2006-11-27 01:05:10 +00001776 New = new FPExtInst(New, Type::DoubleTy, CI->getName(), CI);
Chris Lattner4201cd12005-08-24 17:22:17 +00001777 CI->replaceAllUsesWith(New);
1778 CI->eraseFromParent();
1779 if (Cast->use_empty())
1780 Cast->eraseFromParent();
1781 return true;
1782 }
Chris Lattner57a28632006-01-23 05:57:36 +00001783 return false;
Chris Lattner4201cd12005-08-24 17:22:17 +00001784 }
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001785};
1786
Chris Lattner57a28632006-01-23 05:57:36 +00001787
Reid Spencer557ab152007-02-05 23:32:05 +00001788struct VISIBILITY_HIDDEN FloorOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57a28632006-01-23 05:57:36 +00001789 FloorOptimization()
1790 : UnaryDoubleFPOptimizer("floor", "Number of 'floor' calls simplified") {}
1791
1792 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001793#ifdef HAVE_FLOORF
Chris Lattner57a28632006-01-23 05:57:36 +00001794 // If this is a float argument passed in, convert to floorf.
1795 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_floorf))
1796 return true;
Reid Spencerade18212006-01-19 08:36:56 +00001797#endif
Chris Lattner57a28632006-01-23 05:57:36 +00001798 return false; // opt failed
1799 }
1800} FloorOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001801
Reid Spencer557ab152007-02-05 23:32:05 +00001802struct VISIBILITY_HIDDEN CeilOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001803 CeilOptimization()
1804 : UnaryDoubleFPOptimizer("ceil", "Number of 'ceil' calls simplified") {}
1805
1806 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1807#ifdef HAVE_CEILF
1808 // If this is a float argument passed in, convert to ceilf.
1809 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_ceilf))
1810 return true;
1811#endif
1812 return false; // opt failed
1813 }
1814} CeilOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001815
Reid Spencer557ab152007-02-05 23:32:05 +00001816struct VISIBILITY_HIDDEN RoundOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001817 RoundOptimization()
1818 : UnaryDoubleFPOptimizer("round", "Number of 'round' calls simplified") {}
1819
1820 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1821#ifdef HAVE_ROUNDF
1822 // If this is a float argument passed in, convert to roundf.
1823 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_roundf))
1824 return true;
1825#endif
1826 return false; // opt failed
1827 }
1828} RoundOptimizer;
1829
Reid Spencer557ab152007-02-05 23:32:05 +00001830struct VISIBILITY_HIDDEN RintOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001831 RintOptimization()
1832 : UnaryDoubleFPOptimizer("rint", "Number of 'rint' calls simplified") {}
1833
1834 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1835#ifdef HAVE_RINTF
1836 // If this is a float argument passed in, convert to rintf.
1837 if (ShrinkFunctionToFloatVersion(CI, SLC, &SimplifyLibCalls::get_rintf))
1838 return true;
1839#endif
1840 return false; // opt failed
1841 }
1842} RintOptimizer;
1843
Reid Spencer557ab152007-02-05 23:32:05 +00001844struct VISIBILITY_HIDDEN NearByIntOptimization : public UnaryDoubleFPOptimizer {
Chris Lattner57740402006-01-23 06:24:46 +00001845 NearByIntOptimization()
1846 : UnaryDoubleFPOptimizer("nearbyint",
1847 "Number of 'nearbyint' calls simplified") {}
1848
1849 virtual bool OptimizeCall(CallInst *CI, SimplifyLibCalls &SLC) {
1850#ifdef HAVE_NEARBYINTF
1851 // If this is a float argument passed in, convert to nearbyintf.
1852 if (ShrinkFunctionToFloatVersion(CI, SLC,&SimplifyLibCalls::get_nearbyintf))
1853 return true;
1854#endif
1855 return false; // opt failed
1856 }
1857} NearByIntOptimizer;
Chris Lattner4201cd12005-08-24 17:22:17 +00001858
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001859/// GetConstantStringInfo - This function computes the length of a
1860/// null-terminated constant array of integers. This function can't rely on the
1861/// size of the constant array because there could be a null terminator in the
1862/// middle of the array.
1863///
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001864/// We also have to bail out if we find a non-integer constant initializer
1865/// of one of the elements or if there is no null-terminator. The logic
Reid Spencer7ddcfb32005-04-27 21:29:20 +00001866/// below checks each of these conditions and will return true only if all
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001867/// conditions are met. If the conditions aren't met, this returns false.
1868///
1869/// If successful, the \p Array param is set to the constant array being
1870/// indexed, the \p Length parameter is set to the length of the null-terminated
1871/// string pointed to by V, the \p StartIdx value is set to the first
1872/// element of the Array that V points to, and true is returned.
Chris Lattner182a9452007-04-07 21:58:02 +00001873static bool GetConstantStringInfo(Value *V, std::string &Str) {
1874 // Look through noop bitcast instructions.
1875 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V)) {
1876 if (BCI->getType() == BCI->getOperand(0)->getType())
1877 return GetConstantStringInfo(BCI->getOperand(0), Str);
1878 return false;
1879 }
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001880
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001881 // If the value is not a GEP instruction nor a constant expression with a
1882 // GEP instruction, then return false because ConstantArray can't occur
Reid Spencere249a822005-04-27 07:54:40 +00001883 // any other way
Chris Lattner182a9452007-04-07 21:58:02 +00001884 User *GEP = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001885 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
Reid Spencere249a822005-04-27 07:54:40 +00001886 GEP = GEPI;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001887 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
1888 if (CE->getOpcode() != Instruction::GetElementPtr)
Reid Spencere249a822005-04-27 07:54:40 +00001889 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001890 GEP = CE;
1891 } else {
Reid Spencere249a822005-04-27 07:54:40 +00001892 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001893 }
Reid Spencere249a822005-04-27 07:54:40 +00001894
1895 // Make sure the GEP has exactly three arguments.
1896 if (GEP->getNumOperands() != 3)
1897 return false;
1898
1899 // Check to make sure that the first operand of the GEP is an integer and
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001900 // has value 0 so that we are sure we're indexing into the initializer.
Chris Lattner182a9452007-04-07 21:58:02 +00001901 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
1902 if (!Idx->isZero())
Reid Spencere249a822005-04-27 07:54:40 +00001903 return false;
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001904 } else
Reid Spencere249a822005-04-27 07:54:40 +00001905 return false;
1906
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001907 // If the second index isn't a ConstantInt, then this is a variable index
1908 // into the array. If this occurs, we can't say anything meaningful about
1909 // the string.
Chris Lattner182a9452007-04-07 21:58:02 +00001910 uint64_t StartIdx = 0;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001911 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
1912 StartIdx = CI->getZExtValue();
Reid Spencere249a822005-04-27 07:54:40 +00001913 else
1914 return false;
1915
1916 // The GEP instruction, constant or instruction, must reference a global
1917 // variable that is a constant and is initialized. The referenced constant
1918 // initializer is the array that we'll use for optimization.
1919 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1920 if (!GV || !GV->isConstant() || !GV->hasInitializer())
1921 return false;
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001922 Constant *GlobalInit = GV->getInitializer();
Reid Spencere249a822005-04-27 07:54:40 +00001923
1924 // Handle the ConstantAggregateZero case
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001925 if (isa<ConstantAggregateZero>(GlobalInit)) {
Reid Spencere249a822005-04-27 07:54:40 +00001926 // This is a degenerate case. The initializer is constant zero so the
1927 // length of the string must be zero.
Chris Lattner182a9452007-04-07 21:58:02 +00001928 Str.clear();
Reid Spencere249a822005-04-27 07:54:40 +00001929 return true;
1930 }
1931
1932 // Must be a Constant Array
Chris Lattner182a9452007-04-07 21:58:02 +00001933 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001934 if (!Array) return false;
Reid Spencere249a822005-04-27 07:54:40 +00001935
1936 // Get the number of elements in the array
Chris Lattner9b2b8ab2007-04-06 22:54:17 +00001937 uint64_t NumElts = Array->getType()->getNumElements();
Reid Spencere249a822005-04-27 07:54:40 +00001938
Chris Lattner182a9452007-04-07 21:58:02 +00001939 // Traverse the constant array from StartIdx (derived above) which is
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001940 // the place the GEP refers to in the array.
Chris Lattner182a9452007-04-07 21:58:02 +00001941 for (unsigned i = StartIdx; i < NumElts; ++i) {
1942 Constant *Elt = Array->getOperand(i);
1943 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
1944 if (!CI) // This array isn't suitable, non-int initializer.
1945 return false;
1946 if (CI->isZero())
1947 return true; // we found end of string, success!
1948 Str += (char)CI->getZExtValue();
Reid Spencere249a822005-04-27 07:54:40 +00001949 }
Chris Lattner0d4ebfc2006-01-22 22:35:08 +00001950
Chris Lattner182a9452007-04-07 21:58:02 +00001951 return false; // The array isn't null terminated.
Reid Spencere249a822005-04-27 07:54:40 +00001952}
1953
Reid Spencera7828ba2005-06-18 17:46:28 +00001954/// CastToCStr - Return V if it is an sbyte*, otherwise cast it to sbyte*,
1955/// inserting the cast before IP, and return the cast.
1956/// @brief Cast a value to a "C" string.
Chris Lattnerbed184c2007-04-07 21:04:50 +00001957static Value *CastToCStr(Value *V, Instruction *IP) {
Reid Spencera730cf82006-12-13 08:04:32 +00001958 assert(isa<PointerType>(V->getType()) &&
Reid Spencerbfe26ff2006-12-13 00:50:17 +00001959 "Can't cast non-pointer type to C string type");
Christopher Lambedf07882007-12-17 01:12:55 +00001960 const Type *SBPTy = PointerType::getUnqual(Type::Int8Ty);
Reid Spencera7828ba2005-06-18 17:46:28 +00001961 if (V->getType() != SBPTy)
Chris Lattnerbed184c2007-04-07 21:04:50 +00001962 return new BitCastInst(V, SBPTy, V->getName(), IP);
Reid Spencera7828ba2005-06-18 17:46:28 +00001963 return V;
1964}
1965
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001966// TODO:
Reid Spencer649ac282005-04-28 04:40:06 +00001967// Additional cases that we need to add to this file:
1968//
Reid Spencer649ac282005-04-28 04:40:06 +00001969// cbrt:
Reid Spencer649ac282005-04-28 04:40:06 +00001970// * cbrt(expN(X)) -> expN(x/3)
1971// * cbrt(sqrt(x)) -> pow(x,1/6)
1972// * cbrt(sqrt(x)) -> pow(x,1/9)
1973//
Reid Spencer649ac282005-04-28 04:40:06 +00001974// cos, cosf, cosl:
Reid Spencer16983ca2005-04-28 18:05:16 +00001975// * cos(-x) -> cos(x)
Reid Spencer649ac282005-04-28 04:40:06 +00001976//
1977// exp, expf, expl:
Reid Spencer649ac282005-04-28 04:40:06 +00001978// * exp(log(x)) -> x
1979//
Reid Spencer649ac282005-04-28 04:40:06 +00001980// log, logf, logl:
Reid Spencer649ac282005-04-28 04:40:06 +00001981// * log(exp(x)) -> x
1982// * log(x**y) -> y*log(x)
1983// * log(exp(y)) -> y*log(e)
1984// * log(exp2(y)) -> y*log(2)
1985// * log(exp10(y)) -> y*log(10)
1986// * log(sqrt(x)) -> 0.5*log(x)
1987// * log(pow(x,y)) -> y*log(x)
1988//
1989// lround, lroundf, lroundl:
1990// * lround(cnst) -> cnst'
1991//
1992// memcmp:
Reid Spencer649ac282005-04-28 04:40:06 +00001993// * memcmp(x,y,l) -> cnst
1994// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
Reid Spencer649ac282005-04-28 04:40:06 +00001995//
Reid Spencer649ac282005-04-28 04:40:06 +00001996// memmove:
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00001997// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
Reid Spencer649ac282005-04-28 04:40:06 +00001998// (if s is a global constant array)
1999//
Reid Spencer649ac282005-04-28 04:40:06 +00002000// pow, powf, powl:
Reid Spencer649ac282005-04-28 04:40:06 +00002001// * pow(exp(x),y) -> exp(x*y)
2002// * pow(sqrt(x),y) -> pow(x,y*0.5)
2003// * pow(pow(x,y),z)-> pow(x,y*z)
2004//
2005// puts:
Chris Lattner49fa8d22007-04-14 01:17:48 +00002006// * puts("") -> putchar("\n")
Reid Spencer649ac282005-04-28 04:40:06 +00002007//
2008// round, roundf, roundl:
2009// * round(cnst) -> cnst'
2010//
2011// signbit:
2012// * signbit(cnst) -> cnst'
2013// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2014//
Reid Spencer649ac282005-04-28 04:40:06 +00002015// sqrt, sqrtf, sqrtl:
Reid Spencer649ac282005-04-28 04:40:06 +00002016// * sqrt(expN(x)) -> expN(x*0.5)
2017// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2018// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2019//
Reid Spencer170ae7f2005-05-07 20:15:59 +00002020// stpcpy:
2021// * stpcpy(str, "literal") ->
2022// llvm.memcpy(str,"literal",strlen("literal")+1,1)
Reid Spencer38cabd72005-05-03 07:23:44 +00002023// strrchr:
Reid Spencer649ac282005-04-28 04:40:06 +00002024// * strrchr(s,c) -> reverse_offset_of_in(c,s)
2025// (if c is a constant integer and s is a constant string)
2026// * strrchr(s1,0) -> strchr(s1,0)
2027//
Reid Spencer649ac282005-04-28 04:40:06 +00002028// strncat:
2029// * strncat(x,y,0) -> x
2030// * strncat(x,y,0) -> x (if strlen(y) = 0)
2031// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2032//
Reid Spencer649ac282005-04-28 04:40:06 +00002033// strncpy:
2034// * strncpy(d,s,0) -> d
2035// * strncpy(d,s,l) -> memcpy(d,s,l,1)
2036// (if s and l are constants)
2037//
2038// strpbrk:
2039// * strpbrk(s,a) -> offset_in_for(s,a)
2040// (if s and a are both constant strings)
2041// * strpbrk(s,"") -> 0
2042// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2043//
2044// strspn, strcspn:
2045// * strspn(s,a) -> const_int (if both args are constant)
2046// * strspn("",a) -> 0
2047// * strspn(s,"") -> 0
2048// * strcspn(s,a) -> const_int (if both args are constant)
2049// * strcspn("",a) -> 0
2050// * strcspn(s,"") -> strlen(a)
2051//
2052// strstr:
2053// * strstr(x,x) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002054// * strstr(s1,s2) -> offset_of_s2_in(s1)
Reid Spencer649ac282005-04-28 04:40:06 +00002055// (if s1 and s2 are constant strings)
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002056//
Reid Spencer649ac282005-04-28 04:40:06 +00002057// tan, tanf, tanl:
Reid Spencer649ac282005-04-28 04:40:06 +00002058// * tan(atan(x)) -> x
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002059//
Reid Spencer649ac282005-04-28 04:40:06 +00002060// trunc, truncf, truncl:
2061// * trunc(cnst) -> cnst'
2062//
Jeff Cohen5f4ef3c2005-07-27 06:12:32 +00002063//
Reid Spencer39a762d2005-04-25 02:53:12 +00002064}