1 //===- SimplifyLibCalls.cpp - Optimize specific well-known library calls --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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). Any optimization that takes the very simple form
13 // "replace call to library function with simpler code that provides the same
14 // result" belongs in this file.
16 //===----------------------------------------------------------------------===//
18 #define DEBUG_TYPE "simplify-libcalls"
19 #include "llvm/Transforms/Scalar.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/LLVMContext.h"
22 #include "llvm/Module.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/IRBuilder.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/Statistic.h"
30 #include "llvm/ADT/STLExtras.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Config/config.h"
36 STATISTIC(NumSimplified, "Number of library calls simplified");
37 STATISTIC(NumAnnotated, "Number of attributes added to library functions");
39 //===----------------------------------------------------------------------===//
40 // Optimizer Base Class
41 //===----------------------------------------------------------------------===//
43 /// This class is the abstract base class for the set of optimizations that
44 /// corresponds to one library call.
46 class LibCallOptimization {
52 LibCallOptimization() { }
53 virtual ~LibCallOptimization() {}
55 /// CallOptimizer - This pure virtual method is implemented by base classes to
56 /// do various optimizations. If this returns null then no transformation was
57 /// performed. If it returns CI, then it transformed the call and CI is to be
58 /// deleted. If it returns something else, replace CI with the new value and
60 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
63 Value *OptimizeCall(CallInst *CI, const TargetData *TD, IRBuilder<> &B) {
64 Caller = CI->getParent()->getParent();
66 if (CI->getCalledFunction())
67 Context = &CI->getCalledFunction()->getContext();
68 return CallOptimizer(CI->getCalledFunction(), CI, B);
71 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
72 Value *CastToCStr(Value *V, IRBuilder<> &B);
74 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
75 /// specified pointer. Ptr is required to be some pointer type, and the
76 /// return value has 'intptr_t' type.
77 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
79 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
80 /// specified pointer and character. Ptr is required to be some pointer type,
81 /// and the return value has 'i8*' type.
82 Value *EmitStrChr(Value *Ptr, char C, IRBuilder<> &B);
84 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
85 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
86 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
87 unsigned Align, IRBuilder<> &B);
89 /// EmitMemMove - Emit a call to the memmove function to the builder. This
90 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
91 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
92 unsigned Align, IRBuilder<> &B);
94 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
95 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
96 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
98 /// EmitMemCmp - Emit a call to the memcmp function.
99 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
101 /// EmitMemSet - Emit a call to the memset function
102 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
104 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name'
105 /// (e.g. 'floor'). This function is known to take a single of type matching
106 /// 'Op' and returns one value with the same type. If 'Op' is a long double,
107 /// 'l' is added as the suffix of name, if 'Op' is a float, we add a 'f'
109 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
110 const AttrListPtr &Attrs);
112 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
114 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
116 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
118 void EmitPutS(Value *Str, IRBuilder<> &B);
120 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
121 /// an i32, and File is a pointer to FILE.
122 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
124 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
125 /// pointer and File is a pointer to FILE.
126 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
128 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
129 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
130 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
133 } // End anonymous namespace.
135 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
136 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
137 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
140 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
141 /// specified pointer. This always returns an integer value of size intptr_t.
142 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
143 Module *M = Caller->getParent();
144 AttributeWithIndex AWI[2];
145 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
146 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
147 Attribute::NoUnwind);
149 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
150 TD->getIntPtrType(*Context),
151 Type::getInt8PtrTy(*Context),
153 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
154 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
155 CI->setCallingConv(F->getCallingConv());
160 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
161 /// specified pointer and character. Ptr is required to be some pointer type,
162 /// and the return value has 'i8*' type.
163 Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
164 Module *M = Caller->getParent();
165 AttributeWithIndex AWI =
166 AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
168 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
169 const Type *I32Ty = Type::getInt32Ty(*Context);
170 Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
171 I8Ptr, I8Ptr, I32Ty, NULL);
172 CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
173 ConstantInt::get(I32Ty, C), "strchr");
174 if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
175 CI->setCallingConv(F->getCallingConv());
180 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
181 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
182 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
183 unsigned Align, IRBuilder<> &B) {
184 Module *M = Caller->getParent();
185 const Type *Ty = Len->getType();
186 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
187 Dst = CastToCStr(Dst, B);
188 Src = CastToCStr(Src, B);
189 return B.CreateCall4(MemCpy, Dst, Src, Len,
190 ConstantInt::get(Type::getInt32Ty(*Context), Align));
193 /// EmitMemMove - Emit a call to the memmove function to the builder. This
194 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
195 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
196 unsigned Align, IRBuilder<> &B) {
197 Module *M = Caller->getParent();
198 const Type *Ty = TD->getIntPtrType(*Context);
199 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
200 Dst = CastToCStr(Dst, B);
201 Src = CastToCStr(Src, B);
202 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
203 return B.CreateCall4(MemMove, Dst, Src, Len, A);
206 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
207 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
208 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
209 Value *Len, IRBuilder<> &B) {
210 Module *M = Caller->getParent();
211 AttributeWithIndex AWI;
212 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
214 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
215 Type::getInt8PtrTy(*Context),
216 Type::getInt8PtrTy(*Context),
217 Type::getInt32Ty(*Context),
218 TD->getIntPtrType(*Context),
220 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
222 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
223 CI->setCallingConv(F->getCallingConv());
228 /// EmitMemCmp - Emit a call to the memcmp function.
229 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
230 Value *Len, IRBuilder<> &B) {
231 Module *M = Caller->getParent();
232 AttributeWithIndex AWI[3];
233 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
234 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
235 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
236 Attribute::NoUnwind);
238 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
239 Type::getInt32Ty(*Context),
240 Type::getInt8PtrTy(*Context),
241 Type::getInt8PtrTy(*Context),
242 TD->getIntPtrType(*Context), NULL);
243 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
246 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
247 CI->setCallingConv(F->getCallingConv());
252 /// EmitMemSet - Emit a call to the memset function
253 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
254 Value *Len, IRBuilder<> &B) {
255 Module *M = Caller->getParent();
256 Intrinsic::ID IID = Intrinsic::memset;
258 Tys[0] = Len->getType();
259 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
260 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
261 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
264 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
265 /// 'floor'). This function is known to take a single of type matching 'Op' and
266 /// returns one value with the same type. If 'Op' is a long double, 'l' is
267 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
268 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
270 const AttrListPtr &Attrs) {
272 if (!Op->getType()->isDoubleTy()) {
273 // If we need to add a suffix, copy into NameBuffer.
274 unsigned NameLen = strlen(Name);
275 assert(NameLen < sizeof(NameBuffer)-2);
276 memcpy(NameBuffer, Name, NameLen);
277 if (Op->getType()->isFloatTy())
278 NameBuffer[NameLen] = 'f'; // floorf
280 NameBuffer[NameLen] = 'l'; // floorl
281 NameBuffer[NameLen+1] = 0;
285 Module *M = Caller->getParent();
286 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
287 Op->getType(), NULL);
288 CallInst *CI = B.CreateCall(Callee, Op, Name);
289 CI->setAttributes(Attrs);
290 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
291 CI->setCallingConv(F->getCallingConv());
296 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
298 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
299 Module *M = Caller->getParent();
300 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
301 Type::getInt32Ty(*Context), NULL);
302 CallInst *CI = B.CreateCall(PutChar,
303 B.CreateIntCast(Char,
304 Type::getInt32Ty(*Context),
309 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
310 CI->setCallingConv(F->getCallingConv());
314 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
316 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
317 Module *M = Caller->getParent();
318 AttributeWithIndex AWI[2];
319 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
320 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
322 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
323 Type::getInt32Ty(*Context),
324 Type::getInt8PtrTy(*Context),
326 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
327 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
328 CI->setCallingConv(F->getCallingConv());
332 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
333 /// an integer and File is a pointer to FILE.
334 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
335 Module *M = Caller->getParent();
336 AttributeWithIndex AWI[2];
337 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
338 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
340 if (isa<PointerType>(File->getType()))
341 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
342 Type::getInt32Ty(*Context),
343 Type::getInt32Ty(*Context), File->getType(),
346 F = M->getOrInsertFunction("fputc",
347 Type::getInt32Ty(*Context),
348 Type::getInt32Ty(*Context),
349 File->getType(), NULL);
350 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
352 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
354 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
355 CI->setCallingConv(Fn->getCallingConv());
358 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
359 /// pointer and File is a pointer to FILE.
360 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
361 Module *M = Caller->getParent();
362 AttributeWithIndex AWI[3];
363 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
364 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
365 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
367 if (isa<PointerType>(File->getType()))
368 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
369 Type::getInt32Ty(*Context),
370 Type::getInt8PtrTy(*Context),
371 File->getType(), NULL);
373 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
374 Type::getInt8PtrTy(*Context),
375 File->getType(), NULL);
376 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
378 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
379 CI->setCallingConv(Fn->getCallingConv());
382 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
383 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
384 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
386 Module *M = Caller->getParent();
387 AttributeWithIndex AWI[3];
388 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
389 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
390 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
392 if (isa<PointerType>(File->getType()))
393 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
394 TD->getIntPtrType(*Context),
395 Type::getInt8PtrTy(*Context),
396 TD->getIntPtrType(*Context),
397 TD->getIntPtrType(*Context),
398 File->getType(), NULL);
400 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
401 Type::getInt8PtrTy(*Context),
402 TD->getIntPtrType(*Context),
403 TD->getIntPtrType(*Context),
404 File->getType(), NULL);
405 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
406 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
408 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
409 CI->setCallingConv(Fn->getCallingConv());
412 //===----------------------------------------------------------------------===//
414 //===----------------------------------------------------------------------===//
416 /// GetStringLengthH - If we can compute the length of the string pointed to by
417 /// the specified pointer, return 'len+1'. If we can't, return 0.
418 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
419 // Look through noop bitcast instructions.
420 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
421 return GetStringLengthH(BCI->getOperand(0), PHIs);
423 // If this is a PHI node, there are two cases: either we have already seen it
425 if (PHINode *PN = dyn_cast<PHINode>(V)) {
426 if (!PHIs.insert(PN))
427 return ~0ULL; // already in the set.
429 // If it was new, see if all the input strings are the same length.
430 uint64_t LenSoFar = ~0ULL;
431 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
432 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
433 if (Len == 0) return 0; // Unknown length -> unknown.
435 if (Len == ~0ULL) continue;
437 if (Len != LenSoFar && LenSoFar != ~0ULL)
438 return 0; // Disagree -> unknown.
442 // Success, all agree.
446 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
447 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
448 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
449 if (Len1 == 0) return 0;
450 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
451 if (Len2 == 0) return 0;
452 if (Len1 == ~0ULL) return Len2;
453 if (Len2 == ~0ULL) return Len1;
454 if (Len1 != Len2) return 0;
458 // If the value is not a GEP instruction nor a constant expression with a
459 // GEP instruction, then return unknown.
461 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
463 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
464 if (CE->getOpcode() != Instruction::GetElementPtr)
471 // Make sure the GEP has exactly three arguments.
472 if (GEP->getNumOperands() != 3)
475 // Check to make sure that the first operand of the GEP is an integer and
476 // has value 0 so that we are sure we're indexing into the initializer.
477 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
483 // If the second index isn't a ConstantInt, then this is a variable index
484 // into the array. If this occurs, we can't say anything meaningful about
486 uint64_t StartIdx = 0;
487 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
488 StartIdx = CI->getZExtValue();
492 // The GEP instruction, constant or instruction, must reference a global
493 // variable that is a constant and is initialized. The referenced constant
494 // initializer is the array that we'll use for optimization.
495 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
496 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
497 GV->mayBeOverridden())
499 Constant *GlobalInit = GV->getInitializer();
501 // Handle the ConstantAggregateZero case, which is a degenerate case. The
502 // initializer is constant zero so the length of the string must be zero.
503 if (isa<ConstantAggregateZero>(GlobalInit))
504 return 1; // Len = 0 offset by 1.
506 // Must be a Constant Array
507 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
508 if (!Array || !Array->getType()->getElementType()->isInteger(8))
511 // Get the number of elements in the array
512 uint64_t NumElts = Array->getType()->getNumElements();
514 // Traverse the constant array from StartIdx (derived above) which is
515 // the place the GEP refers to in the array.
516 for (unsigned i = StartIdx; i != NumElts; ++i) {
517 Constant *Elt = Array->getOperand(i);
518 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
519 if (!CI) // This array isn't suitable, non-int initializer.
522 return i-StartIdx+1; // We found end of string, success!
525 return 0; // The array isn't null terminated, conservatively return 'unknown'.
528 /// GetStringLength - If we can compute the length of the string pointed to by
529 /// the specified pointer, return 'len+1'. If we can't, return 0.
530 static uint64_t GetStringLength(Value *V) {
531 if (!isa<PointerType>(V->getType())) return 0;
533 SmallPtrSet<PHINode*, 32> PHIs;
534 uint64_t Len = GetStringLengthH(V, PHIs);
535 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
536 // an empty string as a length.
537 return Len == ~0ULL ? 1 : Len;
540 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
541 /// value is equal or not-equal to zero.
542 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
543 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
545 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
546 if (IC->isEquality())
547 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
548 if (C->isNullValue())
550 // Unknown instruction.
556 //===----------------------------------------------------------------------===//
557 // String and Memory LibCall Optimizations
558 //===----------------------------------------------------------------------===//
560 //===---------------------------------------===//
561 // 'strcat' Optimizations
563 struct StrCatOpt : public LibCallOptimization {
564 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
565 // Verify the "strcat" function prototype.
566 const FunctionType *FT = Callee->getFunctionType();
567 if (FT->getNumParams() != 2 ||
568 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
569 FT->getParamType(0) != FT->getReturnType() ||
570 FT->getParamType(1) != FT->getReturnType())
573 // Extract some information from the instruction
574 Value *Dst = CI->getOperand(1);
575 Value *Src = CI->getOperand(2);
577 // See if we can get the length of the input string.
578 uint64_t Len = GetStringLength(Src);
579 if (Len == 0) return 0;
580 --Len; // Unbias length.
582 // Handle the simple, do-nothing case: strcat(x, "") -> x
586 // These optimizations require TargetData.
589 EmitStrLenMemCpy(Src, Dst, Len, B);
593 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
594 // We need to find the end of the destination string. That's where the
595 // memory is to be moved to. We just generate a call to strlen.
596 Value *DstLen = EmitStrLen(Dst, B);
598 // Now that we have the destination's length, we must index into the
599 // destination's pointer to get the actual memcpy destination (end of
600 // the string .. we're concatenating).
601 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
603 // We have enough information to now generate the memcpy call to do the
604 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
605 EmitMemCpy(CpyDst, Src,
606 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
610 //===---------------------------------------===//
611 // 'strncat' Optimizations
613 struct StrNCatOpt : public StrCatOpt {
614 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
615 // Verify the "strncat" function prototype.
616 const FunctionType *FT = Callee->getFunctionType();
617 if (FT->getNumParams() != 3 ||
618 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
619 FT->getParamType(0) != FT->getReturnType() ||
620 FT->getParamType(1) != FT->getReturnType() ||
621 !isa<IntegerType>(FT->getParamType(2)))
624 // Extract some information from the instruction
625 Value *Dst = CI->getOperand(1);
626 Value *Src = CI->getOperand(2);
629 // We don't do anything if length is not constant
630 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
631 Len = LengthArg->getZExtValue();
635 // See if we can get the length of the input string.
636 uint64_t SrcLen = GetStringLength(Src);
637 if (SrcLen == 0) return 0;
638 --SrcLen; // Unbias length.
640 // Handle the simple, do-nothing cases:
641 // strncat(x, "", c) -> x
642 // strncat(x, c, 0) -> x
643 if (SrcLen == 0 || Len == 0) return Dst;
645 // These optimizations require TargetData.
648 // We don't optimize this case
649 if (Len < SrcLen) return 0;
651 // strncat(x, s, c) -> strcat(x, s)
652 // s is constant so the strcat can be optimized further
653 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
658 //===---------------------------------------===//
659 // 'strchr' Optimizations
661 struct StrChrOpt : public LibCallOptimization {
662 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
663 // Verify the "strchr" function prototype.
664 const FunctionType *FT = Callee->getFunctionType();
665 if (FT->getNumParams() != 2 ||
666 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
667 FT->getParamType(0) != FT->getReturnType())
670 Value *SrcStr = CI->getOperand(1);
672 // If the second operand is non-constant, see if we can compute the length
673 // of the input string and turn this into memchr.
674 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
676 // These optimizations require TargetData.
679 uint64_t Len = GetStringLength(SrcStr);
680 if (Len == 0 || !FT->getParamType(1)->isInteger(32)) // memchr needs i32.
683 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
684 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
687 // Otherwise, the character is a constant, see if the first argument is
688 // a string literal. If so, we can constant fold.
690 if (!GetConstantStringInfo(SrcStr, Str))
693 // strchr can find the nul character.
695 char CharValue = CharC->getSExtValue();
697 // Compute the offset.
700 if (i == Str.size()) // Didn't find the char. strchr returns null.
701 return Constant::getNullValue(CI->getType());
702 // Did we find our match?
703 if (Str[i] == CharValue)
708 // strchr(s+n,c) -> gep(s+n+i,c)
709 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
710 return B.CreateGEP(SrcStr, Idx, "strchr");
714 //===---------------------------------------===//
715 // 'strcmp' Optimizations
717 struct StrCmpOpt : public LibCallOptimization {
718 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
719 // Verify the "strcmp" function prototype.
720 const FunctionType *FT = Callee->getFunctionType();
721 if (FT->getNumParams() != 2 ||
722 !FT->getReturnType()->isInteger(32) ||
723 FT->getParamType(0) != FT->getParamType(1) ||
724 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
727 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
728 if (Str1P == Str2P) // strcmp(x,x) -> 0
729 return ConstantInt::get(CI->getType(), 0);
731 std::string Str1, Str2;
732 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
733 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
735 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
736 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
738 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
739 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
741 // strcmp(x, y) -> cnst (if both x and y are constant strings)
742 if (HasStr1 && HasStr2)
743 return ConstantInt::get(CI->getType(),
744 strcmp(Str1.c_str(),Str2.c_str()));
746 // strcmp(P, "x") -> memcmp(P, "x", 2)
747 uint64_t Len1 = GetStringLength(Str1P);
748 uint64_t Len2 = GetStringLength(Str2P);
750 // These optimizations require TargetData.
753 return EmitMemCmp(Str1P, Str2P,
754 ConstantInt::get(TD->getIntPtrType(*Context),
755 std::min(Len1, Len2)), B);
762 //===---------------------------------------===//
763 // 'strncmp' Optimizations
765 struct StrNCmpOpt : public LibCallOptimization {
766 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
767 // Verify the "strncmp" function prototype.
768 const FunctionType *FT = Callee->getFunctionType();
769 if (FT->getNumParams() != 3 ||
770 !FT->getReturnType()->isInteger(32) ||
771 FT->getParamType(0) != FT->getParamType(1) ||
772 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
773 !isa<IntegerType>(FT->getParamType(2)))
776 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
777 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
778 return ConstantInt::get(CI->getType(), 0);
780 // Get the length argument if it is constant.
782 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
783 Length = LengthArg->getZExtValue();
787 if (Length == 0) // strncmp(x,y,0) -> 0
788 return ConstantInt::get(CI->getType(), 0);
790 std::string Str1, Str2;
791 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
792 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
794 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
795 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
797 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
798 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
800 // strncmp(x, y) -> cnst (if both x and y are constant strings)
801 if (HasStr1 && HasStr2)
802 return ConstantInt::get(CI->getType(),
803 strncmp(Str1.c_str(), Str2.c_str(), Length));
809 //===---------------------------------------===//
810 // 'strcpy' Optimizations
812 struct StrCpyOpt : public LibCallOptimization {
813 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
814 // Verify the "strcpy" function prototype.
815 const FunctionType *FT = Callee->getFunctionType();
816 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
817 FT->getParamType(0) != FT->getParamType(1) ||
818 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
821 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
822 if (Dst == Src) // strcpy(x,x) -> x
825 // These optimizations require TargetData.
828 // See if we can get the length of the input string.
829 uint64_t Len = GetStringLength(Src);
830 if (Len == 0) return 0;
832 // We have enough information to now generate the memcpy call to do the
833 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
835 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
840 //===---------------------------------------===//
841 // 'strncpy' Optimizations
843 struct StrNCpyOpt : public LibCallOptimization {
844 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
845 const FunctionType *FT = Callee->getFunctionType();
846 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
847 FT->getParamType(0) != FT->getParamType(1) ||
848 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
849 !isa<IntegerType>(FT->getParamType(2)))
852 Value *Dst = CI->getOperand(1);
853 Value *Src = CI->getOperand(2);
854 Value *LenOp = CI->getOperand(3);
856 // See if we can get the length of the input string.
857 uint64_t SrcLen = GetStringLength(Src);
858 if (SrcLen == 0) return 0;
862 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
863 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
869 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
870 Len = LengthArg->getZExtValue();
874 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
876 // These optimizations require TargetData.
879 // Let strncpy handle the zero padding
880 if (Len > SrcLen+1) return 0;
882 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
884 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
890 //===---------------------------------------===//
891 // 'strlen' Optimizations
893 struct StrLenOpt : public LibCallOptimization {
894 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
895 const FunctionType *FT = Callee->getFunctionType();
896 if (FT->getNumParams() != 1 ||
897 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
898 !isa<IntegerType>(FT->getReturnType()))
901 Value *Src = CI->getOperand(1);
903 // Constant folding: strlen("xyz") -> 3
904 if (uint64_t Len = GetStringLength(Src))
905 return ConstantInt::get(CI->getType(), Len-1);
907 // strlen(x) != 0 --> *x != 0
908 // strlen(x) == 0 --> *x == 0
909 if (IsOnlyUsedInZeroEqualityComparison(CI))
910 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
915 //===---------------------------------------===//
916 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
918 struct StrToOpt : public LibCallOptimization {
919 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
920 const FunctionType *FT = Callee->getFunctionType();
921 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
922 !isa<PointerType>(FT->getParamType(0)) ||
923 !isa<PointerType>(FT->getParamType(1)))
926 Value *EndPtr = CI->getOperand(2);
927 if (isa<ConstantPointerNull>(EndPtr)) {
928 CI->setOnlyReadsMemory();
929 CI->addAttribute(1, Attribute::NoCapture);
936 //===---------------------------------------===//
937 // 'strstr' Optimizations
939 struct StrStrOpt : public LibCallOptimization {
940 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
941 const FunctionType *FT = Callee->getFunctionType();
942 if (FT->getNumParams() != 2 ||
943 !isa<PointerType>(FT->getParamType(0)) ||
944 !isa<PointerType>(FT->getParamType(1)) ||
945 !isa<PointerType>(FT->getReturnType()))
948 // fold strstr(x, x) -> x.
949 if (CI->getOperand(1) == CI->getOperand(2))
950 return B.CreateBitCast(CI->getOperand(1), CI->getType());
952 // See if either input string is a constant string.
953 std::string SearchStr, ToFindStr;
954 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
955 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
957 // fold strstr(x, "") -> x.
958 if (HasStr2 && ToFindStr.empty())
959 return B.CreateBitCast(CI->getOperand(1), CI->getType());
961 // If both strings are known, constant fold it.
962 if (HasStr1 && HasStr2) {
963 std::string::size_type Offset = SearchStr.find(ToFindStr);
965 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
966 return Constant::getNullValue(CI->getType());
968 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
969 Value *Result = CastToCStr(CI->getOperand(1), B);
970 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
971 return B.CreateBitCast(Result, CI->getType());
974 // fold strstr(x, "y") -> strchr(x, 'y').
975 if (HasStr2 && ToFindStr.size() == 1)
976 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
983 //===---------------------------------------===//
984 // 'memcmp' Optimizations
986 struct MemCmpOpt : public LibCallOptimization {
987 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
988 const FunctionType *FT = Callee->getFunctionType();
989 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
990 !isa<PointerType>(FT->getParamType(1)) ||
991 !FT->getReturnType()->isInteger(32))
994 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
996 if (LHS == RHS) // memcmp(s,s,x) -> 0
997 return Constant::getNullValue(CI->getType());
999 // Make sure we have a constant length.
1000 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1001 if (!LenC) return 0;
1002 uint64_t Len = LenC->getZExtValue();
1004 if (Len == 0) // memcmp(s1,s2,0) -> 0
1005 return Constant::getNullValue(CI->getType());
1007 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1008 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1009 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
1010 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
1013 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1014 std::string LHSStr, RHSStr;
1015 if (GetConstantStringInfo(LHS, LHSStr) &&
1016 GetConstantStringInfo(RHS, RHSStr)) {
1017 // Make sure we're not reading out-of-bounds memory.
1018 if (Len > LHSStr.length() || Len > RHSStr.length())
1020 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1021 return ConstantInt::get(CI->getType(), Ret);
1028 //===---------------------------------------===//
1029 // 'memcpy' Optimizations
1031 struct MemCpyOpt : public LibCallOptimization {
1032 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1033 // These optimizations require TargetData.
1036 const FunctionType *FT = Callee->getFunctionType();
1037 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1038 !isa<PointerType>(FT->getParamType(0)) ||
1039 !isa<PointerType>(FT->getParamType(1)) ||
1040 FT->getParamType(2) != TD->getIntPtrType(*Context))
1043 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1044 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1045 return CI->getOperand(1);
1049 //===---------------------------------------===//
1050 // 'memmove' Optimizations
1052 struct MemMoveOpt : public LibCallOptimization {
1053 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1054 // These optimizations require TargetData.
1057 const FunctionType *FT = Callee->getFunctionType();
1058 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1059 !isa<PointerType>(FT->getParamType(0)) ||
1060 !isa<PointerType>(FT->getParamType(1)) ||
1061 FT->getParamType(2) != TD->getIntPtrType(*Context))
1064 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1065 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1066 return CI->getOperand(1);
1070 //===---------------------------------------===//
1071 // 'memset' Optimizations
1073 struct MemSetOpt : public LibCallOptimization {
1074 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1075 // These optimizations require TargetData.
1078 const FunctionType *FT = Callee->getFunctionType();
1079 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1080 !isa<PointerType>(FT->getParamType(0)) ||
1081 !isa<IntegerType>(FT->getParamType(1)) ||
1082 FT->getParamType(2) != TD->getIntPtrType(*Context))
1085 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1086 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1088 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1089 return CI->getOperand(1);
1093 //===----------------------------------------------------------------------===//
1094 // Object Size Checking Optimizations
1095 //===----------------------------------------------------------------------===//
1097 //===---------------------------------------===//
1098 // 'memcpy_chk' Optimizations
1100 struct MemCpyChkOpt : public LibCallOptimization {
1101 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1102 // These optimizations require TargetData.
1105 const FunctionType *FT = Callee->getFunctionType();
1106 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1107 !isa<PointerType>(FT->getParamType(0)) ||
1108 !isa<PointerType>(FT->getParamType(1)) ||
1109 !isa<IntegerType>(FT->getParamType(3)) ||
1110 FT->getParamType(2) != TD->getIntPtrType(*Context))
1113 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1116 if (SizeCI->isAllOnesValue()) {
1117 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1118 return CI->getOperand(1);
1125 //===---------------------------------------===//
1126 // 'memset_chk' Optimizations
1128 struct MemSetChkOpt : public LibCallOptimization {
1129 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1130 // These optimizations require TargetData.
1133 const FunctionType *FT = Callee->getFunctionType();
1134 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1135 !isa<PointerType>(FT->getParamType(0)) ||
1136 !isa<IntegerType>(FT->getParamType(1)) ||
1137 !isa<IntegerType>(FT->getParamType(3)) ||
1138 FT->getParamType(2) != TD->getIntPtrType(*Context))
1141 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1144 if (SizeCI->isAllOnesValue()) {
1145 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1147 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1148 return CI->getOperand(1);
1155 //===---------------------------------------===//
1156 // 'memmove_chk' Optimizations
1158 struct MemMoveChkOpt : public LibCallOptimization {
1159 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1160 // These optimizations require TargetData.
1163 const FunctionType *FT = Callee->getFunctionType();
1164 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1165 !isa<PointerType>(FT->getParamType(0)) ||
1166 !isa<PointerType>(FT->getParamType(1)) ||
1167 !isa<IntegerType>(FT->getParamType(3)) ||
1168 FT->getParamType(2) != TD->getIntPtrType(*Context))
1171 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1174 if (SizeCI->isAllOnesValue()) {
1175 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1177 return CI->getOperand(1);
1184 //===----------------------------------------------------------------------===//
1185 // Math Library Optimizations
1186 //===----------------------------------------------------------------------===//
1188 //===---------------------------------------===//
1189 // 'pow*' Optimizations
1191 struct PowOpt : public LibCallOptimization {
1192 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1193 const FunctionType *FT = Callee->getFunctionType();
1194 // Just make sure this has 2 arguments of the same FP type, which match the
1196 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1197 FT->getParamType(0) != FT->getParamType(1) ||
1198 !FT->getParamType(0)->isFloatingPoint())
1201 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1202 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1203 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1205 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1206 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1209 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1210 if (Op2C == 0) return 0;
1212 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1213 return ConstantFP::get(CI->getType(), 1.0);
1215 if (Op2C->isExactlyValue(0.5)) {
1216 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1217 // This is faster than calling pow, and still handles negative zero
1218 // and negative infinite correctly.
1219 // TODO: In fast-math mode, this could be just sqrt(x).
1220 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1221 Value *Inf = ConstantFP::getInfinity(CI->getType());
1222 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1223 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1224 Callee->getAttributes());
1225 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1226 Callee->getAttributes());
1227 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1228 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1232 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1234 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1235 return B.CreateFMul(Op1, Op1, "pow2");
1236 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1237 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1243 //===---------------------------------------===//
1244 // 'exp2' Optimizations
1246 struct Exp2Opt : public LibCallOptimization {
1247 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1248 const FunctionType *FT = Callee->getFunctionType();
1249 // Just make sure this has 1 argument of FP type, which matches the
1251 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1252 !FT->getParamType(0)->isFloatingPoint())
1255 Value *Op = CI->getOperand(1);
1256 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1257 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1258 Value *LdExpArg = 0;
1259 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1260 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1261 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1262 Type::getInt32Ty(*Context), "tmp");
1263 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1264 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1265 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1266 Type::getInt32Ty(*Context), "tmp");
1271 if (Op->getType()->isFloatTy())
1273 else if (Op->getType()->isDoubleTy())
1278 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1279 if (!Op->getType()->isFloatTy())
1280 One = ConstantExpr::getFPExtend(One, Op->getType());
1282 Module *M = Caller->getParent();
1283 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1285 Type::getInt32Ty(*Context),NULL);
1286 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1287 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1288 CI->setCallingConv(F->getCallingConv());
1296 //===---------------------------------------===//
1297 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1299 struct UnaryDoubleFPOpt : public LibCallOptimization {
1300 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1301 const FunctionType *FT = Callee->getFunctionType();
1302 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1303 !FT->getParamType(0)->isDoubleTy())
1306 // If this is something like 'floor((double)floatval)', convert to floorf.
1307 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1308 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1311 // floor((double)floatval) -> (double)floorf(floatval)
1312 Value *V = Cast->getOperand(0);
1313 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1314 Callee->getAttributes());
1315 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1319 //===----------------------------------------------------------------------===//
1320 // Integer Optimizations
1321 //===----------------------------------------------------------------------===//
1323 //===---------------------------------------===//
1324 // 'ffs*' Optimizations
1326 struct FFSOpt : public LibCallOptimization {
1327 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1328 const FunctionType *FT = Callee->getFunctionType();
1329 // Just make sure this has 2 arguments of the same FP type, which match the
1331 if (FT->getNumParams() != 1 ||
1332 !FT->getReturnType()->isInteger(32) ||
1333 !isa<IntegerType>(FT->getParamType(0)))
1336 Value *Op = CI->getOperand(1);
1339 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1340 if (CI->getValue() == 0) // ffs(0) -> 0.
1341 return Constant::getNullValue(CI->getType());
1342 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1343 CI->getValue().countTrailingZeros()+1);
1346 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1347 const Type *ArgType = Op->getType();
1348 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1349 Intrinsic::cttz, &ArgType, 1);
1350 Value *V = B.CreateCall(F, Op, "cttz");
1351 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1352 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1354 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1355 return B.CreateSelect(Cond, V,
1356 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1360 //===---------------------------------------===//
1361 // 'isdigit' Optimizations
1363 struct IsDigitOpt : public LibCallOptimization {
1364 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1365 const FunctionType *FT = Callee->getFunctionType();
1366 // We require integer(i32)
1367 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1368 !FT->getParamType(0)->isInteger(32))
1371 // isdigit(c) -> (c-'0') <u 10
1372 Value *Op = CI->getOperand(1);
1373 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1375 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1377 return B.CreateZExt(Op, CI->getType());
1381 //===---------------------------------------===//
1382 // 'isascii' Optimizations
1384 struct IsAsciiOpt : public LibCallOptimization {
1385 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1386 const FunctionType *FT = Callee->getFunctionType();
1387 // We require integer(i32)
1388 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1389 !FT->getParamType(0)->isInteger(32))
1392 // isascii(c) -> c <u 128
1393 Value *Op = CI->getOperand(1);
1394 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1396 return B.CreateZExt(Op, CI->getType());
1400 //===---------------------------------------===//
1401 // 'abs', 'labs', 'llabs' Optimizations
1403 struct AbsOpt : public LibCallOptimization {
1404 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1405 const FunctionType *FT = Callee->getFunctionType();
1406 // We require integer(integer) where the types agree.
1407 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1408 FT->getParamType(0) != FT->getReturnType())
1411 // abs(x) -> x >s -1 ? x : -x
1412 Value *Op = CI->getOperand(1);
1413 Value *Pos = B.CreateICmpSGT(Op,
1414 Constant::getAllOnesValue(Op->getType()),
1416 Value *Neg = B.CreateNeg(Op, "neg");
1417 return B.CreateSelect(Pos, Op, Neg);
1422 //===---------------------------------------===//
1423 // 'toascii' Optimizations
1425 struct ToAsciiOpt : public LibCallOptimization {
1426 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1427 const FunctionType *FT = Callee->getFunctionType();
1428 // We require i32(i32)
1429 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1430 !FT->getParamType(0)->isInteger(32))
1433 // isascii(c) -> c & 0x7f
1434 return B.CreateAnd(CI->getOperand(1),
1435 ConstantInt::get(CI->getType(),0x7F));
1439 //===----------------------------------------------------------------------===//
1440 // Formatting and IO Optimizations
1441 //===----------------------------------------------------------------------===//
1443 //===---------------------------------------===//
1444 // 'printf' Optimizations
1446 struct PrintFOpt : public LibCallOptimization {
1447 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1448 // Require one fixed pointer argument and an integer/void result.
1449 const FunctionType *FT = Callee->getFunctionType();
1450 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1451 !(isa<IntegerType>(FT->getReturnType()) ||
1452 FT->getReturnType()->isVoidTy()))
1455 // Check for a fixed format string.
1456 std::string FormatStr;
1457 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1460 // Empty format string -> noop.
1461 if (FormatStr.empty()) // Tolerate printf's declared void.
1462 return CI->use_empty() ? (Value*)CI :
1463 ConstantInt::get(CI->getType(), 0);
1465 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1466 // in case there is an error writing to stdout.
1467 if (FormatStr.size() == 1) {
1468 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1470 if (CI->use_empty()) return CI;
1471 return B.CreateIntCast(Res, CI->getType(), true);
1474 // printf("foo\n") --> puts("foo")
1475 if (FormatStr[FormatStr.size()-1] == '\n' &&
1476 FormatStr.find('%') == std::string::npos) { // no format characters.
1477 // Create a string literal with no \n on it. We expect the constant merge
1478 // pass to be run after this pass, to merge duplicate strings.
1479 FormatStr.erase(FormatStr.end()-1);
1480 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1481 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1482 GlobalVariable::InternalLinkage, C, "str");
1484 return CI->use_empty() ? (Value*)CI :
1485 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1488 // Optimize specific format strings.
1489 // printf("%c", chr) --> putchar(*(i8*)dst)
1490 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1491 isa<IntegerType>(CI->getOperand(2)->getType())) {
1492 Value *Res = EmitPutChar(CI->getOperand(2), B);
1494 if (CI->use_empty()) return CI;
1495 return B.CreateIntCast(Res, CI->getType(), true);
1498 // printf("%s\n", str) --> puts(str)
1499 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1500 isa<PointerType>(CI->getOperand(2)->getType()) &&
1502 EmitPutS(CI->getOperand(2), B);
1509 //===---------------------------------------===//
1510 // 'sprintf' Optimizations
1512 struct SPrintFOpt : public LibCallOptimization {
1513 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1514 // Require two fixed pointer arguments and an integer result.
1515 const FunctionType *FT = Callee->getFunctionType();
1516 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1517 !isa<PointerType>(FT->getParamType(1)) ||
1518 !isa<IntegerType>(FT->getReturnType()))
1521 // Check for a fixed format string.
1522 std::string FormatStr;
1523 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1526 // If we just have a format string (nothing else crazy) transform it.
1527 if (CI->getNumOperands() == 3) {
1528 // Make sure there's no % in the constant array. We could try to handle
1529 // %% -> % in the future if we cared.
1530 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1531 if (FormatStr[i] == '%')
1532 return 0; // we found a format specifier, bail out.
1534 // These optimizations require TargetData.
1537 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1538 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1540 (TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1541 return ConstantInt::get(CI->getType(), FormatStr.size());
1544 // The remaining optimizations require the format string to be "%s" or "%c"
1545 // and have an extra operand.
1546 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1549 // Decode the second character of the format string.
1550 if (FormatStr[1] == 'c') {
1551 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1552 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1553 Value *V = B.CreateTrunc(CI->getOperand(3),
1554 Type::getInt8Ty(*Context), "char");
1555 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1556 B.CreateStore(V, Ptr);
1557 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1559 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1561 return ConstantInt::get(CI->getType(), 1);
1564 if (FormatStr[1] == 's') {
1565 // These optimizations require TargetData.
1568 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1569 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1571 Value *Len = EmitStrLen(CI->getOperand(3), B);
1572 Value *IncLen = B.CreateAdd(Len,
1573 ConstantInt::get(Len->getType(), 1),
1575 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1577 // The sprintf result is the unincremented number of bytes in the string.
1578 return B.CreateIntCast(Len, CI->getType(), false);
1584 //===---------------------------------------===//
1585 // 'fwrite' Optimizations
1587 struct FWriteOpt : public LibCallOptimization {
1588 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1589 // Require a pointer, an integer, an integer, a pointer, returning integer.
1590 const FunctionType *FT = Callee->getFunctionType();
1591 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1592 !isa<IntegerType>(FT->getParamType(1)) ||
1593 !isa<IntegerType>(FT->getParamType(2)) ||
1594 !isa<PointerType>(FT->getParamType(3)) ||
1595 !isa<IntegerType>(FT->getReturnType()))
1598 // Get the element size and count.
1599 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1600 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1601 if (!SizeC || !CountC) return 0;
1602 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1604 // If this is writing zero records, remove the call (it's a noop).
1606 return ConstantInt::get(CI->getType(), 0);
1608 // If this is writing one byte, turn it into fputc.
1609 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1610 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1611 EmitFPutC(Char, CI->getOperand(4), B);
1612 return ConstantInt::get(CI->getType(), 1);
1619 //===---------------------------------------===//
1620 // 'fputs' Optimizations
1622 struct FPutsOpt : public LibCallOptimization {
1623 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1624 // These optimizations require TargetData.
1627 // Require two pointers. Also, we can't optimize if return value is used.
1628 const FunctionType *FT = Callee->getFunctionType();
1629 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1630 !isa<PointerType>(FT->getParamType(1)) ||
1634 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1635 uint64_t Len = GetStringLength(CI->getOperand(1));
1637 EmitFWrite(CI->getOperand(1),
1638 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1639 CI->getOperand(2), B);
1640 return CI; // Known to have no uses (see above).
1644 //===---------------------------------------===//
1645 // 'fprintf' Optimizations
1647 struct FPrintFOpt : public LibCallOptimization {
1648 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1649 // Require two fixed paramters as pointers and integer result.
1650 const FunctionType *FT = Callee->getFunctionType();
1651 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1652 !isa<PointerType>(FT->getParamType(1)) ||
1653 !isa<IntegerType>(FT->getReturnType()))
1656 // All the optimizations depend on the format string.
1657 std::string FormatStr;
1658 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1661 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1662 if (CI->getNumOperands() == 3) {
1663 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1664 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1665 return 0; // We found a format specifier.
1667 // These optimizations require TargetData.
1670 EmitFWrite(CI->getOperand(2),
1671 ConstantInt::get(TD->getIntPtrType(*Context),
1673 CI->getOperand(1), B);
1674 return ConstantInt::get(CI->getType(), FormatStr.size());
1677 // The remaining optimizations require the format string to be "%s" or "%c"
1678 // and have an extra operand.
1679 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1682 // Decode the second character of the format string.
1683 if (FormatStr[1] == 'c') {
1684 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1685 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1686 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1687 return ConstantInt::get(CI->getType(), 1);
1690 if (FormatStr[1] == 's') {
1691 // fprintf(F, "%s", str) -> fputs(str, F)
1692 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1694 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1701 } // end anonymous namespace.
1703 //===----------------------------------------------------------------------===//
1704 // SimplifyLibCalls Pass Implementation
1705 //===----------------------------------------------------------------------===//
1708 /// This pass optimizes well known library functions from libc and libm.
1710 class SimplifyLibCalls : public FunctionPass {
1711 StringMap<LibCallOptimization*> Optimizations;
1712 // String and Memory LibCall Optimizations
1713 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1714 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1715 StrToOpt StrTo; StrStrOpt StrStr;
1716 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1717 // Math Library Optimizations
1718 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1719 // Integer Optimizations
1720 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1722 // Formatting and IO Optimizations
1723 SPrintFOpt SPrintF; PrintFOpt PrintF;
1724 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1726 // Object Size Checking
1727 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1729 bool Modified; // This is only used by doInitialization.
1731 static char ID; // Pass identification
1732 SimplifyLibCalls() : FunctionPass(&ID) {}
1734 void InitOptimizations();
1735 bool runOnFunction(Function &F);
1737 void setDoesNotAccessMemory(Function &F);
1738 void setOnlyReadsMemory(Function &F);
1739 void setDoesNotThrow(Function &F);
1740 void setDoesNotCapture(Function &F, unsigned n);
1741 void setDoesNotAlias(Function &F, unsigned n);
1742 bool doInitialization(Module &M);
1744 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1747 char SimplifyLibCalls::ID = 0;
1748 } // end anonymous namespace.
1750 static RegisterPass<SimplifyLibCalls>
1751 X("simplify-libcalls", "Simplify well-known library calls");
1753 // Public interface to the Simplify LibCalls pass.
1754 FunctionPass *llvm::createSimplifyLibCallsPass() {
1755 return new SimplifyLibCalls();
1758 /// Optimizations - Populate the Optimizations map with all the optimizations
1760 void SimplifyLibCalls::InitOptimizations() {
1761 // String and Memory LibCall Optimizations
1762 Optimizations["strcat"] = &StrCat;
1763 Optimizations["strncat"] = &StrNCat;
1764 Optimizations["strchr"] = &StrChr;
1765 Optimizations["strcmp"] = &StrCmp;
1766 Optimizations["strncmp"] = &StrNCmp;
1767 Optimizations["strcpy"] = &StrCpy;
1768 Optimizations["strncpy"] = &StrNCpy;
1769 Optimizations["strlen"] = &StrLen;
1770 Optimizations["strtol"] = &StrTo;
1771 Optimizations["strtod"] = &StrTo;
1772 Optimizations["strtof"] = &StrTo;
1773 Optimizations["strtoul"] = &StrTo;
1774 Optimizations["strtoll"] = &StrTo;
1775 Optimizations["strtold"] = &StrTo;
1776 Optimizations["strtoull"] = &StrTo;
1777 Optimizations["strstr"] = &StrStr;
1778 Optimizations["memcmp"] = &MemCmp;
1779 Optimizations["memcpy"] = &MemCpy;
1780 Optimizations["memmove"] = &MemMove;
1781 Optimizations["memset"] = &MemSet;
1783 // Math Library Optimizations
1784 Optimizations["powf"] = &Pow;
1785 Optimizations["pow"] = &Pow;
1786 Optimizations["powl"] = &Pow;
1787 Optimizations["llvm.pow.f32"] = &Pow;
1788 Optimizations["llvm.pow.f64"] = &Pow;
1789 Optimizations["llvm.pow.f80"] = &Pow;
1790 Optimizations["llvm.pow.f128"] = &Pow;
1791 Optimizations["llvm.pow.ppcf128"] = &Pow;
1792 Optimizations["exp2l"] = &Exp2;
1793 Optimizations["exp2"] = &Exp2;
1794 Optimizations["exp2f"] = &Exp2;
1795 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1796 Optimizations["llvm.exp2.f128"] = &Exp2;
1797 Optimizations["llvm.exp2.f80"] = &Exp2;
1798 Optimizations["llvm.exp2.f64"] = &Exp2;
1799 Optimizations["llvm.exp2.f32"] = &Exp2;
1802 Optimizations["floor"] = &UnaryDoubleFP;
1805 Optimizations["ceil"] = &UnaryDoubleFP;
1808 Optimizations["round"] = &UnaryDoubleFP;
1811 Optimizations["rint"] = &UnaryDoubleFP;
1813 #ifdef HAVE_NEARBYINTF
1814 Optimizations["nearbyint"] = &UnaryDoubleFP;
1817 // Integer Optimizations
1818 Optimizations["ffs"] = &FFS;
1819 Optimizations["ffsl"] = &FFS;
1820 Optimizations["ffsll"] = &FFS;
1821 Optimizations["abs"] = &Abs;
1822 Optimizations["labs"] = &Abs;
1823 Optimizations["llabs"] = &Abs;
1824 Optimizations["isdigit"] = &IsDigit;
1825 Optimizations["isascii"] = &IsAscii;
1826 Optimizations["toascii"] = &ToAscii;
1828 // Formatting and IO Optimizations
1829 Optimizations["sprintf"] = &SPrintF;
1830 Optimizations["printf"] = &PrintF;
1831 Optimizations["fwrite"] = &FWrite;
1832 Optimizations["fputs"] = &FPuts;
1833 Optimizations["fprintf"] = &FPrintF;
1835 // Object Size Checking
1836 Optimizations["__memcpy_chk"] = &MemCpyChk;
1837 Optimizations["__memset_chk"] = &MemSetChk;
1838 Optimizations["__memmove_chk"] = &MemMoveChk;
1842 /// runOnFunction - Top level algorithm.
1844 bool SimplifyLibCalls::runOnFunction(Function &F) {
1845 if (Optimizations.empty())
1846 InitOptimizations();
1848 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1850 IRBuilder<> Builder(F.getContext());
1852 bool Changed = false;
1853 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1854 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1855 // Ignore non-calls.
1856 CallInst *CI = dyn_cast<CallInst>(I++);
1859 // Ignore indirect calls and calls to non-external functions.
1860 Function *Callee = CI->getCalledFunction();
1861 if (Callee == 0 || !Callee->isDeclaration() ||
1862 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1865 // Ignore unknown calls.
1866 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1869 // Set the builder to the instruction after the call.
1870 Builder.SetInsertPoint(BB, I);
1872 // Try to optimize this call.
1873 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1874 if (Result == 0) continue;
1876 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1877 dbgs() << " into: " << *Result << "\n");
1879 // Something changed!
1883 // Inspect the instruction after the call (which was potentially just
1887 if (CI != Result && !CI->use_empty()) {
1888 CI->replaceAllUsesWith(Result);
1889 if (!Result->hasName())
1890 Result->takeName(CI);
1892 CI->eraseFromParent();
1898 // Utility methods for doInitialization.
1900 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1901 if (!F.doesNotAccessMemory()) {
1902 F.setDoesNotAccessMemory();
1907 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1908 if (!F.onlyReadsMemory()) {
1909 F.setOnlyReadsMemory();
1914 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1915 if (!F.doesNotThrow()) {
1916 F.setDoesNotThrow();
1921 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1922 if (!F.doesNotCapture(n)) {
1923 F.setDoesNotCapture(n);
1928 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1929 if (!F.doesNotAlias(n)) {
1930 F.setDoesNotAlias(n);
1936 /// doInitialization - Add attributes to well-known functions.
1938 bool SimplifyLibCalls::doInitialization(Module &M) {
1940 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1942 if (!F.isDeclaration())
1948 const FunctionType *FTy = F.getFunctionType();
1950 StringRef Name = F.getName();
1953 if (Name == "strlen") {
1954 if (FTy->getNumParams() != 1 ||
1955 !isa<PointerType>(FTy->getParamType(0)))
1957 setOnlyReadsMemory(F);
1959 setDoesNotCapture(F, 1);
1960 } else if (Name == "strcpy" ||
1966 Name == "strtoul" ||
1967 Name == "strtoll" ||
1968 Name == "strtold" ||
1969 Name == "strncat" ||
1970 Name == "strncpy" ||
1971 Name == "strtoull") {
1972 if (FTy->getNumParams() < 2 ||
1973 !isa<PointerType>(FTy->getParamType(1)))
1976 setDoesNotCapture(F, 2);
1977 } else if (Name == "strxfrm") {
1978 if (FTy->getNumParams() != 3 ||
1979 !isa<PointerType>(FTy->getParamType(0)) ||
1980 !isa<PointerType>(FTy->getParamType(1)))
1983 setDoesNotCapture(F, 1);
1984 setDoesNotCapture(F, 2);
1985 } else if (Name == "strcmp" ||
1987 Name == "strncmp" ||
1988 Name ==" strcspn" ||
1989 Name == "strcoll" ||
1990 Name == "strcasecmp" ||
1991 Name == "strncasecmp") {
1992 if (FTy->getNumParams() < 2 ||
1993 !isa<PointerType>(FTy->getParamType(0)) ||
1994 !isa<PointerType>(FTy->getParamType(1)))
1996 setOnlyReadsMemory(F);
1998 setDoesNotCapture(F, 1);
1999 setDoesNotCapture(F, 2);
2000 } else if (Name == "strstr" ||
2001 Name == "strpbrk") {
2002 if (FTy->getNumParams() != 2 ||
2003 !isa<PointerType>(FTy->getParamType(1)))
2005 setOnlyReadsMemory(F);
2007 setDoesNotCapture(F, 2);
2008 } else if (Name == "strtok" ||
2009 Name == "strtok_r") {
2010 if (FTy->getNumParams() < 2 ||
2011 !isa<PointerType>(FTy->getParamType(1)))
2014 setDoesNotCapture(F, 2);
2015 } else if (Name == "scanf" ||
2017 Name == "setvbuf") {
2018 if (FTy->getNumParams() < 1 ||
2019 !isa<PointerType>(FTy->getParamType(0)))
2022 setDoesNotCapture(F, 1);
2023 } else if (Name == "strdup" ||
2024 Name == "strndup") {
2025 if (FTy->getNumParams() < 1 ||
2026 !isa<PointerType>(FTy->getReturnType()) ||
2027 !isa<PointerType>(FTy->getParamType(0)))
2030 setDoesNotAlias(F, 0);
2031 setDoesNotCapture(F, 1);
2032 } else if (Name == "stat" ||
2034 Name == "sprintf" ||
2035 Name == "statvfs") {
2036 if (FTy->getNumParams() < 2 ||
2037 !isa<PointerType>(FTy->getParamType(0)) ||
2038 !isa<PointerType>(FTy->getParamType(1)))
2041 setDoesNotCapture(F, 1);
2042 setDoesNotCapture(F, 2);
2043 } else if (Name == "snprintf") {
2044 if (FTy->getNumParams() != 3 ||
2045 !isa<PointerType>(FTy->getParamType(0)) ||
2046 !isa<PointerType>(FTy->getParamType(2)))
2049 setDoesNotCapture(F, 1);
2050 setDoesNotCapture(F, 3);
2051 } else if (Name == "setitimer") {
2052 if (FTy->getNumParams() != 3 ||
2053 !isa<PointerType>(FTy->getParamType(1)) ||
2054 !isa<PointerType>(FTy->getParamType(2)))
2057 setDoesNotCapture(F, 2);
2058 setDoesNotCapture(F, 3);
2059 } else if (Name == "system") {
2060 if (FTy->getNumParams() != 1 ||
2061 !isa<PointerType>(FTy->getParamType(0)))
2063 // May throw; "system" is a valid pthread cancellation point.
2064 setDoesNotCapture(F, 1);
2068 if (Name == "malloc") {
2069 if (FTy->getNumParams() != 1 ||
2070 !isa<PointerType>(FTy->getReturnType()))
2073 setDoesNotAlias(F, 0);
2074 } else if (Name == "memcmp") {
2075 if (FTy->getNumParams() != 3 ||
2076 !isa<PointerType>(FTy->getParamType(0)) ||
2077 !isa<PointerType>(FTy->getParamType(1)))
2079 setOnlyReadsMemory(F);
2081 setDoesNotCapture(F, 1);
2082 setDoesNotCapture(F, 2);
2083 } else if (Name == "memchr" ||
2084 Name == "memrchr") {
2085 if (FTy->getNumParams() != 3)
2087 setOnlyReadsMemory(F);
2089 } else if (Name == "modf" ||
2093 Name == "memccpy" ||
2094 Name == "memmove") {
2095 if (FTy->getNumParams() < 2 ||
2096 !isa<PointerType>(FTy->getParamType(1)))
2099 setDoesNotCapture(F, 2);
2100 } else if (Name == "memalign") {
2101 if (!isa<PointerType>(FTy->getReturnType()))
2103 setDoesNotAlias(F, 0);
2104 } else if (Name == "mkdir" ||
2106 if (FTy->getNumParams() == 0 ||
2107 !isa<PointerType>(FTy->getParamType(0)))
2110 setDoesNotCapture(F, 1);
2114 if (Name == "realloc") {
2115 if (FTy->getNumParams() != 2 ||
2116 !isa<PointerType>(FTy->getParamType(0)) ||
2117 !isa<PointerType>(FTy->getReturnType()))
2120 setDoesNotAlias(F, 0);
2121 setDoesNotCapture(F, 1);
2122 } else if (Name == "read") {
2123 if (FTy->getNumParams() != 3 ||
2124 !isa<PointerType>(FTy->getParamType(1)))
2126 // May throw; "read" is a valid pthread cancellation point.
2127 setDoesNotCapture(F, 2);
2128 } else if (Name == "rmdir" ||
2131 Name == "realpath") {
2132 if (FTy->getNumParams() < 1 ||
2133 !isa<PointerType>(FTy->getParamType(0)))
2136 setDoesNotCapture(F, 1);
2137 } else if (Name == "rename" ||
2138 Name == "readlink") {
2139 if (FTy->getNumParams() < 2 ||
2140 !isa<PointerType>(FTy->getParamType(0)) ||
2141 !isa<PointerType>(FTy->getParamType(1)))
2144 setDoesNotCapture(F, 1);
2145 setDoesNotCapture(F, 2);
2149 if (Name == "write") {
2150 if (FTy->getNumParams() != 3 ||
2151 !isa<PointerType>(FTy->getParamType(1)))
2153 // May throw; "write" is a valid pthread cancellation point.
2154 setDoesNotCapture(F, 2);
2158 if (Name == "bcopy") {
2159 if (FTy->getNumParams() != 3 ||
2160 !isa<PointerType>(FTy->getParamType(0)) ||
2161 !isa<PointerType>(FTy->getParamType(1)))
2164 setDoesNotCapture(F, 1);
2165 setDoesNotCapture(F, 2);
2166 } else if (Name == "bcmp") {
2167 if (FTy->getNumParams() != 3 ||
2168 !isa<PointerType>(FTy->getParamType(0)) ||
2169 !isa<PointerType>(FTy->getParamType(1)))
2172 setOnlyReadsMemory(F);
2173 setDoesNotCapture(F, 1);
2174 setDoesNotCapture(F, 2);
2175 } else if (Name == "bzero") {
2176 if (FTy->getNumParams() != 2 ||
2177 !isa<PointerType>(FTy->getParamType(0)))
2180 setDoesNotCapture(F, 1);
2184 if (Name == "calloc") {
2185 if (FTy->getNumParams() != 2 ||
2186 !isa<PointerType>(FTy->getReturnType()))
2189 setDoesNotAlias(F, 0);
2190 } else if (Name == "chmod" ||
2192 Name == "ctermid" ||
2193 Name == "clearerr" ||
2194 Name == "closedir") {
2195 if (FTy->getNumParams() == 0 ||
2196 !isa<PointerType>(FTy->getParamType(0)))
2199 setDoesNotCapture(F, 1);
2203 if (Name == "atoi" ||
2207 if (FTy->getNumParams() != 1 ||
2208 !isa<PointerType>(FTy->getParamType(0)))
2211 setOnlyReadsMemory(F);
2212 setDoesNotCapture(F, 1);
2213 } else if (Name == "access") {
2214 if (FTy->getNumParams() != 2 ||
2215 !isa<PointerType>(FTy->getParamType(0)))
2218 setDoesNotCapture(F, 1);
2222 if (Name == "fopen") {
2223 if (FTy->getNumParams() != 2 ||
2224 !isa<PointerType>(FTy->getReturnType()) ||
2225 !isa<PointerType>(FTy->getParamType(0)) ||
2226 !isa<PointerType>(FTy->getParamType(1)))
2229 setDoesNotAlias(F, 0);
2230 setDoesNotCapture(F, 1);
2231 setDoesNotCapture(F, 2);
2232 } else if (Name == "fdopen") {
2233 if (FTy->getNumParams() != 2 ||
2234 !isa<PointerType>(FTy->getReturnType()) ||
2235 !isa<PointerType>(FTy->getParamType(1)))
2238 setDoesNotAlias(F, 0);
2239 setDoesNotCapture(F, 2);
2240 } else if (Name == "feof" ||
2250 Name == "fsetpos" ||
2251 Name == "flockfile" ||
2252 Name == "funlockfile" ||
2253 Name == "ftrylockfile") {
2254 if (FTy->getNumParams() == 0 ||
2255 !isa<PointerType>(FTy->getParamType(0)))
2258 setDoesNotCapture(F, 1);
2259 } else if (Name == "ferror") {
2260 if (FTy->getNumParams() != 1 ||
2261 !isa<PointerType>(FTy->getParamType(0)))
2264 setDoesNotCapture(F, 1);
2265 setOnlyReadsMemory(F);
2266 } else if (Name == "fputc" ||
2271 Name == "fstatvfs") {
2272 if (FTy->getNumParams() != 2 ||
2273 !isa<PointerType>(FTy->getParamType(1)))
2276 setDoesNotCapture(F, 2);
2277 } else if (Name == "fgets") {
2278 if (FTy->getNumParams() != 3 ||
2279 !isa<PointerType>(FTy->getParamType(0)) ||
2280 !isa<PointerType>(FTy->getParamType(2)))
2283 setDoesNotCapture(F, 3);
2284 } else if (Name == "fread" ||
2286 if (FTy->getNumParams() != 4 ||
2287 !isa<PointerType>(FTy->getParamType(0)) ||
2288 !isa<PointerType>(FTy->getParamType(3)))
2291 setDoesNotCapture(F, 1);
2292 setDoesNotCapture(F, 4);
2293 } else if (Name == "fputs" ||
2295 Name == "fprintf" ||
2296 Name == "fgetpos") {
2297 if (FTy->getNumParams() < 2 ||
2298 !isa<PointerType>(FTy->getParamType(0)) ||
2299 !isa<PointerType>(FTy->getParamType(1)))
2302 setDoesNotCapture(F, 1);
2303 setDoesNotCapture(F, 2);
2307 if (Name == "getc" ||
2308 Name == "getlogin_r" ||
2309 Name == "getc_unlocked") {
2310 if (FTy->getNumParams() == 0 ||
2311 !isa<PointerType>(FTy->getParamType(0)))
2314 setDoesNotCapture(F, 1);
2315 } else if (Name == "getenv") {
2316 if (FTy->getNumParams() != 1 ||
2317 !isa<PointerType>(FTy->getParamType(0)))
2320 setOnlyReadsMemory(F);
2321 setDoesNotCapture(F, 1);
2322 } else if (Name == "gets" ||
2323 Name == "getchar") {
2325 } else if (Name == "getitimer") {
2326 if (FTy->getNumParams() != 2 ||
2327 !isa<PointerType>(FTy->getParamType(1)))
2330 setDoesNotCapture(F, 2);
2331 } else if (Name == "getpwnam") {
2332 if (FTy->getNumParams() != 1 ||
2333 !isa<PointerType>(FTy->getParamType(0)))
2336 setDoesNotCapture(F, 1);
2340 if (Name == "ungetc") {
2341 if (FTy->getNumParams() != 2 ||
2342 !isa<PointerType>(FTy->getParamType(1)))
2345 setDoesNotCapture(F, 2);
2346 } else if (Name == "uname" ||
2348 Name == "unsetenv") {
2349 if (FTy->getNumParams() != 1 ||
2350 !isa<PointerType>(FTy->getParamType(0)))
2353 setDoesNotCapture(F, 1);
2354 } else if (Name == "utime" ||
2356 if (FTy->getNumParams() != 2 ||
2357 !isa<PointerType>(FTy->getParamType(0)) ||
2358 !isa<PointerType>(FTy->getParamType(1)))
2361 setDoesNotCapture(F, 1);
2362 setDoesNotCapture(F, 2);
2366 if (Name == "putc") {
2367 if (FTy->getNumParams() != 2 ||
2368 !isa<PointerType>(FTy->getParamType(1)))
2371 setDoesNotCapture(F, 2);
2372 } else if (Name == "puts" ||
2375 if (FTy->getNumParams() != 1 ||
2376 !isa<PointerType>(FTy->getParamType(0)))
2379 setDoesNotCapture(F, 1);
2380 } else if (Name == "pread" ||
2382 if (FTy->getNumParams() != 4 ||
2383 !isa<PointerType>(FTy->getParamType(1)))
2385 // May throw; these are valid pthread cancellation points.
2386 setDoesNotCapture(F, 2);
2387 } else if (Name == "putchar") {
2389 } else if (Name == "popen") {
2390 if (FTy->getNumParams() != 2 ||
2391 !isa<PointerType>(FTy->getReturnType()) ||
2392 !isa<PointerType>(FTy->getParamType(0)) ||
2393 !isa<PointerType>(FTy->getParamType(1)))
2396 setDoesNotAlias(F, 0);
2397 setDoesNotCapture(F, 1);
2398 setDoesNotCapture(F, 2);
2399 } else if (Name == "pclose") {
2400 if (FTy->getNumParams() != 1 ||
2401 !isa<PointerType>(FTy->getParamType(0)))
2404 setDoesNotCapture(F, 1);
2408 if (Name == "vscanf") {
2409 if (FTy->getNumParams() != 2 ||
2410 !isa<PointerType>(FTy->getParamType(1)))
2413 setDoesNotCapture(F, 1);
2414 } else if (Name == "vsscanf" ||
2415 Name == "vfscanf") {
2416 if (FTy->getNumParams() != 3 ||
2417 !isa<PointerType>(FTy->getParamType(1)) ||
2418 !isa<PointerType>(FTy->getParamType(2)))
2421 setDoesNotCapture(F, 1);
2422 setDoesNotCapture(F, 2);
2423 } else if (Name == "valloc") {
2424 if (!isa<PointerType>(FTy->getReturnType()))
2427 setDoesNotAlias(F, 0);
2428 } else if (Name == "vprintf") {
2429 if (FTy->getNumParams() != 2 ||
2430 !isa<PointerType>(FTy->getParamType(0)))
2433 setDoesNotCapture(F, 1);
2434 } else if (Name == "vfprintf" ||
2435 Name == "vsprintf") {
2436 if (FTy->getNumParams() != 3 ||
2437 !isa<PointerType>(FTy->getParamType(0)) ||
2438 !isa<PointerType>(FTy->getParamType(1)))
2441 setDoesNotCapture(F, 1);
2442 setDoesNotCapture(F, 2);
2443 } else if (Name == "vsnprintf") {
2444 if (FTy->getNumParams() != 4 ||
2445 !isa<PointerType>(FTy->getParamType(0)) ||
2446 !isa<PointerType>(FTy->getParamType(2)))
2449 setDoesNotCapture(F, 1);
2450 setDoesNotCapture(F, 3);
2454 if (Name == "open") {
2455 if (FTy->getNumParams() < 2 ||
2456 !isa<PointerType>(FTy->getParamType(0)))
2458 // May throw; "open" is a valid pthread cancellation point.
2459 setDoesNotCapture(F, 1);
2460 } else if (Name == "opendir") {
2461 if (FTy->getNumParams() != 1 ||
2462 !isa<PointerType>(FTy->getReturnType()) ||
2463 !isa<PointerType>(FTy->getParamType(0)))
2466 setDoesNotAlias(F, 0);
2467 setDoesNotCapture(F, 1);
2471 if (Name == "tmpfile") {
2472 if (!isa<PointerType>(FTy->getReturnType()))
2475 setDoesNotAlias(F, 0);
2476 } else if (Name == "times") {
2477 if (FTy->getNumParams() != 1 ||
2478 !isa<PointerType>(FTy->getParamType(0)))
2481 setDoesNotCapture(F, 1);
2485 if (Name == "htonl" ||
2488 setDoesNotAccessMemory(F);
2492 if (Name == "ntohl" ||
2495 setDoesNotAccessMemory(F);
2499 if (Name == "lstat") {
2500 if (FTy->getNumParams() != 2 ||
2501 !isa<PointerType>(FTy->getParamType(0)) ||
2502 !isa<PointerType>(FTy->getParamType(1)))
2505 setDoesNotCapture(F, 1);
2506 setDoesNotCapture(F, 2);
2507 } else if (Name == "lchown") {
2508 if (FTy->getNumParams() != 3 ||
2509 !isa<PointerType>(FTy->getParamType(0)))
2512 setDoesNotCapture(F, 1);
2516 if (Name == "qsort") {
2517 if (FTy->getNumParams() != 4 ||
2518 !isa<PointerType>(FTy->getParamType(3)))
2520 // May throw; places call through function pointer.
2521 setDoesNotCapture(F, 4);
2525 if (Name == "__strdup" ||
2526 Name == "__strndup") {
2527 if (FTy->getNumParams() < 1 ||
2528 !isa<PointerType>(FTy->getReturnType()) ||
2529 !isa<PointerType>(FTy->getParamType(0)))
2532 setDoesNotAlias(F, 0);
2533 setDoesNotCapture(F, 1);
2534 } else if (Name == "__strtok_r") {
2535 if (FTy->getNumParams() != 3 ||
2536 !isa<PointerType>(FTy->getParamType(1)))
2539 setDoesNotCapture(F, 2);
2540 } else if (Name == "_IO_getc") {
2541 if (FTy->getNumParams() != 1 ||
2542 !isa<PointerType>(FTy->getParamType(0)))
2545 setDoesNotCapture(F, 1);
2546 } else if (Name == "_IO_putc") {
2547 if (FTy->getNumParams() != 2 ||
2548 !isa<PointerType>(FTy->getParamType(1)))
2551 setDoesNotCapture(F, 2);
2555 if (Name == "\1__isoc99_scanf") {
2556 if (FTy->getNumParams() < 1 ||
2557 !isa<PointerType>(FTy->getParamType(0)))
2560 setDoesNotCapture(F, 1);
2561 } else if (Name == "\1stat64" ||
2562 Name == "\1lstat64" ||
2563 Name == "\1statvfs64" ||
2564 Name == "\1__isoc99_sscanf") {
2565 if (FTy->getNumParams() < 1 ||
2566 !isa<PointerType>(FTy->getParamType(0)) ||
2567 !isa<PointerType>(FTy->getParamType(1)))
2570 setDoesNotCapture(F, 1);
2571 setDoesNotCapture(F, 2);
2572 } else if (Name == "\1fopen64") {
2573 if (FTy->getNumParams() != 2 ||
2574 !isa<PointerType>(FTy->getReturnType()) ||
2575 !isa<PointerType>(FTy->getParamType(0)) ||
2576 !isa<PointerType>(FTy->getParamType(1)))
2579 setDoesNotAlias(F, 0);
2580 setDoesNotCapture(F, 1);
2581 setDoesNotCapture(F, 2);
2582 } else if (Name == "\1fseeko64" ||
2583 Name == "\1ftello64") {
2584 if (FTy->getNumParams() == 0 ||
2585 !isa<PointerType>(FTy->getParamType(0)))
2588 setDoesNotCapture(F, 1);
2589 } else if (Name == "\1tmpfile64") {
2590 if (!isa<PointerType>(FTy->getReturnType()))
2593 setDoesNotAlias(F, 0);
2594 } else if (Name == "\1fstat64" ||
2595 Name == "\1fstatvfs64") {
2596 if (FTy->getNumParams() != 2 ||
2597 !isa<PointerType>(FTy->getParamType(1)))
2600 setDoesNotCapture(F, 2);
2601 } else if (Name == "\1open64") {
2602 if (FTy->getNumParams() < 2 ||
2603 !isa<PointerType>(FTy->getParamType(0)))
2605 // May throw; "open" is a valid pthread cancellation point.
2606 setDoesNotCapture(F, 1);
2615 // Additional cases that we need to add to this file:
2618 // * cbrt(expN(X)) -> expN(x/3)
2619 // * cbrt(sqrt(x)) -> pow(x,1/6)
2620 // * cbrt(sqrt(x)) -> pow(x,1/9)
2623 // * cos(-x) -> cos(x)
2626 // * exp(log(x)) -> x
2629 // * log(exp(x)) -> x
2630 // * log(x**y) -> y*log(x)
2631 // * log(exp(y)) -> y*log(e)
2632 // * log(exp2(y)) -> y*log(2)
2633 // * log(exp10(y)) -> y*log(10)
2634 // * log(sqrt(x)) -> 0.5*log(x)
2635 // * log(pow(x,y)) -> y*log(x)
2637 // lround, lroundf, lroundl:
2638 // * lround(cnst) -> cnst'
2641 // * pow(exp(x),y) -> exp(x*y)
2642 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2643 // * pow(pow(x,y),z)-> pow(x,y*z)
2646 // * puts("") -> putchar("\n")
2648 // round, roundf, roundl:
2649 // * round(cnst) -> cnst'
2652 // * signbit(cnst) -> cnst'
2653 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2655 // sqrt, sqrtf, sqrtl:
2656 // * sqrt(expN(x)) -> expN(x*0.5)
2657 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2658 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2661 // * stpcpy(str, "literal") ->
2662 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2664 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2665 // (if c is a constant integer and s is a constant string)
2666 // * strrchr(s1,0) -> strchr(s1,0)
2669 // * strpbrk(s,a) -> offset_in_for(s,a)
2670 // (if s and a are both constant strings)
2671 // * strpbrk(s,"") -> 0
2672 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2675 // * strspn(s,a) -> const_int (if both args are constant)
2676 // * strspn("",a) -> 0
2677 // * strspn(s,"") -> 0
2678 // * strcspn(s,a) -> const_int (if both args are constant)
2679 // * strcspn("",a) -> 0
2680 // * strcspn(s,"") -> strlen(a)
2683 // * tan(atan(x)) -> x
2685 // trunc, truncf, truncl:
2686 // * trunc(cnst) -> cnst'