blob: 2fbc25e0bd94e5ead16896da11211f397ec0243a [file] [log] [blame]
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001//===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements a simple pass that applies a variety of small
11// optimizations for calls to specific well-known function calls (e.g. runtime
12// library functions). For example, a call to the function "exit(3)" that
13// occurs within the main() function can be transformed into a simple "return 3"
14// instruction. Any optimization that takes this form (replace call to library
15// function with simpler code that provides the same result) belongs in this
16// file.
17//
18//===----------------------------------------------------------------------===//
19
20#define DEBUG_TYPE "simplify-libcalls"
21#include "llvm/Transforms/Scalar.h"
22#include "llvm/Intrinsics.h"
23#include "llvm/Module.h"
24#include "llvm/Pass.h"
25#include "llvm/Support/IRBuilder.h"
Evan Cheng0ff39b32008-06-30 07:31:25 +000026#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000027#include "llvm/Target/TargetData.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/ADT/Statistic.h"
31#include "llvm/Support/Compiler.h"
Chris Lattner56b4f2b2008-05-01 06:39:12 +000032#include "llvm/Support/Debug.h"
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000033#include "llvm/Config/config.h"
34using namespace llvm;
35
36STATISTIC(NumSimplified, "Number of library calls simplified");
37
38//===----------------------------------------------------------------------===//
39// Optimizer Base Class
40//===----------------------------------------------------------------------===//
41
42/// This class is the abstract base class for the set of optimizations that
43/// corresponds to one library call.
44namespace {
45class VISIBILITY_HIDDEN LibCallOptimization {
46protected:
47 Function *Caller;
48 const TargetData *TD;
49public:
50 LibCallOptimization() { }
51 virtual ~LibCallOptimization() {}
52
53 /// CallOptimizer - This pure virtual method is implemented by base classes to
54 /// do various optimizations. If this returns null then no transformation was
55 /// performed. If it returns CI, then it transformed the call and CI is to be
56 /// deleted. If it returns something else, replace CI with the new value and
57 /// delete CI.
Eric Christopher7a61d702008-08-08 19:39:37 +000058 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
59 =0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000060
Eric Christopher7a61d702008-08-08 19:39:37 +000061 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000062 Caller = CI->getParent()->getParent();
63 this->TD = &TD;
64 return CallOptimizer(CI->getCalledFunction(), CI, B);
65 }
66
67 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +000068 Value *CastToCStr(Value *V, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000069
70 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
71 /// specified pointer. Ptr is required to be some pointer type, and the
72 /// return value has 'intptr_t' type.
Eric Christopher7a61d702008-08-08 19:39:37 +000073 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000074
75 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
76 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
77 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +000078 unsigned Align, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000079
80 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
81 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
Eric Christopher7a61d702008-08-08 19:39:37 +000082 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000083
84 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
85 /// 'floor'). This function is known to take a single of type matching 'Op'
86 /// and returns one value with the same type. If 'Op' is a long double, 'l'
87 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
Eric Christopher7a61d702008-08-08 19:39:37 +000088 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000089
90 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
91 /// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +000092 void EmitPutChar(Value *Char, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000093
94 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
95 /// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +000096 void EmitPutS(Value *Str, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +000097
98 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
99 /// an i32, and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000100 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000101
102 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
103 /// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000104 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000105
106 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
107 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000108 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000109
110};
111} // End anonymous namespace.
112
113/// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
Eric Christopher7a61d702008-08-08 19:39:37 +0000114Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000115 return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
116}
117
118/// EmitStrLen - Emit a call to the strlen function to the builder, for the
119/// specified pointer. This always returns an integer value of size intptr_t.
Eric Christopher7a61d702008-08-08 19:39:37 +0000120Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000121 Module *M = Caller->getParent();
122 Constant *StrLen =M->getOrInsertFunction("strlen", TD->getIntPtrType(),
123 PointerType::getUnqual(Type::Int8Ty),
124 NULL);
125 return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
126}
127
128/// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
129/// expects that the size has type 'intptr_t' and Dst/Src are pointers.
130Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
Eric Christopher7a61d702008-08-08 19:39:37 +0000131 unsigned Align, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000132 Module *M = Caller->getParent();
Chris Lattner077707c2008-06-16 04:10:21 +0000133 Intrinsic::ID IID = Len->getType() == Type::Int32Ty ?
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000134 Intrinsic::memcpy_i32 : Intrinsic::memcpy_i64;
135 Value *MemCpy = Intrinsic::getDeclaration(M, IID);
136 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
137 ConstantInt::get(Type::Int32Ty, Align));
138}
139
140/// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
141/// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
142Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
Eric Christopher7a61d702008-08-08 19:39:37 +0000143 Value *Len, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000144 Module *M = Caller->getParent();
145 Value *MemChr = M->getOrInsertFunction("memchr",
146 PointerType::getUnqual(Type::Int8Ty),
147 PointerType::getUnqual(Type::Int8Ty),
148 Type::Int32Ty, TD->getIntPtrType(),
149 NULL);
150 return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
151}
152
153/// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
154/// 'floor'). This function is known to take a single of type matching 'Op' and
155/// returns one value with the same type. If 'Op' is a long double, 'l' is
156/// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
157Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
Eric Christopher7a61d702008-08-08 19:39:37 +0000158 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000159 char NameBuffer[20];
160 if (Op->getType() != Type::DoubleTy) {
161 // If we need to add a suffix, copy into NameBuffer.
162 unsigned NameLen = strlen(Name);
163 assert(NameLen < sizeof(NameBuffer)-2);
164 memcpy(NameBuffer, Name, NameLen);
165 if (Op->getType() == Type::FloatTy)
166 NameBuffer[NameLen] = 'f'; // floorf
167 else
168 NameBuffer[NameLen] = 'l'; // floorl
169 NameBuffer[NameLen+1] = 0;
170 Name = NameBuffer;
171 }
172
173 Module *M = Caller->getParent();
174 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
175 Op->getType(), NULL);
176 return B.CreateCall(Callee, Op, Name);
177}
178
179/// EmitPutChar - Emit a call to the putchar function. This assumes that Char
180/// is an integer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000181void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000182 Module *M = Caller->getParent();
183 Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
184 Type::Int32Ty, NULL);
185 B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
186}
187
188/// EmitPutS - Emit a call to the puts function. This assumes that Str is
189/// some pointer.
Eric Christopher7a61d702008-08-08 19:39:37 +0000190void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000191 Module *M = Caller->getParent();
192 Value *F = M->getOrInsertFunction("puts", Type::Int32Ty,
193 PointerType::getUnqual(Type::Int8Ty), NULL);
194 B.CreateCall(F, CastToCStr(Str, B), "puts");
195}
196
197/// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
198/// an integer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000199void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000200 Module *M = Caller->getParent();
201 Constant *F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
202 File->getType(), NULL);
203 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
204 B.CreateCall2(F, Char, File, "fputc");
205}
206
207/// EmitFPutS - Emit a call to the puts function. Str is required to be a
208/// pointer and File is a pointer to FILE.
Eric Christopher7a61d702008-08-08 19:39:37 +0000209void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000210 Module *M = Caller->getParent();
211 Constant *F = M->getOrInsertFunction("fputs", Type::Int32Ty,
212 PointerType::getUnqual(Type::Int8Ty),
213 File->getType(), NULL);
214 B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
215}
216
217/// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
218/// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
219void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
Eric Christopher7a61d702008-08-08 19:39:37 +0000220 IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000221 Module *M = Caller->getParent();
222 Constant *F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
223 PointerType::getUnqual(Type::Int8Ty),
224 TD->getIntPtrType(), TD->getIntPtrType(),
225 File->getType(), NULL);
226 B.CreateCall4(F, CastToCStr(Ptr, B), Size,
227 ConstantInt::get(TD->getIntPtrType(), 1), File);
228}
229
230//===----------------------------------------------------------------------===//
231// Helper Functions
232//===----------------------------------------------------------------------===//
233
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000234/// GetStringLengthH - If we can compute the length of the string pointed to by
235/// the specified pointer, return 'len+1'. If we can't, return 0.
236static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
237 // Look through noop bitcast instructions.
238 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
239 return GetStringLengthH(BCI->getOperand(0), PHIs);
240
241 // If this is a PHI node, there are two cases: either we have already seen it
242 // or we haven't.
243 if (PHINode *PN = dyn_cast<PHINode>(V)) {
244 if (!PHIs.insert(PN))
245 return ~0ULL; // already in the set.
246
247 // If it was new, see if all the input strings are the same length.
248 uint64_t LenSoFar = ~0ULL;
249 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
250 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
251 if (Len == 0) return 0; // Unknown length -> unknown.
252
253 if (Len == ~0ULL) continue;
254
255 if (Len != LenSoFar && LenSoFar != ~0ULL)
256 return 0; // Disagree -> unknown.
257 LenSoFar = Len;
258 }
259
260 // Success, all agree.
261 return LenSoFar;
262 }
263
264 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
265 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
266 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
267 if (Len1 == 0) return 0;
268 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
269 if (Len2 == 0) return 0;
270 if (Len1 == ~0ULL) return Len2;
271 if (Len2 == ~0ULL) return Len1;
272 if (Len1 != Len2) return 0;
273 return Len1;
274 }
275
276 // If the value is not a GEP instruction nor a constant expression with a
277 // GEP instruction, then return unknown.
278 User *GEP = 0;
279 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
280 GEP = GEPI;
281 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
282 if (CE->getOpcode() != Instruction::GetElementPtr)
283 return 0;
284 GEP = CE;
285 } else {
286 return 0;
287 }
288
289 // Make sure the GEP has exactly three arguments.
290 if (GEP->getNumOperands() != 3)
291 return 0;
292
293 // Check to make sure that the first operand of the GEP is an integer and
294 // has value 0 so that we are sure we're indexing into the initializer.
295 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
296 if (!Idx->isZero())
297 return 0;
298 } else
299 return 0;
300
301 // If the second index isn't a ConstantInt, then this is a variable index
302 // into the array. If this occurs, we can't say anything meaningful about
303 // the string.
304 uint64_t StartIdx = 0;
305 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
306 StartIdx = CI->getZExtValue();
307 else
308 return 0;
309
310 // The GEP instruction, constant or instruction, must reference a global
311 // variable that is a constant and is initialized. The referenced constant
312 // initializer is the array that we'll use for optimization.
313 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
314 if (!GV || !GV->isConstant() || !GV->hasInitializer())
315 return 0;
316 Constant *GlobalInit = GV->getInitializer();
317
318 // Handle the ConstantAggregateZero case, which is a degenerate case. The
319 // initializer is constant zero so the length of the string must be zero.
320 if (isa<ConstantAggregateZero>(GlobalInit))
321 return 1; // Len = 0 offset by 1.
322
323 // Must be a Constant Array
324 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
325 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
326 return false;
327
328 // Get the number of elements in the array
329 uint64_t NumElts = Array->getType()->getNumElements();
330
331 // Traverse the constant array from StartIdx (derived above) which is
332 // the place the GEP refers to in the array.
333 for (unsigned i = StartIdx; i != NumElts; ++i) {
334 Constant *Elt = Array->getOperand(i);
335 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
336 if (!CI) // This array isn't suitable, non-int initializer.
337 return 0;
338 if (CI->isZero())
339 return i-StartIdx+1; // We found end of string, success!
340 }
341
342 return 0; // The array isn't null terminated, conservatively return 'unknown'.
343}
344
345/// GetStringLength - If we can compute the length of the string pointed to by
346/// the specified pointer, return 'len+1'. If we can't, return 0.
347static uint64_t GetStringLength(Value *V) {
348 if (!isa<PointerType>(V->getType())) return 0;
349
350 SmallPtrSet<PHINode*, 32> PHIs;
351 uint64_t Len = GetStringLengthH(V, PHIs);
352 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
353 // an empty string as a length.
354 return Len == ~0ULL ? 1 : Len;
355}
356
357/// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
358/// value is equal or not-equal to zero.
359static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
360 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
361 UI != E; ++UI) {
362 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
363 if (IC->isEquality())
364 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
365 if (C->isNullValue())
366 continue;
367 // Unknown instruction.
368 return false;
369 }
370 return true;
371}
372
373//===----------------------------------------------------------------------===//
374// Miscellaneous LibCall Optimizations
375//===----------------------------------------------------------------------===//
376
Bill Wendlingac178222008-05-05 21:37:59 +0000377namespace {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000378//===---------------------------------------===//
379// 'exit' Optimizations
380
381/// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
382struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000383 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000384 // Verify we have a reasonable prototype for exit.
385 if (Callee->arg_size() == 0 || !CI->use_empty())
386 return 0;
387
388 // Verify the caller is main, and that the result type of main matches the
389 // argument type of exit.
390 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
391 Caller->getReturnType() != CI->getOperand(1)->getType())
392 return 0;
393
394 TerminatorInst *OldTI = CI->getParent()->getTerminator();
395
396 // Create the return after the call.
397 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
398
399 // Drop all successor phi node entries.
400 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
401 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
402
403 // Erase all instructions from after our return instruction until the end of
404 // the block.
405 BasicBlock::iterator FirstDead = RI; ++FirstDead;
406 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
407 return CI;
408 }
409};
410
411//===----------------------------------------------------------------------===//
412// String and Memory LibCall Optimizations
413//===----------------------------------------------------------------------===//
414
415//===---------------------------------------===//
416// 'strcat' Optimizations
417
418struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000419 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000420 // Verify the "strcat" function prototype.
421 const FunctionType *FT = Callee->getFunctionType();
422 if (FT->getNumParams() != 2 ||
423 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
424 FT->getParamType(0) != FT->getReturnType() ||
425 FT->getParamType(1) != FT->getReturnType())
426 return 0;
427
428 // Extract some information from the instruction
429 Value *Dst = CI->getOperand(1);
430 Value *Src = CI->getOperand(2);
431
432 // See if we can get the length of the input string.
433 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000434 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000435 --Len; // Unbias length.
436
437 // Handle the simple, do-nothing case: strcat(x, "") -> x
438 if (Len == 0)
439 return Dst;
440
441 // We need to find the end of the destination string. That's where the
442 // memory is to be moved to. We just generate a call to strlen.
443 Value *DstLen = EmitStrLen(Dst, B);
444
445 // Now that we have the destination's length, we must index into the
446 // destination's pointer to get the actual memcpy destination (end of
447 // the string .. we're concatenating).
448 Dst = B.CreateGEP(Dst, DstLen, "endptr");
449
450 // We have enough information to now generate the memcpy call to do the
451 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
452 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
453 return Dst;
454 }
455};
456
457//===---------------------------------------===//
458// 'strchr' Optimizations
459
460struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000461 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000462 // Verify the "strchr" function prototype.
463 const FunctionType *FT = Callee->getFunctionType();
464 if (FT->getNumParams() != 2 ||
465 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
466 FT->getParamType(0) != FT->getReturnType())
467 return 0;
468
469 Value *SrcStr = CI->getOperand(1);
470
471 // If the second operand is non-constant, see if we can compute the length
472 // of the input string and turn this into memchr.
473 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
474 if (CharC == 0) {
475 uint64_t Len = GetStringLength(SrcStr);
476 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
477 return 0;
478
479 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
480 ConstantInt::get(TD->getIntPtrType(), Len), B);
481 }
482
483 // Otherwise, the character is a constant, see if the first argument is
484 // a string literal. If so, we can constant fold.
485 std::string Str;
486 if (!GetConstantStringInfo(SrcStr, Str))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000487 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000488
489 // strchr can find the nul character.
490 Str += '\0';
491 char CharValue = CharC->getSExtValue();
492
493 // Compute the offset.
494 uint64_t i = 0;
495 while (1) {
496 if (i == Str.size()) // Didn't find the char. strchr returns null.
497 return Constant::getNullValue(CI->getType());
498 // Did we find our match?
499 if (Str[i] == CharValue)
500 break;
501 ++i;
502 }
503
504 // strchr(s+n,c) -> gep(s+n+i,c)
505 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
506 return B.CreateGEP(SrcStr, Idx, "strchr");
507 }
508};
509
510//===---------------------------------------===//
511// 'strcmp' Optimizations
512
513struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000514 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000515 // Verify the "strcmp" function prototype.
516 const FunctionType *FT = Callee->getFunctionType();
517 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
518 FT->getParamType(0) != FT->getParamType(1) ||
519 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
520 return 0;
521
522 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
523 if (Str1P == Str2P) // strcmp(x,x) -> 0
524 return ConstantInt::get(CI->getType(), 0);
525
526 std::string Str1, Str2;
527 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
528 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
529
530 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
531 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
532
533 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
534 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
535
536 // strcmp(x, y) -> cnst (if both x and y are constant strings)
537 if (HasStr1 && HasStr2)
538 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
539 return 0;
540 }
541};
542
543//===---------------------------------------===//
544// 'strncmp' Optimizations
545
546struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000547 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000548 // Verify the "strncmp" function prototype.
549 const FunctionType *FT = Callee->getFunctionType();
550 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
551 FT->getParamType(0) != FT->getParamType(1) ||
552 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
553 !isa<IntegerType>(FT->getParamType(2)))
554 return 0;
555
556 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
557 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
558 return ConstantInt::get(CI->getType(), 0);
559
560 // Get the length argument if it is constant.
561 uint64_t Length;
562 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
563 Length = LengthArg->getZExtValue();
564 else
565 return 0;
566
567 if (Length == 0) // strncmp(x,y,0) -> 0
568 return ConstantInt::get(CI->getType(), 0);
569
570 std::string Str1, Str2;
571 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
572 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
573
574 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
575 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
576
577 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
578 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
579
580 // strncmp(x, y) -> cnst (if both x and y are constant strings)
581 if (HasStr1 && HasStr2)
582 return ConstantInt::get(CI->getType(),
583 strncmp(Str1.c_str(), Str2.c_str(), Length));
584 return 0;
585 }
586};
587
588
589//===---------------------------------------===//
590// 'strcpy' Optimizations
591
592struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000593 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000594 // Verify the "strcpy" function prototype.
595 const FunctionType *FT = Callee->getFunctionType();
596 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
597 FT->getParamType(0) != FT->getParamType(1) ||
598 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
599 return 0;
600
601 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
602 if (Dst == Src) // strcpy(x,x) -> x
603 return Src;
604
605 // See if we can get the length of the input string.
606 uint64_t Len = GetStringLength(Src);
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000607 if (Len == 0) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000608
609 // We have enough information to now generate the memcpy call to do the
610 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
611 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
612 return Dst;
613 }
614};
615
616
617
618//===---------------------------------------===//
619// 'strlen' Optimizations
620
621struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000622 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000623 const FunctionType *FT = Callee->getFunctionType();
624 if (FT->getNumParams() != 1 ||
625 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
626 !isa<IntegerType>(FT->getReturnType()))
627 return 0;
628
629 Value *Src = CI->getOperand(1);
630
631 // Constant folding: strlen("xyz") -> 3
632 if (uint64_t Len = GetStringLength(Src))
633 return ConstantInt::get(CI->getType(), Len-1);
634
635 // Handle strlen(p) != 0.
636 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
637
638 // strlen(x) != 0 --> *x != 0
639 // strlen(x) == 0 --> *x == 0
640 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
641 }
642};
643
644//===---------------------------------------===//
645// 'memcmp' Optimizations
646
647struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000648 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000649 const FunctionType *FT = Callee->getFunctionType();
650 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
651 !isa<PointerType>(FT->getParamType(1)) ||
652 FT->getReturnType() != Type::Int32Ty)
653 return 0;
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000654
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000655 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000656
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000657 if (LHS == RHS) // memcmp(s,s,x) -> 0
658 return Constant::getNullValue(CI->getType());
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000659
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000660 // Make sure we have a constant length.
661 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000662 if (!LenC) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000663 uint64_t Len = LenC->getZExtValue();
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000664
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000665 if (Len == 0) // memcmp(s1,s2,0) -> 0
666 return Constant::getNullValue(CI->getType());
667
668 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
669 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
670 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
671 return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
672 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000673
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000674 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
675 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
676 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000677 const Type *PTy = PointerType::getUnqual(Len == 2 ?
678 Type::Int16Ty : Type::Int32Ty);
679 LHS = B.CreateBitCast(LHS, PTy, "tmp");
680 RHS = B.CreateBitCast(RHS, PTy, "tmp");
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000681 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
682 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
683 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
684 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
685 }
Duncan Sandsec00fcb2008-05-19 09:27:24 +0000686
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000687 return 0;
688 }
689};
690
691//===---------------------------------------===//
692// 'memcpy' Optimizations
693
694struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000695 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000696 const FunctionType *FT = Callee->getFunctionType();
697 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
698 !isa<PointerType>(FT->getParamType(0)) ||
699 !isa<PointerType>(FT->getParamType(1)) ||
700 FT->getParamType(2) != TD->getIntPtrType())
701 return 0;
702
703 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
704 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
705 return CI->getOperand(1);
706 }
707};
708
709//===----------------------------------------------------------------------===//
710// Math Library Optimizations
711//===----------------------------------------------------------------------===//
712
713//===---------------------------------------===//
714// 'pow*' Optimizations
715
716struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000717 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000718 const FunctionType *FT = Callee->getFunctionType();
719 // Just make sure this has 2 arguments of the same FP type, which match the
720 // result type.
721 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
722 FT->getParamType(0) != FT->getParamType(1) ||
723 !FT->getParamType(0)->isFloatingPoint())
724 return 0;
725
726 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
727 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
728 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
729 return Op1C;
730 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
731 return EmitUnaryFloatFnCall(Op2, "exp2", B);
732 }
733
734 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
735 if (Op2C == 0) return 0;
736
737 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
738 return ConstantFP::get(CI->getType(), 1.0);
739
740 if (Op2C->isExactlyValue(0.5)) {
741 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
742 // 'unsafe' math optimizations are allowed.
743 // x pow(x, 0.5) sqrt(x)
744 // ---------------------------------------------
745 // -0.0 +0.0 -0.0
746 // -inf +inf NaN
747#if 0
748 // pow(x, 0.5) -> sqrt(x)
749 return B.CreateCall(get_sqrt(), Op1, "sqrt");
750#endif
751 }
752
753 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
754 return Op1;
755 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
756 return B.CreateMul(Op1, Op1, "pow2");
757 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
758 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
759 return 0;
760 }
761};
762
763//===---------------------------------------===//
Chris Lattnere818f772008-05-02 18:43:35 +0000764// 'exp2' Optimizations
765
766struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000767 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnere818f772008-05-02 18:43:35 +0000768 const FunctionType *FT = Callee->getFunctionType();
769 // Just make sure this has 1 argument of FP type, which matches the
770 // result type.
771 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
772 !FT->getParamType(0)->isFloatingPoint())
773 return 0;
774
775 Value *Op = CI->getOperand(1);
776 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
777 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
778 Value *LdExpArg = 0;
779 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
780 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
781 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
782 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
783 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
784 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
785 }
786
787 if (LdExpArg) {
788 const char *Name;
789 if (Op->getType() == Type::FloatTy)
790 Name = "ldexpf";
791 else if (Op->getType() == Type::DoubleTy)
792 Name = "ldexp";
793 else
794 Name = "ldexpl";
795
796 Constant *One = ConstantFP::get(APFloat(1.0f));
797 if (Op->getType() != Type::FloatTy)
798 One = ConstantExpr::getFPExtend(One, Op->getType());
799
800 Module *M = Caller->getParent();
801 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
802 Op->getType(), Type::Int32Ty,NULL);
803 return B.CreateCall2(Callee, One, LdExpArg);
804 }
805 return 0;
806 }
807};
808
809
810//===---------------------------------------===//
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000811// Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
812
813struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000814 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000815 const FunctionType *FT = Callee->getFunctionType();
816 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
817 FT->getParamType(0) != Type::DoubleTy)
818 return 0;
819
820 // If this is something like 'floor((double)floatval)', convert to floorf.
821 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
822 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
823 return 0;
824
825 // floor((double)floatval) -> (double)floorf(floatval)
826 Value *V = Cast->getOperand(0);
827 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
828 return B.CreateFPExt(V, Type::DoubleTy);
829 }
830};
831
832//===----------------------------------------------------------------------===//
833// Integer Optimizations
834//===----------------------------------------------------------------------===//
835
836//===---------------------------------------===//
837// 'ffs*' Optimizations
838
839struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000840 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000841 const FunctionType *FT = Callee->getFunctionType();
842 // Just make sure this has 2 arguments of the same FP type, which match the
843 // result type.
844 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
845 !isa<IntegerType>(FT->getParamType(0)))
846 return 0;
847
848 Value *Op = CI->getOperand(1);
849
850 // Constant fold.
851 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
852 if (CI->getValue() == 0) // ffs(0) -> 0.
853 return Constant::getNullValue(CI->getType());
854 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
855 CI->getValue().countTrailingZeros()+1);
856 }
857
858 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
859 const Type *ArgType = Op->getType();
860 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
861 Intrinsic::cttz, &ArgType, 1);
862 Value *V = B.CreateCall(F, Op, "cttz");
863 V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
864 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
865
866 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
867 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
868 }
869};
870
871//===---------------------------------------===//
872// 'isdigit' Optimizations
873
874struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000875 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000876 const FunctionType *FT = Callee->getFunctionType();
877 // We require integer(i32)
878 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
879 FT->getParamType(0) != Type::Int32Ty)
880 return 0;
881
882 // isdigit(c) -> (c-'0') <u 10
883 Value *Op = CI->getOperand(1);
884 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
885 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
886 return B.CreateZExt(Op, CI->getType());
887 }
888};
889
890//===---------------------------------------===//
891// 'isascii' Optimizations
892
893struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000894 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000895 const FunctionType *FT = Callee->getFunctionType();
896 // We require integer(i32)
897 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
898 FT->getParamType(0) != Type::Int32Ty)
899 return 0;
900
901 // isascii(c) -> c <u 128
902 Value *Op = CI->getOperand(1);
903 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
904 return B.CreateZExt(Op, CI->getType());
905 }
906};
Chris Lattner313f0e62008-06-09 08:26:51 +0000907
908//===---------------------------------------===//
909// 'abs', 'labs', 'llabs' Optimizations
910
911struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000912 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattner313f0e62008-06-09 08:26:51 +0000913 const FunctionType *FT = Callee->getFunctionType();
914 // We require integer(integer) where the types agree.
915 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
916 FT->getParamType(0) != FT->getReturnType())
917 return 0;
918
919 // abs(x) -> x >s -1 ? x : -x
920 Value *Op = CI->getOperand(1);
921 Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
922 "ispos");
923 Value *Neg = B.CreateNeg(Op, "neg");
924 return B.CreateSelect(Pos, Op, Neg);
925 }
926};
927
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000928
929//===---------------------------------------===//
930// 'toascii' Optimizations
931
932struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000933 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000934 const FunctionType *FT = Callee->getFunctionType();
935 // We require i32(i32)
936 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
937 FT->getParamType(0) != Type::Int32Ty)
938 return 0;
939
940 // isascii(c) -> c & 0x7f
941 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
942 }
943};
944
945//===----------------------------------------------------------------------===//
946// Formatting and IO Optimizations
947//===----------------------------------------------------------------------===//
948
949//===---------------------------------------===//
950// 'printf' Optimizations
951
952struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +0000953 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000954 // Require one fixed pointer argument and an integer/void result.
955 const FunctionType *FT = Callee->getFunctionType();
956 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
957 !(isa<IntegerType>(FT->getReturnType()) ||
958 FT->getReturnType() == Type::VoidTy))
959 return 0;
960
961 // Check for a fixed format string.
962 std::string FormatStr;
963 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
Chris Lattner56b4f2b2008-05-01 06:39:12 +0000964 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +0000965
966 // Empty format string -> noop.
967 if (FormatStr.empty()) // Tolerate printf's declared void.
968 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
969
970 // printf("x") -> putchar('x'), even for '%'.
971 if (FormatStr.size() == 1) {
972 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
973 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
974 }
975
976 // printf("foo\n") --> puts("foo")
977 if (FormatStr[FormatStr.size()-1] == '\n' &&
978 FormatStr.find('%') == std::string::npos) { // no format characters.
979 // Create a string literal with no \n on it. We expect the constant merge
980 // pass to be run after this pass, to merge duplicate strings.
981 FormatStr.erase(FormatStr.end()-1);
982 Constant *C = ConstantArray::get(FormatStr, true);
983 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
984 C, "str", Callee->getParent());
985 EmitPutS(C, B);
986 return CI->use_empty() ? (Value*)CI :
987 ConstantInt::get(CI->getType(), FormatStr.size()+1);
988 }
989
990 // Optimize specific format strings.
991 // printf("%c", chr) --> putchar(*(i8*)dst)
992 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
993 isa<IntegerType>(CI->getOperand(2)->getType())) {
994 EmitPutChar(CI->getOperand(2), B);
995 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
996 }
997
998 // printf("%s\n", str) --> puts(str)
999 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1000 isa<PointerType>(CI->getOperand(2)->getType()) &&
1001 CI->use_empty()) {
1002 EmitPutS(CI->getOperand(2), B);
1003 return CI;
1004 }
1005 return 0;
1006 }
1007};
1008
1009//===---------------------------------------===//
1010// 'sprintf' Optimizations
1011
1012struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001013 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001014 // Require two fixed pointer arguments and an integer result.
1015 const FunctionType *FT = Callee->getFunctionType();
1016 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1017 !isa<PointerType>(FT->getParamType(1)) ||
1018 !isa<IntegerType>(FT->getReturnType()))
1019 return 0;
1020
1021 // Check for a fixed format string.
1022 std::string FormatStr;
1023 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001024 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001025
1026 // If we just have a format string (nothing else crazy) transform it.
1027 if (CI->getNumOperands() == 3) {
1028 // Make sure there's no % in the constant array. We could try to handle
1029 // %% -> % in the future if we cared.
1030 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1031 if (FormatStr[i] == '%')
1032 return 0; // we found a format specifier, bail out.
1033
1034 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1035 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1036 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1037 return ConstantInt::get(CI->getType(), FormatStr.size());
1038 }
1039
1040 // The remaining optimizations require the format string to be "%s" or "%c"
1041 // and have an extra operand.
1042 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1043 return 0;
1044
1045 // Decode the second character of the format string.
1046 if (FormatStr[1] == 'c') {
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001047 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001048 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1049 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001050 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1051 B.CreateStore(V, Ptr);
1052 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1053 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1054
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001055 return ConstantInt::get(CI->getType(), 1);
1056 }
1057
1058 if (FormatStr[1] == 's') {
1059 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1060 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1061
1062 Value *Len = EmitStrLen(CI->getOperand(3), B);
1063 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1064 "leninc");
1065 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1066
1067 // The sprintf result is the unincremented number of bytes in the string.
1068 return B.CreateIntCast(Len, CI->getType(), false);
1069 }
1070 return 0;
1071 }
1072};
1073
1074//===---------------------------------------===//
1075// 'fwrite' Optimizations
1076
1077struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001078 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001079 // Require a pointer, an integer, an integer, a pointer, returning integer.
1080 const FunctionType *FT = Callee->getFunctionType();
1081 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1082 !isa<IntegerType>(FT->getParamType(1)) ||
1083 !isa<IntegerType>(FT->getParamType(2)) ||
1084 !isa<PointerType>(FT->getParamType(3)) ||
1085 !isa<IntegerType>(FT->getReturnType()))
1086 return 0;
1087
1088 // Get the element size and count.
1089 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1090 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1091 if (!SizeC || !CountC) return 0;
1092 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1093
1094 // If this is writing zero records, remove the call (it's a noop).
1095 if (Bytes == 0)
1096 return ConstantInt::get(CI->getType(), 0);
1097
1098 // If this is writing one byte, turn it into fputc.
1099 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1100 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1101 EmitFPutC(Char, CI->getOperand(4), B);
1102 return ConstantInt::get(CI->getType(), 1);
1103 }
1104
1105 return 0;
1106 }
1107};
1108
1109//===---------------------------------------===//
1110// 'fputs' Optimizations
1111
1112struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001113 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001114 // Require two pointers. Also, we can't optimize if return value is used.
1115 const FunctionType *FT = Callee->getFunctionType();
1116 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1117 !isa<PointerType>(FT->getParamType(1)) ||
1118 !CI->use_empty())
1119 return 0;
1120
1121 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1122 uint64_t Len = GetStringLength(CI->getOperand(1));
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001123 if (!Len) return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001124 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1125 CI->getOperand(2), B);
1126 return CI; // Known to have no uses (see above).
1127 }
1128};
1129
1130//===---------------------------------------===//
1131// 'fprintf' Optimizations
1132
1133struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
Eric Christopher7a61d702008-08-08 19:39:37 +00001134 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001135 // Require two fixed paramters as pointers and integer result.
1136 const FunctionType *FT = Callee->getFunctionType();
1137 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1138 !isa<PointerType>(FT->getParamType(1)) ||
1139 !isa<IntegerType>(FT->getReturnType()))
1140 return 0;
1141
1142 // All the optimizations depend on the format string.
1143 std::string FormatStr;
1144 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001145 return 0;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001146
1147 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1148 if (CI->getNumOperands() == 3) {
1149 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1150 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001151 return 0; // We found a format specifier.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001152
1153 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1154 FormatStr.size()),
1155 CI->getOperand(1), B);
1156 return ConstantInt::get(CI->getType(), FormatStr.size());
1157 }
1158
1159 // The remaining optimizations require the format string to be "%s" or "%c"
1160 // and have an extra operand.
1161 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1162 return 0;
1163
1164 // Decode the second character of the format string.
1165 if (FormatStr[1] == 'c') {
1166 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1167 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1168 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1169 return ConstantInt::get(CI->getType(), 1);
1170 }
1171
1172 if (FormatStr[1] == 's') {
1173 // fprintf(F, "%s", str) -> fputs(str, F)
1174 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1175 return 0;
1176 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1177 return CI;
1178 }
1179 return 0;
1180 }
1181};
1182
Bill Wendlingac178222008-05-05 21:37:59 +00001183} // end anonymous namespace.
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001184
1185//===----------------------------------------------------------------------===//
1186// SimplifyLibCalls Pass Implementation
1187//===----------------------------------------------------------------------===//
1188
1189namespace {
1190 /// This pass optimizes well known library functions from libc and libm.
1191 ///
1192 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1193 StringMap<LibCallOptimization*> Optimizations;
1194 // Miscellaneous LibCall Optimizations
1195 ExitOpt Exit;
1196 // String and Memory LibCall Optimizations
1197 StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1198 StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt MemCpy;
1199 // Math Library Optimizations
Chris Lattnere818f772008-05-02 18:43:35 +00001200 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001201 // Integer Optimizations
Chris Lattner313f0e62008-06-09 08:26:51 +00001202 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1203 ToAsciiOpt ToAscii;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001204 // Formatting and IO Optimizations
1205 SPrintFOpt SPrintF; PrintFOpt PrintF;
1206 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1207 public:
1208 static char ID; // Pass identification
Dan Gohmanae73dc12008-09-04 17:05:41 +00001209 SimplifyLibCalls() : FunctionPass(&ID) {}
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001210
1211 void InitOptimizations();
1212 bool runOnFunction(Function &F);
1213
1214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1215 AU.addRequired<TargetData>();
1216 }
1217 };
1218 char SimplifyLibCalls::ID = 0;
1219} // end anonymous namespace.
1220
1221static RegisterPass<SimplifyLibCalls>
1222X("simplify-libcalls", "Simplify well-known library calls");
1223
1224// Public interface to the Simplify LibCalls pass.
1225FunctionPass *llvm::createSimplifyLibCallsPass() {
1226 return new SimplifyLibCalls();
1227}
1228
1229/// Optimizations - Populate the Optimizations map with all the optimizations
1230/// we know.
1231void SimplifyLibCalls::InitOptimizations() {
1232 // Miscellaneous LibCall Optimizations
1233 Optimizations["exit"] = &Exit;
1234
1235 // String and Memory LibCall Optimizations
1236 Optimizations["strcat"] = &StrCat;
1237 Optimizations["strchr"] = &StrChr;
1238 Optimizations["strcmp"] = &StrCmp;
1239 Optimizations["strncmp"] = &StrNCmp;
1240 Optimizations["strcpy"] = &StrCpy;
1241 Optimizations["strlen"] = &StrLen;
1242 Optimizations["memcmp"] = &MemCmp;
1243 Optimizations["memcpy"] = &MemCpy;
1244
1245 // Math Library Optimizations
1246 Optimizations["powf"] = &Pow;
1247 Optimizations["pow"] = &Pow;
1248 Optimizations["powl"] = &Pow;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001249 Optimizations["llvm.pow.f32"] = &Pow;
1250 Optimizations["llvm.pow.f64"] = &Pow;
1251 Optimizations["llvm.pow.f80"] = &Pow;
1252 Optimizations["llvm.pow.f128"] = &Pow;
1253 Optimizations["llvm.pow.ppcf128"] = &Pow;
Chris Lattnere818f772008-05-02 18:43:35 +00001254 Optimizations["exp2l"] = &Exp2;
1255 Optimizations["exp2"] = &Exp2;
1256 Optimizations["exp2f"] = &Exp2;
Dale Johannesen53bfbbc2008-09-04 18:30:46 +00001257 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1258 Optimizations["llvm.exp2.f128"] = &Exp2;
1259 Optimizations["llvm.exp2.f80"] = &Exp2;
1260 Optimizations["llvm.exp2.f64"] = &Exp2;
1261 Optimizations["llvm.exp2.f32"] = &Exp2;
Chris Lattnere818f772008-05-02 18:43:35 +00001262
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001263#ifdef HAVE_FLOORF
1264 Optimizations["floor"] = &UnaryDoubleFP;
1265#endif
1266#ifdef HAVE_CEILF
1267 Optimizations["ceil"] = &UnaryDoubleFP;
1268#endif
1269#ifdef HAVE_ROUNDF
1270 Optimizations["round"] = &UnaryDoubleFP;
1271#endif
1272#ifdef HAVE_RINTF
1273 Optimizations["rint"] = &UnaryDoubleFP;
1274#endif
1275#ifdef HAVE_NEARBYINTF
1276 Optimizations["nearbyint"] = &UnaryDoubleFP;
1277#endif
1278
1279 // Integer Optimizations
1280 Optimizations["ffs"] = &FFS;
1281 Optimizations["ffsl"] = &FFS;
1282 Optimizations["ffsll"] = &FFS;
Chris Lattner313f0e62008-06-09 08:26:51 +00001283 Optimizations["abs"] = &Abs;
1284 Optimizations["labs"] = &Abs;
1285 Optimizations["llabs"] = &Abs;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001286 Optimizations["isdigit"] = &IsDigit;
1287 Optimizations["isascii"] = &IsAscii;
1288 Optimizations["toascii"] = &ToAscii;
1289
1290 // Formatting and IO Optimizations
1291 Optimizations["sprintf"] = &SPrintF;
1292 Optimizations["printf"] = &PrintF;
1293 Optimizations["fwrite"] = &FWrite;
1294 Optimizations["fputs"] = &FPuts;
1295 Optimizations["fprintf"] = &FPrintF;
1296}
1297
1298
1299/// runOnFunction - Top level algorithm.
1300///
1301bool SimplifyLibCalls::runOnFunction(Function &F) {
1302 if (Optimizations.empty())
1303 InitOptimizations();
1304
1305 const TargetData &TD = getAnalysis<TargetData>();
1306
Eric Christopher7a61d702008-08-08 19:39:37 +00001307 IRBuilder<> Builder;
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001308
1309 bool Changed = false;
1310 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1311 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1312 // Ignore non-calls.
1313 CallInst *CI = dyn_cast<CallInst>(I++);
1314 if (!CI) continue;
1315
1316 // Ignore indirect calls and calls to non-external functions.
1317 Function *Callee = CI->getCalledFunction();
1318 if (Callee == 0 || !Callee->isDeclaration() ||
1319 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1320 continue;
1321
1322 // Ignore unknown calls.
1323 const char *CalleeName = Callee->getNameStart();
1324 StringMap<LibCallOptimization*>::iterator OMI =
1325 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1326 if (OMI == Optimizations.end()) continue;
1327
1328 // Set the builder to the instruction after the call.
1329 Builder.SetInsertPoint(BB, I);
1330
1331 // Try to optimize this call.
1332 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1333 if (Result == 0) continue;
1334
Chris Lattner56b4f2b2008-05-01 06:39:12 +00001335 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1336 DOUT << " into: " << *Result << "\n");
1337
Chris Lattnerfd1cbbe2008-05-01 06:25:24 +00001338 // Something changed!
1339 Changed = true;
1340 ++NumSimplified;
1341
1342 // Inspect the instruction after the call (which was potentially just
1343 // added) next.
1344 I = CI; ++I;
1345
1346 if (CI != Result && !CI->use_empty()) {
1347 CI->replaceAllUsesWith(Result);
1348 if (!Result->hasName())
1349 Result->takeName(CI);
1350 }
1351 CI->eraseFromParent();
1352 }
1353 }
1354 return Changed;
1355}
1356
1357
1358// TODO:
1359// Additional cases that we need to add to this file:
1360//
1361// cbrt:
1362// * cbrt(expN(X)) -> expN(x/3)
1363// * cbrt(sqrt(x)) -> pow(x,1/6)
1364// * cbrt(sqrt(x)) -> pow(x,1/9)
1365//
1366// cos, cosf, cosl:
1367// * cos(-x) -> cos(x)
1368//
1369// exp, expf, expl:
1370// * exp(log(x)) -> x
1371//
1372// log, logf, logl:
1373// * log(exp(x)) -> x
1374// * log(x**y) -> y*log(x)
1375// * log(exp(y)) -> y*log(e)
1376// * log(exp2(y)) -> y*log(2)
1377// * log(exp10(y)) -> y*log(10)
1378// * log(sqrt(x)) -> 0.5*log(x)
1379// * log(pow(x,y)) -> y*log(x)
1380//
1381// lround, lroundf, lroundl:
1382// * lround(cnst) -> cnst'
1383//
1384// memcmp:
1385// * memcmp(x,y,l) -> cnst
1386// (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1387//
1388// memmove:
1389// * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1390// (if s is a global constant array)
1391//
1392// pow, powf, powl:
1393// * pow(exp(x),y) -> exp(x*y)
1394// * pow(sqrt(x),y) -> pow(x,y*0.5)
1395// * pow(pow(x,y),z)-> pow(x,y*z)
1396//
1397// puts:
1398// * puts("") -> putchar("\n")
1399//
1400// round, roundf, roundl:
1401// * round(cnst) -> cnst'
1402//
1403// signbit:
1404// * signbit(cnst) -> cnst'
1405// * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1406//
1407// sqrt, sqrtf, sqrtl:
1408// * sqrt(expN(x)) -> expN(x*0.5)
1409// * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1410// * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1411//
1412// stpcpy:
1413// * stpcpy(str, "literal") ->
1414// llvm.memcpy(str,"literal",strlen("literal")+1,1)
1415// strrchr:
1416// * strrchr(s,c) -> reverse_offset_of_in(c,s)
1417// (if c is a constant integer and s is a constant string)
1418// * strrchr(s1,0) -> strchr(s1,0)
1419//
1420// strncat:
1421// * strncat(x,y,0) -> x
1422// * strncat(x,y,0) -> x (if strlen(y) = 0)
1423// * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1424//
1425// strncpy:
1426// * strncpy(d,s,0) -> d
1427// * strncpy(d,s,l) -> memcpy(d,s,l,1)
1428// (if s and l are constants)
1429//
1430// strpbrk:
1431// * strpbrk(s,a) -> offset_in_for(s,a)
1432// (if s and a are both constant strings)
1433// * strpbrk(s,"") -> 0
1434// * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1435//
1436// strspn, strcspn:
1437// * strspn(s,a) -> const_int (if both args are constant)
1438// * strspn("",a) -> 0
1439// * strspn(s,"") -> 0
1440// * strcspn(s,a) -> const_int (if both args are constant)
1441// * strcspn("",a) -> 0
1442// * strcspn(s,"") -> strlen(a)
1443//
1444// strstr:
1445// * strstr(x,x) -> x
1446// * strstr(s1,s2) -> offset_of_s2_in(s1)
1447// (if s1 and s2 are constant strings)
1448//
1449// tan, tanf, tanl:
1450// * tan(atan(x)) -> x
1451//
1452// trunc, truncf, truncl:
1453// * trunc(cnst) -> cnst'
1454//
1455//