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 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
80 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
81 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
82 unsigned Align, IRBuilder<> &B);
84 /// EmitMemMove - Emit a call to the memmove function to the builder. This
85 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
86 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
87 unsigned Align, IRBuilder<> &B);
89 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
90 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
91 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
93 /// EmitMemCmp - Emit a call to the memcmp function.
94 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
96 /// EmitMemSet - Emit a call to the memset function
97 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
99 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
100 /// 'floor'). This function is known to take a single of type matching 'Op'
101 /// and returns one value with the same type. If 'Op' is a long double, 'l'
102 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
103 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
104 const AttrListPtr &Attrs);
106 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
108 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
110 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
112 void EmitPutS(Value *Str, IRBuilder<> &B);
114 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
115 /// an i32, and File is a pointer to FILE.
116 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
118 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
119 /// pointer and File is a pointer to FILE.
120 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
122 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
123 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
124 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
127 } // End anonymous namespace.
129 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
130 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
132 B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
135 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
136 /// specified pointer. This always returns an integer value of size intptr_t.
137 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
138 Module *M = Caller->getParent();
139 AttributeWithIndex AWI[2];
140 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
141 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
142 Attribute::NoUnwind);
144 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
145 TD->getIntPtrType(*Context),
146 Type::getInt8PtrTy(*Context),
148 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
149 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
150 CI->setCallingConv(F->getCallingConv());
155 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
156 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
157 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
158 unsigned Align, IRBuilder<> &B) {
159 Module *M = Caller->getParent();
160 Intrinsic::ID IID = Intrinsic::memcpy;
162 Tys[0] = Len->getType();
163 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
164 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
165 ConstantInt::get(Type::getInt32Ty(*Context), Align));
168 /// EmitMemMOve - Emit a call to the memmove function to the builder. This
169 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
170 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
171 unsigned Align, IRBuilder<> &B) {
172 Module *M = Caller->getParent();
173 Intrinsic::ID IID = Intrinsic::memmove;
175 Tys[0] = TD->getIntPtrType(*Context);
176 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
177 Value *D = CastToCStr(Dst, B);
178 Value *S = CastToCStr(Src, B);
179 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
180 return B.CreateCall4(MemMove, D, S, Len, A);
183 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
184 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
185 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
186 Value *Len, IRBuilder<> &B) {
187 Module *M = Caller->getParent();
188 AttributeWithIndex AWI;
189 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
191 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
192 Type::getInt8PtrTy(*Context),
193 Type::getInt8PtrTy(*Context),
194 Type::getInt32Ty(*Context),
195 TD->getIntPtrType(*Context),
197 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
199 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
200 CI->setCallingConv(F->getCallingConv());
205 /// EmitMemCmp - Emit a call to the memcmp function.
206 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
207 Value *Len, IRBuilder<> &B) {
208 Module *M = Caller->getParent();
209 AttributeWithIndex AWI[3];
210 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
211 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
212 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
213 Attribute::NoUnwind);
215 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
216 Type::getInt32Ty(*Context),
217 Type::getInt8PtrTy(*Context),
218 Type::getInt8PtrTy(*Context),
219 TD->getIntPtrType(*Context), NULL);
220 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
223 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
224 CI->setCallingConv(F->getCallingConv());
229 /// EmitMemSet - Emit a call to the memset function
230 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
231 Value *Len, IRBuilder<> &B) {
232 Module *M = Caller->getParent();
233 Intrinsic::ID IID = Intrinsic::memset;
235 Tys[0] = Len->getType();
236 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
237 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
238 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
241 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
242 /// 'floor'). This function is known to take a single of type matching 'Op' and
243 /// returns one value with the same type. If 'Op' is a long double, 'l' is
244 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
245 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
247 const AttrListPtr &Attrs) {
249 if (!Op->getType()->isDoubleTy()) {
250 // If we need to add a suffix, copy into NameBuffer.
251 unsigned NameLen = strlen(Name);
252 assert(NameLen < sizeof(NameBuffer)-2);
253 memcpy(NameBuffer, Name, NameLen);
254 if (Op->getType()->isFloatTy())
255 NameBuffer[NameLen] = 'f'; // floorf
257 NameBuffer[NameLen] = 'l'; // floorl
258 NameBuffer[NameLen+1] = 0;
262 Module *M = Caller->getParent();
263 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
264 Op->getType(), NULL);
265 CallInst *CI = B.CreateCall(Callee, Op, Name);
266 CI->setAttributes(Attrs);
267 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
268 CI->setCallingConv(F->getCallingConv());
273 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
275 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
276 Module *M = Caller->getParent();
277 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
278 Type::getInt32Ty(*Context), NULL);
279 CallInst *CI = B.CreateCall(PutChar,
280 B.CreateIntCast(Char,
281 Type::getInt32Ty(*Context),
286 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
287 CI->setCallingConv(F->getCallingConv());
291 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
293 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
294 Module *M = Caller->getParent();
295 AttributeWithIndex AWI[2];
296 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
297 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
299 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
300 Type::getInt32Ty(*Context),
301 Type::getInt8PtrTy(*Context),
303 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
304 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
305 CI->setCallingConv(F->getCallingConv());
309 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
310 /// an integer and File is a pointer to FILE.
311 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
312 Module *M = Caller->getParent();
313 AttributeWithIndex AWI[2];
314 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
315 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
317 if (isa<PointerType>(File->getType()))
318 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
319 Type::getInt32Ty(*Context),
320 Type::getInt32Ty(*Context), File->getType(),
323 F = M->getOrInsertFunction("fputc",
324 Type::getInt32Ty(*Context),
325 Type::getInt32Ty(*Context),
326 File->getType(), NULL);
327 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
329 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
331 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
332 CI->setCallingConv(Fn->getCallingConv());
335 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
336 /// pointer and File is a pointer to FILE.
337 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
338 Module *M = Caller->getParent();
339 AttributeWithIndex AWI[3];
340 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
341 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
342 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
344 if (isa<PointerType>(File->getType()))
345 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
346 Type::getInt32Ty(*Context),
347 Type::getInt8PtrTy(*Context),
348 File->getType(), NULL);
350 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
351 Type::getInt8PtrTy(*Context),
352 File->getType(), NULL);
353 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
355 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
356 CI->setCallingConv(Fn->getCallingConv());
359 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
360 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
361 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
363 Module *M = Caller->getParent();
364 AttributeWithIndex AWI[3];
365 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
366 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
367 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
369 if (isa<PointerType>(File->getType()))
370 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
371 TD->getIntPtrType(*Context),
372 Type::getInt8PtrTy(*Context),
373 TD->getIntPtrType(*Context),
374 TD->getIntPtrType(*Context),
375 File->getType(), NULL);
377 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
378 Type::getInt8PtrTy(*Context),
379 TD->getIntPtrType(*Context),
380 TD->getIntPtrType(*Context),
381 File->getType(), NULL);
382 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
383 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
385 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
386 CI->setCallingConv(Fn->getCallingConv());
389 //===----------------------------------------------------------------------===//
391 //===----------------------------------------------------------------------===//
393 /// GetStringLengthH - If we can compute the length of the string pointed to by
394 /// the specified pointer, return 'len+1'. If we can't, return 0.
395 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
396 // Look through noop bitcast instructions.
397 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
398 return GetStringLengthH(BCI->getOperand(0), PHIs);
400 // If this is a PHI node, there are two cases: either we have already seen it
402 if (PHINode *PN = dyn_cast<PHINode>(V)) {
403 if (!PHIs.insert(PN))
404 return ~0ULL; // already in the set.
406 // If it was new, see if all the input strings are the same length.
407 uint64_t LenSoFar = ~0ULL;
408 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
409 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
410 if (Len == 0) return 0; // Unknown length -> unknown.
412 if (Len == ~0ULL) continue;
414 if (Len != LenSoFar && LenSoFar != ~0ULL)
415 return 0; // Disagree -> unknown.
419 // Success, all agree.
423 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
424 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
425 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
426 if (Len1 == 0) return 0;
427 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
428 if (Len2 == 0) return 0;
429 if (Len1 == ~0ULL) return Len2;
430 if (Len2 == ~0ULL) return Len1;
431 if (Len1 != Len2) return 0;
435 // If the value is not a GEP instruction nor a constant expression with a
436 // GEP instruction, then return unknown.
438 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
440 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
441 if (CE->getOpcode() != Instruction::GetElementPtr)
448 // Make sure the GEP has exactly three arguments.
449 if (GEP->getNumOperands() != 3)
452 // Check to make sure that the first operand of the GEP is an integer and
453 // has value 0 so that we are sure we're indexing into the initializer.
454 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
460 // If the second index isn't a ConstantInt, then this is a variable index
461 // into the array. If this occurs, we can't say anything meaningful about
463 uint64_t StartIdx = 0;
464 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
465 StartIdx = CI->getZExtValue();
469 // The GEP instruction, constant or instruction, must reference a global
470 // variable that is a constant and is initialized. The referenced constant
471 // initializer is the array that we'll use for optimization.
472 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
473 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
474 GV->mayBeOverridden())
476 Constant *GlobalInit = GV->getInitializer();
478 // Handle the ConstantAggregateZero case, which is a degenerate case. The
479 // initializer is constant zero so the length of the string must be zero.
480 if (isa<ConstantAggregateZero>(GlobalInit))
481 return 1; // Len = 0 offset by 1.
483 // Must be a Constant Array
484 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
486 Array->getType()->getElementType() != Type::getInt8Ty(V->getContext()))
489 // Get the number of elements in the array
490 uint64_t NumElts = Array->getType()->getNumElements();
492 // Traverse the constant array from StartIdx (derived above) which is
493 // the place the GEP refers to in the array.
494 for (unsigned i = StartIdx; i != NumElts; ++i) {
495 Constant *Elt = Array->getOperand(i);
496 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
497 if (!CI) // This array isn't suitable, non-int initializer.
500 return i-StartIdx+1; // We found end of string, success!
503 return 0; // The array isn't null terminated, conservatively return 'unknown'.
506 /// GetStringLength - If we can compute the length of the string pointed to by
507 /// the specified pointer, return 'len+1'. If we can't, return 0.
508 static uint64_t GetStringLength(Value *V) {
509 if (!isa<PointerType>(V->getType())) return 0;
511 SmallPtrSet<PHINode*, 32> PHIs;
512 uint64_t Len = GetStringLengthH(V, PHIs);
513 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
514 // an empty string as a length.
515 return Len == ~0ULL ? 1 : Len;
518 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
519 /// value is equal or not-equal to zero.
520 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
521 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
523 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
524 if (IC->isEquality())
525 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
526 if (C->isNullValue())
528 // Unknown instruction.
534 //===----------------------------------------------------------------------===//
535 // String and Memory LibCall Optimizations
536 //===----------------------------------------------------------------------===//
538 //===---------------------------------------===//
539 // 'strcat' Optimizations
541 struct StrCatOpt : public LibCallOptimization {
542 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
543 // Verify the "strcat" function prototype.
544 const FunctionType *FT = Callee->getFunctionType();
545 if (FT->getNumParams() != 2 ||
546 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
547 FT->getParamType(0) != FT->getReturnType() ||
548 FT->getParamType(1) != FT->getReturnType())
551 // Extract some information from the instruction
552 Value *Dst = CI->getOperand(1);
553 Value *Src = CI->getOperand(2);
555 // See if we can get the length of the input string.
556 uint64_t Len = GetStringLength(Src);
557 if (Len == 0) return 0;
558 --Len; // Unbias length.
560 // Handle the simple, do-nothing case: strcat(x, "") -> x
564 // These optimizations require TargetData.
567 EmitStrLenMemCpy(Src, Dst, Len, B);
571 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
572 // We need to find the end of the destination string. That's where the
573 // memory is to be moved to. We just generate a call to strlen.
574 Value *DstLen = EmitStrLen(Dst, B);
576 // Now that we have the destination's length, we must index into the
577 // destination's pointer to get the actual memcpy destination (end of
578 // the string .. we're concatenating).
579 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
581 // We have enough information to now generate the memcpy call to do the
582 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
583 EmitMemCpy(CpyDst, Src,
584 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
588 //===---------------------------------------===//
589 // 'strncat' Optimizations
591 struct StrNCatOpt : public StrCatOpt {
592 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
593 // Verify the "strncat" function prototype.
594 const FunctionType *FT = Callee->getFunctionType();
595 if (FT->getNumParams() != 3 ||
596 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
597 FT->getParamType(0) != FT->getReturnType() ||
598 FT->getParamType(1) != FT->getReturnType() ||
599 !isa<IntegerType>(FT->getParamType(2)))
602 // Extract some information from the instruction
603 Value *Dst = CI->getOperand(1);
604 Value *Src = CI->getOperand(2);
607 // We don't do anything if length is not constant
608 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
609 Len = LengthArg->getZExtValue();
613 // See if we can get the length of the input string.
614 uint64_t SrcLen = GetStringLength(Src);
615 if (SrcLen == 0) return 0;
616 --SrcLen; // Unbias length.
618 // Handle the simple, do-nothing cases:
619 // strncat(x, "", c) -> x
620 // strncat(x, c, 0) -> x
621 if (SrcLen == 0 || Len == 0) return Dst;
623 // These optimizations require TargetData.
626 // We don't optimize this case
627 if (Len < SrcLen) return 0;
629 // strncat(x, s, c) -> strcat(x, s)
630 // s is constant so the strcat can be optimized further
631 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
636 //===---------------------------------------===//
637 // 'strchr' Optimizations
639 struct StrChrOpt : public LibCallOptimization {
640 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
641 // Verify the "strchr" function prototype.
642 const FunctionType *FT = Callee->getFunctionType();
643 if (FT->getNumParams() != 2 ||
644 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
645 FT->getParamType(0) != FT->getReturnType())
648 Value *SrcStr = CI->getOperand(1);
650 // If the second operand is non-constant, see if we can compute the length
651 // of the input string and turn this into memchr.
652 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
654 // These optimizations require TargetData.
657 uint64_t Len = GetStringLength(SrcStr);
659 FT->getParamType(1) != Type::getInt32Ty(*Context)) // memchr needs i32.
662 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
663 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
666 // Otherwise, the character is a constant, see if the first argument is
667 // a string literal. If so, we can constant fold.
669 if (!GetConstantStringInfo(SrcStr, Str))
672 // strchr can find the nul character.
674 char CharValue = CharC->getSExtValue();
676 // Compute the offset.
679 if (i == Str.size()) // Didn't find the char. strchr returns null.
680 return Constant::getNullValue(CI->getType());
681 // Did we find our match?
682 if (Str[i] == CharValue)
687 // strchr(s+n,c) -> gep(s+n+i,c)
688 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
689 return B.CreateGEP(SrcStr, Idx, "strchr");
693 //===---------------------------------------===//
694 // 'strcmp' Optimizations
696 struct StrCmpOpt : public LibCallOptimization {
697 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
698 // Verify the "strcmp" function prototype.
699 const FunctionType *FT = Callee->getFunctionType();
700 if (FT->getNumParams() != 2 ||
701 FT->getReturnType() != Type::getInt32Ty(*Context) ||
702 FT->getParamType(0) != FT->getParamType(1) ||
703 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
706 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
707 if (Str1P == Str2P) // strcmp(x,x) -> 0
708 return ConstantInt::get(CI->getType(), 0);
710 std::string Str1, Str2;
711 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
712 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
714 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
715 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
717 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
718 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
720 // strcmp(x, y) -> cnst (if both x and y are constant strings)
721 if (HasStr1 && HasStr2)
722 return ConstantInt::get(CI->getType(),
723 strcmp(Str1.c_str(),Str2.c_str()));
725 // strcmp(P, "x") -> memcmp(P, "x", 2)
726 uint64_t Len1 = GetStringLength(Str1P);
727 uint64_t Len2 = GetStringLength(Str2P);
729 // These optimizations require TargetData.
732 return EmitMemCmp(Str1P, Str2P,
733 ConstantInt::get(TD->getIntPtrType(*Context),
734 std::min(Len1, Len2)), B);
741 //===---------------------------------------===//
742 // 'strncmp' Optimizations
744 struct StrNCmpOpt : public LibCallOptimization {
745 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
746 // Verify the "strncmp" function prototype.
747 const FunctionType *FT = Callee->getFunctionType();
748 if (FT->getNumParams() != 3 ||
749 FT->getReturnType() != Type::getInt32Ty(*Context) ||
750 FT->getParamType(0) != FT->getParamType(1) ||
751 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
752 !isa<IntegerType>(FT->getParamType(2)))
755 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
756 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
757 return ConstantInt::get(CI->getType(), 0);
759 // Get the length argument if it is constant.
761 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
762 Length = LengthArg->getZExtValue();
766 if (Length == 0) // strncmp(x,y,0) -> 0
767 return ConstantInt::get(CI->getType(), 0);
769 std::string Str1, Str2;
770 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
771 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
773 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
774 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
776 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
777 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
779 // strncmp(x, y) -> cnst (if both x and y are constant strings)
780 if (HasStr1 && HasStr2)
781 return ConstantInt::get(CI->getType(),
782 strncmp(Str1.c_str(), Str2.c_str(), Length));
788 //===---------------------------------------===//
789 // 'strcpy' Optimizations
791 struct StrCpyOpt : public LibCallOptimization {
792 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
793 // Verify the "strcpy" function prototype.
794 const FunctionType *FT = Callee->getFunctionType();
795 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
796 FT->getParamType(0) != FT->getParamType(1) ||
797 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
800 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
801 if (Dst == Src) // strcpy(x,x) -> x
804 // These optimizations require TargetData.
807 // See if we can get the length of the input string.
808 uint64_t Len = GetStringLength(Src);
809 if (Len == 0) return 0;
811 // We have enough information to now generate the memcpy call to do the
812 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
814 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
819 //===---------------------------------------===//
820 // 'strncpy' Optimizations
822 struct StrNCpyOpt : public LibCallOptimization {
823 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
824 const FunctionType *FT = Callee->getFunctionType();
825 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
826 FT->getParamType(0) != FT->getParamType(1) ||
827 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
828 !isa<IntegerType>(FT->getParamType(2)))
831 Value *Dst = CI->getOperand(1);
832 Value *Src = CI->getOperand(2);
833 Value *LenOp = CI->getOperand(3);
835 // See if we can get the length of the input string.
836 uint64_t SrcLen = GetStringLength(Src);
837 if (SrcLen == 0) return 0;
841 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
842 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
848 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
849 Len = LengthArg->getZExtValue();
853 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
855 // These optimizations require TargetData.
858 // Let strncpy handle the zero padding
859 if (Len > SrcLen+1) return 0;
861 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
863 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
869 //===---------------------------------------===//
870 // 'strlen' Optimizations
872 struct StrLenOpt : public LibCallOptimization {
873 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
874 const FunctionType *FT = Callee->getFunctionType();
875 if (FT->getNumParams() != 1 ||
876 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
877 !isa<IntegerType>(FT->getReturnType()))
880 Value *Src = CI->getOperand(1);
882 // Constant folding: strlen("xyz") -> 3
883 if (uint64_t Len = GetStringLength(Src))
884 return ConstantInt::get(CI->getType(), Len-1);
886 // Handle strlen(p) != 0.
887 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
889 // strlen(x) != 0 --> *x != 0
890 // strlen(x) == 0 --> *x == 0
891 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
895 //===---------------------------------------===//
896 // 'strto*' Optimizations
898 struct StrToOpt : public LibCallOptimization {
899 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
900 const FunctionType *FT = Callee->getFunctionType();
901 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
902 !isa<PointerType>(FT->getParamType(0)) ||
903 !isa<PointerType>(FT->getParamType(1)))
906 Value *EndPtr = CI->getOperand(2);
907 if (isa<ConstantPointerNull>(EndPtr)) {
908 CI->setOnlyReadsMemory();
909 CI->addAttribute(1, Attribute::NoCapture);
917 //===---------------------------------------===//
918 // 'memcmp' Optimizations
920 struct MemCmpOpt : public LibCallOptimization {
921 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
922 const FunctionType *FT = Callee->getFunctionType();
923 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
924 !isa<PointerType>(FT->getParamType(1)) ||
925 FT->getReturnType() != Type::getInt32Ty(*Context))
928 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
930 if (LHS == RHS) // memcmp(s,s,x) -> 0
931 return Constant::getNullValue(CI->getType());
933 // Make sure we have a constant length.
934 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
936 uint64_t Len = LenC->getZExtValue();
938 if (Len == 0) // memcmp(s1,s2,0) -> 0
939 return Constant::getNullValue(CI->getType());
941 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
942 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
943 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
944 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
947 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
948 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
949 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
950 const Type *PTy = PointerType::getUnqual(Len == 2 ?
951 Type::getInt16Ty(*Context) : Type::getInt32Ty(*Context));
952 LHS = B.CreateBitCast(LHS, PTy, "tmp");
953 RHS = B.CreateBitCast(RHS, PTy, "tmp");
954 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
955 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
956 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
957 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
960 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
961 std::string LHSStr, RHSStr;
962 if (GetConstantStringInfo(LHS, LHSStr) &&
963 GetConstantStringInfo(RHS, RHSStr)) {
964 // Make sure we're not reading out-of-bounds memory.
965 if (Len > LHSStr.length() || Len > RHSStr.length())
967 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
968 return ConstantInt::get(CI->getType(), Ret);
975 //===---------------------------------------===//
976 // 'memcpy' Optimizations
978 struct MemCpyOpt : public LibCallOptimization {
979 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
980 // These optimizations require TargetData.
983 const FunctionType *FT = Callee->getFunctionType();
984 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
985 !isa<PointerType>(FT->getParamType(0)) ||
986 !isa<PointerType>(FT->getParamType(1)) ||
987 FT->getParamType(2) != TD->getIntPtrType(*Context))
990 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
991 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
992 return CI->getOperand(1);
996 //===---------------------------------------===//
997 // 'memmove' Optimizations
999 struct MemMoveOpt : public LibCallOptimization {
1000 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1001 // These optimizations require TargetData.
1004 const FunctionType *FT = Callee->getFunctionType();
1005 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1006 !isa<PointerType>(FT->getParamType(0)) ||
1007 !isa<PointerType>(FT->getParamType(1)) ||
1008 FT->getParamType(2) != TD->getIntPtrType(*Context))
1011 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1012 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1013 return CI->getOperand(1);
1017 //===---------------------------------------===//
1018 // 'memset' Optimizations
1020 struct MemSetOpt : public LibCallOptimization {
1021 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1022 // These optimizations require TargetData.
1025 const FunctionType *FT = Callee->getFunctionType();
1026 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1027 !isa<PointerType>(FT->getParamType(0)) ||
1028 !isa<IntegerType>(FT->getParamType(1)) ||
1029 FT->getParamType(2) != TD->getIntPtrType(*Context))
1032 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1033 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1035 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1036 return CI->getOperand(1);
1040 //===----------------------------------------------------------------------===//
1041 // Object Size Checking Optimizations
1042 //===----------------------------------------------------------------------===//
1044 //===---------------------------------------===//
1047 struct SizeOpt : public LibCallOptimization {
1048 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1049 // TODO: We can do more with this, but delaying to here should be no change
1051 ConstantInt *Const = dyn_cast<ConstantInt>(CI->getOperand(2));
1053 if (!Const) return 0;
1055 const Type *Ty = Callee->getFunctionType()->getReturnType();
1057 if (Const->getZExtValue() < 2)
1058 return Constant::getAllOnesValue(Ty);
1060 return ConstantInt::get(Ty, 0);
1065 //===---------------------------------------===//
1066 // 'memcpy_chk' Optimizations
1068 struct MemCpyChkOpt : public LibCallOptimization {
1069 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1070 // These optimizations require TargetData.
1073 const FunctionType *FT = Callee->getFunctionType();
1074 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1075 !isa<PointerType>(FT->getParamType(0)) ||
1076 !isa<PointerType>(FT->getParamType(1)) ||
1077 !isa<IntegerType>(FT->getParamType(3)) ||
1078 FT->getParamType(2) != TD->getIntPtrType(*Context))
1081 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1084 if (SizeCI->isAllOnesValue()) {
1085 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1086 return CI->getOperand(1);
1093 //===---------------------------------------===//
1094 // 'memset_chk' Optimizations
1096 struct MemSetChkOpt : public LibCallOptimization {
1097 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1098 // These optimizations require TargetData.
1101 const FunctionType *FT = Callee->getFunctionType();
1102 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1103 !isa<PointerType>(FT->getParamType(0)) ||
1104 !isa<IntegerType>(FT->getParamType(1)) ||
1105 !isa<IntegerType>(FT->getParamType(3)) ||
1106 FT->getParamType(2) != TD->getIntPtrType(*Context))
1109 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1112 if (SizeCI->isAllOnesValue()) {
1113 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1115 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1116 return CI->getOperand(1);
1123 //===---------------------------------------===//
1124 // 'memmove_chk' Optimizations
1126 struct MemMoveChkOpt : public LibCallOptimization {
1127 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1128 // These optimizations require TargetData.
1131 const FunctionType *FT = Callee->getFunctionType();
1132 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1133 !isa<PointerType>(FT->getParamType(0)) ||
1134 !isa<PointerType>(FT->getParamType(1)) ||
1135 !isa<IntegerType>(FT->getParamType(3)) ||
1136 FT->getParamType(2) != TD->getIntPtrType(*Context))
1139 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1142 if (SizeCI->isAllOnesValue()) {
1143 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1145 return CI->getOperand(1);
1152 //===----------------------------------------------------------------------===//
1153 // Math Library Optimizations
1154 //===----------------------------------------------------------------------===//
1156 //===---------------------------------------===//
1157 // 'pow*' Optimizations
1159 struct PowOpt : public LibCallOptimization {
1160 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1161 const FunctionType *FT = Callee->getFunctionType();
1162 // Just make sure this has 2 arguments of the same FP type, which match the
1164 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1165 FT->getParamType(0) != FT->getParamType(1) ||
1166 !FT->getParamType(0)->isFloatingPoint())
1169 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1170 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1171 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1173 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1174 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1177 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1178 if (Op2C == 0) return 0;
1180 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1181 return ConstantFP::get(CI->getType(), 1.0);
1183 if (Op2C->isExactlyValue(0.5)) {
1184 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1185 // This is faster than calling pow, and still handles negative zero
1186 // and negative infinite correctly.
1187 // TODO: In fast-math mode, this could be just sqrt(x).
1188 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1189 Value *Inf = ConstantFP::getInfinity(CI->getType());
1190 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1191 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1192 Callee->getAttributes());
1193 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1194 Callee->getAttributes());
1195 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1196 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1200 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1202 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1203 return B.CreateFMul(Op1, Op1, "pow2");
1204 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1205 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1211 //===---------------------------------------===//
1212 // 'exp2' Optimizations
1214 struct Exp2Opt : public LibCallOptimization {
1215 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1216 const FunctionType *FT = Callee->getFunctionType();
1217 // Just make sure this has 1 argument of FP type, which matches the
1219 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1220 !FT->getParamType(0)->isFloatingPoint())
1223 Value *Op = CI->getOperand(1);
1224 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1225 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1226 Value *LdExpArg = 0;
1227 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1228 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1229 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1230 Type::getInt32Ty(*Context), "tmp");
1231 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1232 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1233 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1234 Type::getInt32Ty(*Context), "tmp");
1239 if (Op->getType()->isFloatTy())
1241 else if (Op->getType()->isDoubleTy())
1246 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1247 if (!Op->getType()->isFloatTy())
1248 One = ConstantExpr::getFPExtend(One, Op->getType());
1250 Module *M = Caller->getParent();
1251 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1253 Type::getInt32Ty(*Context),NULL);
1254 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1255 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1256 CI->setCallingConv(F->getCallingConv());
1264 //===---------------------------------------===//
1265 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1267 struct UnaryDoubleFPOpt : public LibCallOptimization {
1268 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1269 const FunctionType *FT = Callee->getFunctionType();
1270 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1271 !FT->getParamType(0)->isDoubleTy())
1274 // If this is something like 'floor((double)floatval)', convert to floorf.
1275 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1276 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1279 // floor((double)floatval) -> (double)floorf(floatval)
1280 Value *V = Cast->getOperand(0);
1281 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1282 Callee->getAttributes());
1283 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1287 //===----------------------------------------------------------------------===//
1288 // Integer Optimizations
1289 //===----------------------------------------------------------------------===//
1291 //===---------------------------------------===//
1292 // 'ffs*' Optimizations
1294 struct FFSOpt : public LibCallOptimization {
1295 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1296 const FunctionType *FT = Callee->getFunctionType();
1297 // Just make sure this has 2 arguments of the same FP type, which match the
1299 if (FT->getNumParams() != 1 ||
1300 FT->getReturnType() != Type::getInt32Ty(*Context) ||
1301 !isa<IntegerType>(FT->getParamType(0)))
1304 Value *Op = CI->getOperand(1);
1307 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1308 if (CI->getValue() == 0) // ffs(0) -> 0.
1309 return Constant::getNullValue(CI->getType());
1310 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1311 CI->getValue().countTrailingZeros()+1);
1314 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1315 const Type *ArgType = Op->getType();
1316 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1317 Intrinsic::cttz, &ArgType, 1);
1318 Value *V = B.CreateCall(F, Op, "cttz");
1319 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1320 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1322 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1323 return B.CreateSelect(Cond, V,
1324 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1328 //===---------------------------------------===//
1329 // 'isdigit' Optimizations
1331 struct IsDigitOpt : public LibCallOptimization {
1332 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1333 const FunctionType *FT = Callee->getFunctionType();
1334 // We require integer(i32)
1335 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1336 FT->getParamType(0) != Type::getInt32Ty(*Context))
1339 // isdigit(c) -> (c-'0') <u 10
1340 Value *Op = CI->getOperand(1);
1341 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1343 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1345 return B.CreateZExt(Op, CI->getType());
1349 //===---------------------------------------===//
1350 // 'isascii' Optimizations
1352 struct IsAsciiOpt : public LibCallOptimization {
1353 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1354 const FunctionType *FT = Callee->getFunctionType();
1355 // We require integer(i32)
1356 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1357 FT->getParamType(0) != Type::getInt32Ty(*Context))
1360 // isascii(c) -> c <u 128
1361 Value *Op = CI->getOperand(1);
1362 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1364 return B.CreateZExt(Op, CI->getType());
1368 //===---------------------------------------===//
1369 // 'abs', 'labs', 'llabs' Optimizations
1371 struct AbsOpt : public LibCallOptimization {
1372 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1373 const FunctionType *FT = Callee->getFunctionType();
1374 // We require integer(integer) where the types agree.
1375 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1376 FT->getParamType(0) != FT->getReturnType())
1379 // abs(x) -> x >s -1 ? x : -x
1380 Value *Op = CI->getOperand(1);
1381 Value *Pos = B.CreateICmpSGT(Op,
1382 Constant::getAllOnesValue(Op->getType()),
1384 Value *Neg = B.CreateNeg(Op, "neg");
1385 return B.CreateSelect(Pos, Op, Neg);
1390 //===---------------------------------------===//
1391 // 'toascii' Optimizations
1393 struct ToAsciiOpt : public LibCallOptimization {
1394 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1395 const FunctionType *FT = Callee->getFunctionType();
1396 // We require i32(i32)
1397 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1398 FT->getParamType(0) != Type::getInt32Ty(*Context))
1401 // isascii(c) -> c & 0x7f
1402 return B.CreateAnd(CI->getOperand(1),
1403 ConstantInt::get(CI->getType(),0x7F));
1407 //===----------------------------------------------------------------------===//
1408 // Formatting and IO Optimizations
1409 //===----------------------------------------------------------------------===//
1411 //===---------------------------------------===//
1412 // 'printf' Optimizations
1414 struct PrintFOpt : public LibCallOptimization {
1415 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1416 // Require one fixed pointer argument and an integer/void result.
1417 const FunctionType *FT = Callee->getFunctionType();
1418 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1419 !(isa<IntegerType>(FT->getReturnType()) ||
1420 FT->getReturnType()->isVoidTy()))
1423 // Check for a fixed format string.
1424 std::string FormatStr;
1425 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1428 // Empty format string -> noop.
1429 if (FormatStr.empty()) // Tolerate printf's declared void.
1430 return CI->use_empty() ? (Value*)CI :
1431 ConstantInt::get(CI->getType(), 0);
1433 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1434 // in case there is an error writing to stdout.
1435 if (FormatStr.size() == 1) {
1436 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1438 if (CI->use_empty()) return CI;
1439 return B.CreateIntCast(Res, CI->getType(), true);
1442 // printf("foo\n") --> puts("foo")
1443 if (FormatStr[FormatStr.size()-1] == '\n' &&
1444 FormatStr.find('%') == std::string::npos) { // no format characters.
1445 // Create a string literal with no \n on it. We expect the constant merge
1446 // pass to be run after this pass, to merge duplicate strings.
1447 FormatStr.erase(FormatStr.end()-1);
1448 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1449 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1450 GlobalVariable::InternalLinkage, C, "str");
1452 return CI->use_empty() ? (Value*)CI :
1453 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1456 // Optimize specific format strings.
1457 // printf("%c", chr) --> putchar(*(i8*)dst)
1458 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1459 isa<IntegerType>(CI->getOperand(2)->getType())) {
1460 Value *Res = EmitPutChar(CI->getOperand(2), B);
1462 if (CI->use_empty()) return CI;
1463 return B.CreateIntCast(Res, CI->getType(), true);
1466 // printf("%s\n", str) --> puts(str)
1467 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1468 isa<PointerType>(CI->getOperand(2)->getType()) &&
1470 EmitPutS(CI->getOperand(2), B);
1477 //===---------------------------------------===//
1478 // 'sprintf' Optimizations
1480 struct SPrintFOpt : public LibCallOptimization {
1481 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1482 // Require two fixed pointer arguments and an integer result.
1483 const FunctionType *FT = Callee->getFunctionType();
1484 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1485 !isa<PointerType>(FT->getParamType(1)) ||
1486 !isa<IntegerType>(FT->getReturnType()))
1489 // Check for a fixed format string.
1490 std::string FormatStr;
1491 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1494 // If we just have a format string (nothing else crazy) transform it.
1495 if (CI->getNumOperands() == 3) {
1496 // Make sure there's no % in the constant array. We could try to handle
1497 // %% -> % in the future if we cared.
1498 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1499 if (FormatStr[i] == '%')
1500 return 0; // we found a format specifier, bail out.
1502 // These optimizations require TargetData.
1505 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1506 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1507 ConstantInt::get(TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1508 return ConstantInt::get(CI->getType(), FormatStr.size());
1511 // The remaining optimizations require the format string to be "%s" or "%c"
1512 // and have an extra operand.
1513 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1516 // Decode the second character of the format string.
1517 if (FormatStr[1] == 'c') {
1518 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1519 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1520 Value *V = B.CreateTrunc(CI->getOperand(3),
1521 Type::getInt8Ty(*Context), "char");
1522 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1523 B.CreateStore(V, Ptr);
1524 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1526 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1528 return ConstantInt::get(CI->getType(), 1);
1531 if (FormatStr[1] == 's') {
1532 // These optimizations require TargetData.
1535 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1536 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1538 Value *Len = EmitStrLen(CI->getOperand(3), B);
1539 Value *IncLen = B.CreateAdd(Len,
1540 ConstantInt::get(Len->getType(), 1),
1542 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1544 // The sprintf result is the unincremented number of bytes in the string.
1545 return B.CreateIntCast(Len, CI->getType(), false);
1551 //===---------------------------------------===//
1552 // 'fwrite' Optimizations
1554 struct FWriteOpt : public LibCallOptimization {
1555 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1556 // Require a pointer, an integer, an integer, a pointer, returning integer.
1557 const FunctionType *FT = Callee->getFunctionType();
1558 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1559 !isa<IntegerType>(FT->getParamType(1)) ||
1560 !isa<IntegerType>(FT->getParamType(2)) ||
1561 !isa<PointerType>(FT->getParamType(3)) ||
1562 !isa<IntegerType>(FT->getReturnType()))
1565 // Get the element size and count.
1566 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1567 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1568 if (!SizeC || !CountC) return 0;
1569 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1571 // If this is writing zero records, remove the call (it's a noop).
1573 return ConstantInt::get(CI->getType(), 0);
1575 // If this is writing one byte, turn it into fputc.
1576 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1577 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1578 EmitFPutC(Char, CI->getOperand(4), B);
1579 return ConstantInt::get(CI->getType(), 1);
1586 //===---------------------------------------===//
1587 // 'fputs' Optimizations
1589 struct FPutsOpt : public LibCallOptimization {
1590 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1591 // These optimizations require TargetData.
1594 // Require two pointers. Also, we can't optimize if return value is used.
1595 const FunctionType *FT = Callee->getFunctionType();
1596 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1597 !isa<PointerType>(FT->getParamType(1)) ||
1601 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1602 uint64_t Len = GetStringLength(CI->getOperand(1));
1604 EmitFWrite(CI->getOperand(1),
1605 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1606 CI->getOperand(2), B);
1607 return CI; // Known to have no uses (see above).
1611 //===---------------------------------------===//
1612 // 'fprintf' Optimizations
1614 struct FPrintFOpt : public LibCallOptimization {
1615 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1616 // Require two fixed paramters as pointers and integer result.
1617 const FunctionType *FT = Callee->getFunctionType();
1618 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1619 !isa<PointerType>(FT->getParamType(1)) ||
1620 !isa<IntegerType>(FT->getReturnType()))
1623 // All the optimizations depend on the format string.
1624 std::string FormatStr;
1625 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1628 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1629 if (CI->getNumOperands() == 3) {
1630 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1631 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1632 return 0; // We found a format specifier.
1634 // These optimizations require TargetData.
1637 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(*Context),
1639 CI->getOperand(1), B);
1640 return ConstantInt::get(CI->getType(), FormatStr.size());
1643 // The remaining optimizations require the format string to be "%s" or "%c"
1644 // and have an extra operand.
1645 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1648 // Decode the second character of the format string.
1649 if (FormatStr[1] == 'c') {
1650 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1651 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1652 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1653 return ConstantInt::get(CI->getType(), 1);
1656 if (FormatStr[1] == 's') {
1657 // fprintf(F, "%s", str) -> fputs(str, F)
1658 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1660 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1667 } // end anonymous namespace.
1669 //===----------------------------------------------------------------------===//
1670 // SimplifyLibCalls Pass Implementation
1671 //===----------------------------------------------------------------------===//
1674 /// This pass optimizes well known library functions from libc and libm.
1676 class SimplifyLibCalls : public FunctionPass {
1677 StringMap<LibCallOptimization*> Optimizations;
1678 // String and Memory LibCall Optimizations
1679 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1680 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1681 StrToOpt StrTo; MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove;
1683 // Math Library Optimizations
1684 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1685 // Integer Optimizations
1686 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1688 // Formatting and IO Optimizations
1689 SPrintFOpt SPrintF; PrintFOpt PrintF;
1690 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1692 // Object Size Checking
1694 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1696 bool Modified; // This is only used by doInitialization.
1698 static char ID; // Pass identification
1699 SimplifyLibCalls() : FunctionPass(&ID) {}
1701 void InitOptimizations();
1702 bool runOnFunction(Function &F);
1704 void setDoesNotAccessMemory(Function &F);
1705 void setOnlyReadsMemory(Function &F);
1706 void setDoesNotThrow(Function &F);
1707 void setDoesNotCapture(Function &F, unsigned n);
1708 void setDoesNotAlias(Function &F, unsigned n);
1709 bool doInitialization(Module &M);
1711 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1714 char SimplifyLibCalls::ID = 0;
1715 } // end anonymous namespace.
1717 static RegisterPass<SimplifyLibCalls>
1718 X("simplify-libcalls", "Simplify well-known library calls");
1720 // Public interface to the Simplify LibCalls pass.
1721 FunctionPass *llvm::createSimplifyLibCallsPass() {
1722 return new SimplifyLibCalls();
1725 /// Optimizations - Populate the Optimizations map with all the optimizations
1727 void SimplifyLibCalls::InitOptimizations() {
1728 // String and Memory LibCall Optimizations
1729 Optimizations["strcat"] = &StrCat;
1730 Optimizations["strncat"] = &StrNCat;
1731 Optimizations["strchr"] = &StrChr;
1732 Optimizations["strcmp"] = &StrCmp;
1733 Optimizations["strncmp"] = &StrNCmp;
1734 Optimizations["strcpy"] = &StrCpy;
1735 Optimizations["strncpy"] = &StrNCpy;
1736 Optimizations["strlen"] = &StrLen;
1737 Optimizations["strtol"] = &StrTo;
1738 Optimizations["strtod"] = &StrTo;
1739 Optimizations["strtof"] = &StrTo;
1740 Optimizations["strtoul"] = &StrTo;
1741 Optimizations["strtoll"] = &StrTo;
1742 Optimizations["strtold"] = &StrTo;
1743 Optimizations["strtoull"] = &StrTo;
1744 Optimizations["memcmp"] = &MemCmp;
1745 Optimizations["memcpy"] = &MemCpy;
1746 Optimizations["memmove"] = &MemMove;
1747 Optimizations["memset"] = &MemSet;
1749 // Math Library Optimizations
1750 Optimizations["powf"] = &Pow;
1751 Optimizations["pow"] = &Pow;
1752 Optimizations["powl"] = &Pow;
1753 Optimizations["llvm.pow.f32"] = &Pow;
1754 Optimizations["llvm.pow.f64"] = &Pow;
1755 Optimizations["llvm.pow.f80"] = &Pow;
1756 Optimizations["llvm.pow.f128"] = &Pow;
1757 Optimizations["llvm.pow.ppcf128"] = &Pow;
1758 Optimizations["exp2l"] = &Exp2;
1759 Optimizations["exp2"] = &Exp2;
1760 Optimizations["exp2f"] = &Exp2;
1761 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1762 Optimizations["llvm.exp2.f128"] = &Exp2;
1763 Optimizations["llvm.exp2.f80"] = &Exp2;
1764 Optimizations["llvm.exp2.f64"] = &Exp2;
1765 Optimizations["llvm.exp2.f32"] = &Exp2;
1768 Optimizations["floor"] = &UnaryDoubleFP;
1771 Optimizations["ceil"] = &UnaryDoubleFP;
1774 Optimizations["round"] = &UnaryDoubleFP;
1777 Optimizations["rint"] = &UnaryDoubleFP;
1779 #ifdef HAVE_NEARBYINTF
1780 Optimizations["nearbyint"] = &UnaryDoubleFP;
1783 // Integer Optimizations
1784 Optimizations["ffs"] = &FFS;
1785 Optimizations["ffsl"] = &FFS;
1786 Optimizations["ffsll"] = &FFS;
1787 Optimizations["abs"] = &Abs;
1788 Optimizations["labs"] = &Abs;
1789 Optimizations["llabs"] = &Abs;
1790 Optimizations["isdigit"] = &IsDigit;
1791 Optimizations["isascii"] = &IsAscii;
1792 Optimizations["toascii"] = &ToAscii;
1794 // Formatting and IO Optimizations
1795 Optimizations["sprintf"] = &SPrintF;
1796 Optimizations["printf"] = &PrintF;
1797 Optimizations["fwrite"] = &FWrite;
1798 Optimizations["fputs"] = &FPuts;
1799 Optimizations["fprintf"] = &FPrintF;
1801 // Object Size Checking
1802 Optimizations["llvm.objectsize.i32"] = &ObjectSize;
1803 Optimizations["llvm.objectsize.i64"] = &ObjectSize;
1804 Optimizations["__memcpy_chk"] = &MemCpyChk;
1805 Optimizations["__memset_chk"] = &MemSetChk;
1806 Optimizations["__memmove_chk"] = &MemMoveChk;
1810 /// runOnFunction - Top level algorithm.
1812 bool SimplifyLibCalls::runOnFunction(Function &F) {
1813 if (Optimizations.empty())
1814 InitOptimizations();
1816 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1818 IRBuilder<> Builder(F.getContext());
1820 bool Changed = false;
1821 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1822 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1823 // Ignore non-calls.
1824 CallInst *CI = dyn_cast<CallInst>(I++);
1827 // Ignore indirect calls and calls to non-external functions.
1828 Function *Callee = CI->getCalledFunction();
1829 if (Callee == 0 || !Callee->isDeclaration() ||
1830 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1833 // Ignore unknown calls.
1834 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1837 // Set the builder to the instruction after the call.
1838 Builder.SetInsertPoint(BB, I);
1840 // Try to optimize this call.
1841 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1842 if (Result == 0) continue;
1844 DEBUG(errs() << "SimplifyLibCalls simplified: " << *CI;
1845 errs() << " into: " << *Result << "\n");
1847 // Something changed!
1851 // Inspect the instruction after the call (which was potentially just
1855 if (CI != Result && !CI->use_empty()) {
1856 CI->replaceAllUsesWith(Result);
1857 if (!Result->hasName())
1858 Result->takeName(CI);
1860 CI->eraseFromParent();
1866 // Utility methods for doInitialization.
1868 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1869 if (!F.doesNotAccessMemory()) {
1870 F.setDoesNotAccessMemory();
1875 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1876 if (!F.onlyReadsMemory()) {
1877 F.setOnlyReadsMemory();
1882 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1883 if (!F.doesNotThrow()) {
1884 F.setDoesNotThrow();
1889 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1890 if (!F.doesNotCapture(n)) {
1891 F.setDoesNotCapture(n);
1896 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1897 if (!F.doesNotAlias(n)) {
1898 F.setDoesNotAlias(n);
1904 /// doInitialization - Add attributes to well-known functions.
1906 bool SimplifyLibCalls::doInitialization(Module &M) {
1908 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1910 if (!F.isDeclaration())
1916 const FunctionType *FTy = F.getFunctionType();
1918 StringRef Name = F.getName();
1921 if (Name == "strlen") {
1922 if (FTy->getNumParams() != 1 ||
1923 !isa<PointerType>(FTy->getParamType(0)))
1925 setOnlyReadsMemory(F);
1927 setDoesNotCapture(F, 1);
1928 } else if (Name == "strcpy" ||
1934 Name == "strtoul" ||
1935 Name == "strtoll" ||
1936 Name == "strtold" ||
1937 Name == "strncat" ||
1938 Name == "strncpy" ||
1939 Name == "strtoull") {
1940 if (FTy->getNumParams() < 2 ||
1941 !isa<PointerType>(FTy->getParamType(1)))
1944 setDoesNotCapture(F, 2);
1945 } else if (Name == "strxfrm") {
1946 if (FTy->getNumParams() != 3 ||
1947 !isa<PointerType>(FTy->getParamType(0)) ||
1948 !isa<PointerType>(FTy->getParamType(1)))
1951 setDoesNotCapture(F, 1);
1952 setDoesNotCapture(F, 2);
1953 } else if (Name == "strcmp" ||
1955 Name == "strncmp" ||
1956 Name ==" strcspn" ||
1957 Name == "strcoll" ||
1958 Name == "strcasecmp" ||
1959 Name == "strncasecmp") {
1960 if (FTy->getNumParams() < 2 ||
1961 !isa<PointerType>(FTy->getParamType(0)) ||
1962 !isa<PointerType>(FTy->getParamType(1)))
1964 setOnlyReadsMemory(F);
1966 setDoesNotCapture(F, 1);
1967 setDoesNotCapture(F, 2);
1968 } else if (Name == "strstr" ||
1969 Name == "strpbrk") {
1970 if (FTy->getNumParams() != 2 ||
1971 !isa<PointerType>(FTy->getParamType(1)))
1973 setOnlyReadsMemory(F);
1975 setDoesNotCapture(F, 2);
1976 } else if (Name == "strtok" ||
1977 Name == "strtok_r") {
1978 if (FTy->getNumParams() < 2 ||
1979 !isa<PointerType>(FTy->getParamType(1)))
1982 setDoesNotCapture(F, 2);
1983 } else if (Name == "scanf" ||
1985 Name == "setvbuf") {
1986 if (FTy->getNumParams() < 1 ||
1987 !isa<PointerType>(FTy->getParamType(0)))
1990 setDoesNotCapture(F, 1);
1991 } else if (Name == "strdup" ||
1992 Name == "strndup") {
1993 if (FTy->getNumParams() < 1 ||
1994 !isa<PointerType>(FTy->getReturnType()) ||
1995 !isa<PointerType>(FTy->getParamType(0)))
1998 setDoesNotAlias(F, 0);
1999 setDoesNotCapture(F, 1);
2000 } else if (Name == "stat" ||
2002 Name == "sprintf" ||
2003 Name == "statvfs") {
2004 if (FTy->getNumParams() < 2 ||
2005 !isa<PointerType>(FTy->getParamType(0)) ||
2006 !isa<PointerType>(FTy->getParamType(1)))
2009 setDoesNotCapture(F, 1);
2010 setDoesNotCapture(F, 2);
2011 } else if (Name == "snprintf") {
2012 if (FTy->getNumParams() != 3 ||
2013 !isa<PointerType>(FTy->getParamType(0)) ||
2014 !isa<PointerType>(FTy->getParamType(2)))
2017 setDoesNotCapture(F, 1);
2018 setDoesNotCapture(F, 3);
2019 } else if (Name == "setitimer") {
2020 if (FTy->getNumParams() != 3 ||
2021 !isa<PointerType>(FTy->getParamType(1)) ||
2022 !isa<PointerType>(FTy->getParamType(2)))
2025 setDoesNotCapture(F, 2);
2026 setDoesNotCapture(F, 3);
2027 } else if (Name == "system") {
2028 if (FTy->getNumParams() != 1 ||
2029 !isa<PointerType>(FTy->getParamType(0)))
2031 // May throw; "system" is a valid pthread cancellation point.
2032 setDoesNotCapture(F, 1);
2036 if (Name == "malloc") {
2037 if (FTy->getNumParams() != 1 ||
2038 !isa<PointerType>(FTy->getReturnType()))
2041 setDoesNotAlias(F, 0);
2042 } else if (Name == "memcmp") {
2043 if (FTy->getNumParams() != 3 ||
2044 !isa<PointerType>(FTy->getParamType(0)) ||
2045 !isa<PointerType>(FTy->getParamType(1)))
2047 setOnlyReadsMemory(F);
2049 setDoesNotCapture(F, 1);
2050 setDoesNotCapture(F, 2);
2051 } else if (Name == "memchr" ||
2052 Name == "memrchr") {
2053 if (FTy->getNumParams() != 3)
2055 setOnlyReadsMemory(F);
2057 } else if (Name == "modf" ||
2061 Name == "memccpy" ||
2062 Name == "memmove") {
2063 if (FTy->getNumParams() < 2 ||
2064 !isa<PointerType>(FTy->getParamType(1)))
2067 setDoesNotCapture(F, 2);
2068 } else if (Name == "memalign") {
2069 if (!isa<PointerType>(FTy->getReturnType()))
2071 setDoesNotAlias(F, 0);
2072 } else if (Name == "mkdir" ||
2074 if (FTy->getNumParams() == 0 ||
2075 !isa<PointerType>(FTy->getParamType(0)))
2078 setDoesNotCapture(F, 1);
2082 if (Name == "realloc") {
2083 if (FTy->getNumParams() != 2 ||
2084 !isa<PointerType>(FTy->getParamType(0)) ||
2085 !isa<PointerType>(FTy->getReturnType()))
2088 setDoesNotAlias(F, 0);
2089 setDoesNotCapture(F, 1);
2090 } else if (Name == "read") {
2091 if (FTy->getNumParams() != 3 ||
2092 !isa<PointerType>(FTy->getParamType(1)))
2094 // May throw; "read" is a valid pthread cancellation point.
2095 setDoesNotCapture(F, 2);
2096 } else if (Name == "rmdir" ||
2099 Name == "realpath") {
2100 if (FTy->getNumParams() < 1 ||
2101 !isa<PointerType>(FTy->getParamType(0)))
2104 setDoesNotCapture(F, 1);
2105 } else if (Name == "rename" ||
2106 Name == "readlink") {
2107 if (FTy->getNumParams() < 2 ||
2108 !isa<PointerType>(FTy->getParamType(0)) ||
2109 !isa<PointerType>(FTy->getParamType(1)))
2112 setDoesNotCapture(F, 1);
2113 setDoesNotCapture(F, 2);
2117 if (Name == "write") {
2118 if (FTy->getNumParams() != 3 ||
2119 !isa<PointerType>(FTy->getParamType(1)))
2121 // May throw; "write" is a valid pthread cancellation point.
2122 setDoesNotCapture(F, 2);
2126 if (Name == "bcopy") {
2127 if (FTy->getNumParams() != 3 ||
2128 !isa<PointerType>(FTy->getParamType(0)) ||
2129 !isa<PointerType>(FTy->getParamType(1)))
2132 setDoesNotCapture(F, 1);
2133 setDoesNotCapture(F, 2);
2134 } else if (Name == "bcmp") {
2135 if (FTy->getNumParams() != 3 ||
2136 !isa<PointerType>(FTy->getParamType(0)) ||
2137 !isa<PointerType>(FTy->getParamType(1)))
2140 setOnlyReadsMemory(F);
2141 setDoesNotCapture(F, 1);
2142 setDoesNotCapture(F, 2);
2143 } else if (Name == "bzero") {
2144 if (FTy->getNumParams() != 2 ||
2145 !isa<PointerType>(FTy->getParamType(0)))
2148 setDoesNotCapture(F, 1);
2152 if (Name == "calloc") {
2153 if (FTy->getNumParams() != 2 ||
2154 !isa<PointerType>(FTy->getReturnType()))
2157 setDoesNotAlias(F, 0);
2158 } else if (Name == "chmod" ||
2160 Name == "ctermid" ||
2161 Name == "clearerr" ||
2162 Name == "closedir") {
2163 if (FTy->getNumParams() == 0 ||
2164 !isa<PointerType>(FTy->getParamType(0)))
2167 setDoesNotCapture(F, 1);
2171 if (Name == "atoi" ||
2175 if (FTy->getNumParams() != 1 ||
2176 !isa<PointerType>(FTy->getParamType(0)))
2179 setOnlyReadsMemory(F);
2180 setDoesNotCapture(F, 1);
2181 } else if (Name == "access") {
2182 if (FTy->getNumParams() != 2 ||
2183 !isa<PointerType>(FTy->getParamType(0)))
2186 setDoesNotCapture(F, 1);
2190 if (Name == "fopen") {
2191 if (FTy->getNumParams() != 2 ||
2192 !isa<PointerType>(FTy->getReturnType()) ||
2193 !isa<PointerType>(FTy->getParamType(0)) ||
2194 !isa<PointerType>(FTy->getParamType(1)))
2197 setDoesNotAlias(F, 0);
2198 setDoesNotCapture(F, 1);
2199 setDoesNotCapture(F, 2);
2200 } else if (Name == "fdopen") {
2201 if (FTy->getNumParams() != 2 ||
2202 !isa<PointerType>(FTy->getReturnType()) ||
2203 !isa<PointerType>(FTy->getParamType(1)))
2206 setDoesNotAlias(F, 0);
2207 setDoesNotCapture(F, 2);
2208 } else if (Name == "feof" ||
2218 Name == "fsetpos" ||
2219 Name == "flockfile" ||
2220 Name == "funlockfile" ||
2221 Name == "ftrylockfile") {
2222 if (FTy->getNumParams() == 0 ||
2223 !isa<PointerType>(FTy->getParamType(0)))
2226 setDoesNotCapture(F, 1);
2227 } else if (Name == "ferror") {
2228 if (FTy->getNumParams() != 1 ||
2229 !isa<PointerType>(FTy->getParamType(0)))
2232 setDoesNotCapture(F, 1);
2233 setOnlyReadsMemory(F);
2234 } else if (Name == "fputc" ||
2239 Name == "fstatvfs") {
2240 if (FTy->getNumParams() != 2 ||
2241 !isa<PointerType>(FTy->getParamType(1)))
2244 setDoesNotCapture(F, 2);
2245 } else if (Name == "fgets") {
2246 if (FTy->getNumParams() != 3 ||
2247 !isa<PointerType>(FTy->getParamType(0)) ||
2248 !isa<PointerType>(FTy->getParamType(2)))
2251 setDoesNotCapture(F, 3);
2252 } else if (Name == "fread" ||
2254 if (FTy->getNumParams() != 4 ||
2255 !isa<PointerType>(FTy->getParamType(0)) ||
2256 !isa<PointerType>(FTy->getParamType(3)))
2259 setDoesNotCapture(F, 1);
2260 setDoesNotCapture(F, 4);
2261 } else if (Name == "fputs" ||
2263 Name == "fprintf" ||
2264 Name == "fgetpos") {
2265 if (FTy->getNumParams() < 2 ||
2266 !isa<PointerType>(FTy->getParamType(0)) ||
2267 !isa<PointerType>(FTy->getParamType(1)))
2270 setDoesNotCapture(F, 1);
2271 setDoesNotCapture(F, 2);
2275 if (Name == "getc" ||
2276 Name == "getlogin_r" ||
2277 Name == "getc_unlocked") {
2278 if (FTy->getNumParams() == 0 ||
2279 !isa<PointerType>(FTy->getParamType(0)))
2282 setDoesNotCapture(F, 1);
2283 } else if (Name == "getenv") {
2284 if (FTy->getNumParams() != 1 ||
2285 !isa<PointerType>(FTy->getParamType(0)))
2288 setOnlyReadsMemory(F);
2289 setDoesNotCapture(F, 1);
2290 } else if (Name == "gets" ||
2291 Name == "getchar") {
2293 } else if (Name == "getitimer") {
2294 if (FTy->getNumParams() != 2 ||
2295 !isa<PointerType>(FTy->getParamType(1)))
2298 setDoesNotCapture(F, 2);
2299 } else if (Name == "getpwnam") {
2300 if (FTy->getNumParams() != 1 ||
2301 !isa<PointerType>(FTy->getParamType(0)))
2304 setDoesNotCapture(F, 1);
2308 if (Name == "ungetc") {
2309 if (FTy->getNumParams() != 2 ||
2310 !isa<PointerType>(FTy->getParamType(1)))
2313 setDoesNotCapture(F, 2);
2314 } else if (Name == "uname" ||
2316 Name == "unsetenv") {
2317 if (FTy->getNumParams() != 1 ||
2318 !isa<PointerType>(FTy->getParamType(0)))
2321 setDoesNotCapture(F, 1);
2322 } else if (Name == "utime" ||
2324 if (FTy->getNumParams() != 2 ||
2325 !isa<PointerType>(FTy->getParamType(0)) ||
2326 !isa<PointerType>(FTy->getParamType(1)))
2329 setDoesNotCapture(F, 1);
2330 setDoesNotCapture(F, 2);
2334 if (Name == "putc") {
2335 if (FTy->getNumParams() != 2 ||
2336 !isa<PointerType>(FTy->getParamType(1)))
2339 setDoesNotCapture(F, 2);
2340 } else if (Name == "puts" ||
2343 if (FTy->getNumParams() != 1 ||
2344 !isa<PointerType>(FTy->getParamType(0)))
2347 setDoesNotCapture(F, 1);
2348 } else if (Name == "pread" ||
2350 if (FTy->getNumParams() != 4 ||
2351 !isa<PointerType>(FTy->getParamType(1)))
2353 // May throw; these are valid pthread cancellation points.
2354 setDoesNotCapture(F, 2);
2355 } else if (Name == "putchar") {
2357 } else if (Name == "popen") {
2358 if (FTy->getNumParams() != 2 ||
2359 !isa<PointerType>(FTy->getReturnType()) ||
2360 !isa<PointerType>(FTy->getParamType(0)) ||
2361 !isa<PointerType>(FTy->getParamType(1)))
2364 setDoesNotAlias(F, 0);
2365 setDoesNotCapture(F, 1);
2366 setDoesNotCapture(F, 2);
2367 } else if (Name == "pclose") {
2368 if (FTy->getNumParams() != 1 ||
2369 !isa<PointerType>(FTy->getParamType(0)))
2372 setDoesNotCapture(F, 1);
2376 if (Name == "vscanf") {
2377 if (FTy->getNumParams() != 2 ||
2378 !isa<PointerType>(FTy->getParamType(1)))
2381 setDoesNotCapture(F, 1);
2382 } else if (Name == "vsscanf" ||
2383 Name == "vfscanf") {
2384 if (FTy->getNumParams() != 3 ||
2385 !isa<PointerType>(FTy->getParamType(1)) ||
2386 !isa<PointerType>(FTy->getParamType(2)))
2389 setDoesNotCapture(F, 1);
2390 setDoesNotCapture(F, 2);
2391 } else if (Name == "valloc") {
2392 if (!isa<PointerType>(FTy->getReturnType()))
2395 setDoesNotAlias(F, 0);
2396 } else if (Name == "vprintf") {
2397 if (FTy->getNumParams() != 2 ||
2398 !isa<PointerType>(FTy->getParamType(0)))
2401 setDoesNotCapture(F, 1);
2402 } else if (Name == "vfprintf" ||
2403 Name == "vsprintf") {
2404 if (FTy->getNumParams() != 3 ||
2405 !isa<PointerType>(FTy->getParamType(0)) ||
2406 !isa<PointerType>(FTy->getParamType(1)))
2409 setDoesNotCapture(F, 1);
2410 setDoesNotCapture(F, 2);
2411 } else if (Name == "vsnprintf") {
2412 if (FTy->getNumParams() != 4 ||
2413 !isa<PointerType>(FTy->getParamType(0)) ||
2414 !isa<PointerType>(FTy->getParamType(2)))
2417 setDoesNotCapture(F, 1);
2418 setDoesNotCapture(F, 3);
2422 if (Name == "open") {
2423 if (FTy->getNumParams() < 2 ||
2424 !isa<PointerType>(FTy->getParamType(0)))
2426 // May throw; "open" is a valid pthread cancellation point.
2427 setDoesNotCapture(F, 1);
2428 } else if (Name == "opendir") {
2429 if (FTy->getNumParams() != 1 ||
2430 !isa<PointerType>(FTy->getReturnType()) ||
2431 !isa<PointerType>(FTy->getParamType(0)))
2434 setDoesNotAlias(F, 0);
2435 setDoesNotCapture(F, 1);
2439 if (Name == "tmpfile") {
2440 if (!isa<PointerType>(FTy->getReturnType()))
2443 setDoesNotAlias(F, 0);
2444 } else if (Name == "times") {
2445 if (FTy->getNumParams() != 1 ||
2446 !isa<PointerType>(FTy->getParamType(0)))
2449 setDoesNotCapture(F, 1);
2453 if (Name == "htonl" ||
2456 setDoesNotAccessMemory(F);
2460 if (Name == "ntohl" ||
2463 setDoesNotAccessMemory(F);
2467 if (Name == "lstat") {
2468 if (FTy->getNumParams() != 2 ||
2469 !isa<PointerType>(FTy->getParamType(0)) ||
2470 !isa<PointerType>(FTy->getParamType(1)))
2473 setDoesNotCapture(F, 1);
2474 setDoesNotCapture(F, 2);
2475 } else if (Name == "lchown") {
2476 if (FTy->getNumParams() != 3 ||
2477 !isa<PointerType>(FTy->getParamType(0)))
2480 setDoesNotCapture(F, 1);
2484 if (Name == "qsort") {
2485 if (FTy->getNumParams() != 4 ||
2486 !isa<PointerType>(FTy->getParamType(3)))
2488 // May throw; places call through function pointer.
2489 setDoesNotCapture(F, 4);
2493 if (Name == "__strdup" ||
2494 Name == "__strndup") {
2495 if (FTy->getNumParams() < 1 ||
2496 !isa<PointerType>(FTy->getReturnType()) ||
2497 !isa<PointerType>(FTy->getParamType(0)))
2500 setDoesNotAlias(F, 0);
2501 setDoesNotCapture(F, 1);
2502 } else if (Name == "__strtok_r") {
2503 if (FTy->getNumParams() != 3 ||
2504 !isa<PointerType>(FTy->getParamType(1)))
2507 setDoesNotCapture(F, 2);
2508 } else if (Name == "_IO_getc") {
2509 if (FTy->getNumParams() != 1 ||
2510 !isa<PointerType>(FTy->getParamType(0)))
2513 setDoesNotCapture(F, 1);
2514 } else if (Name == "_IO_putc") {
2515 if (FTy->getNumParams() != 2 ||
2516 !isa<PointerType>(FTy->getParamType(1)))
2519 setDoesNotCapture(F, 2);
2523 if (Name == "\1__isoc99_scanf") {
2524 if (FTy->getNumParams() < 1 ||
2525 !isa<PointerType>(FTy->getParamType(0)))
2528 setDoesNotCapture(F, 1);
2529 } else if (Name == "\1stat64" ||
2530 Name == "\1lstat64" ||
2531 Name == "\1statvfs64" ||
2532 Name == "\1__isoc99_sscanf") {
2533 if (FTy->getNumParams() < 1 ||
2534 !isa<PointerType>(FTy->getParamType(0)) ||
2535 !isa<PointerType>(FTy->getParamType(1)))
2538 setDoesNotCapture(F, 1);
2539 setDoesNotCapture(F, 2);
2540 } else if (Name == "\1fopen64") {
2541 if (FTy->getNumParams() != 2 ||
2542 !isa<PointerType>(FTy->getReturnType()) ||
2543 !isa<PointerType>(FTy->getParamType(0)) ||
2544 !isa<PointerType>(FTy->getParamType(1)))
2547 setDoesNotAlias(F, 0);
2548 setDoesNotCapture(F, 1);
2549 setDoesNotCapture(F, 2);
2550 } else if (Name == "\1fseeko64" ||
2551 Name == "\1ftello64") {
2552 if (FTy->getNumParams() == 0 ||
2553 !isa<PointerType>(FTy->getParamType(0)))
2556 setDoesNotCapture(F, 1);
2557 } else if (Name == "\1tmpfile64") {
2558 if (!isa<PointerType>(FTy->getReturnType()))
2561 setDoesNotAlias(F, 0);
2562 } else if (Name == "\1fstat64" ||
2563 Name == "\1fstatvfs64") {
2564 if (FTy->getNumParams() != 2 ||
2565 !isa<PointerType>(FTy->getParamType(1)))
2568 setDoesNotCapture(F, 2);
2569 } else if (Name == "\1open64") {
2570 if (FTy->getNumParams() < 2 ||
2571 !isa<PointerType>(FTy->getParamType(0)))
2573 // May throw; "open" is a valid pthread cancellation point.
2574 setDoesNotCapture(F, 1);
2583 // Additional cases that we need to add to this file:
2586 // * cbrt(expN(X)) -> expN(x/3)
2587 // * cbrt(sqrt(x)) -> pow(x,1/6)
2588 // * cbrt(sqrt(x)) -> pow(x,1/9)
2591 // * cos(-x) -> cos(x)
2594 // * exp(log(x)) -> x
2597 // * log(exp(x)) -> x
2598 // * log(x**y) -> y*log(x)
2599 // * log(exp(y)) -> y*log(e)
2600 // * log(exp2(y)) -> y*log(2)
2601 // * log(exp10(y)) -> y*log(10)
2602 // * log(sqrt(x)) -> 0.5*log(x)
2603 // * log(pow(x,y)) -> y*log(x)
2605 // lround, lroundf, lroundl:
2606 // * lround(cnst) -> cnst'
2609 // * pow(exp(x),y) -> exp(x*y)
2610 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2611 // * pow(pow(x,y),z)-> pow(x,y*z)
2614 // * puts("") -> putchar("\n")
2616 // round, roundf, roundl:
2617 // * round(cnst) -> cnst'
2620 // * signbit(cnst) -> cnst'
2621 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2623 // sqrt, sqrtf, sqrtl:
2624 // * sqrt(expN(x)) -> expN(x*0.5)
2625 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2626 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2629 // * stpcpy(str, "literal") ->
2630 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2632 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2633 // (if c is a constant integer and s is a constant string)
2634 // * strrchr(s1,0) -> strchr(s1,0)
2637 // * strpbrk(s,a) -> offset_in_for(s,a)
2638 // (if s and a are both constant strings)
2639 // * strpbrk(s,"") -> 0
2640 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2643 // * strspn(s,a) -> const_int (if both args are constant)
2644 // * strspn("",a) -> 0
2645 // * strspn(s,"") -> 0
2646 // * strcspn(s,a) -> const_int (if both args are constant)
2647 // * strcspn("",a) -> 0
2648 // * strcspn(s,"") -> strlen(a)
2651 // * strstr(x,x) -> x
2652 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2653 // (if s1 and s2 are constant strings)
2656 // * tan(atan(x)) -> x
2658 // trunc, truncf, truncl:
2659 // * trunc(cnst) -> cnst'