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 /// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
85 /// specified pointer arguments.
86 Value *EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B);
88 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
89 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
90 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
91 unsigned Align, IRBuilder<> &B);
93 /// EmitMemMove - Emit a call to the memmove function to the builder. This
94 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
95 Value *EmitMemMove(Value *Dst, Value *Src, Value *Len,
96 unsigned Align, IRBuilder<> &B);
98 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
99 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
100 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
102 /// EmitMemCmp - Emit a call to the memcmp function.
103 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
105 /// EmitMemSet - Emit a call to the memset function
106 Value *EmitMemSet(Value *Dst, Value *Val, Value *Len, IRBuilder<> &B);
108 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name'
109 /// (e.g. 'floor'). This function is known to take a single of type matching
110 /// 'Op' and returns one value with the same type. If 'Op' is a long double,
111 /// 'l' is added as the suffix of name, if 'Op' is a float, we add a 'f'
113 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B,
114 const AttrListPtr &Attrs);
116 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
118 Value *EmitPutChar(Value *Char, IRBuilder<> &B);
120 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
122 void EmitPutS(Value *Str, IRBuilder<> &B);
124 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
125 /// an i32, and File is a pointer to FILE.
126 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
128 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
129 /// pointer and File is a pointer to FILE.
130 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
132 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
133 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
134 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
137 } // End anonymous namespace.
139 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
140 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
141 return B.CreateBitCast(V, Type::getInt8PtrTy(*Context), "cstr");
144 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
145 /// specified pointer. This always returns an integer value of size intptr_t.
146 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
147 Module *M = Caller->getParent();
148 AttributeWithIndex AWI[2];
149 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
150 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
151 Attribute::NoUnwind);
153 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
154 TD->getIntPtrType(*Context),
155 Type::getInt8PtrTy(*Context),
157 CallInst *CI = B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
158 if (const Function *F = dyn_cast<Function>(StrLen->stripPointerCasts()))
159 CI->setCallingConv(F->getCallingConv());
164 /// EmitStrChr - Emit a call to the strchr function to the builder, for the
165 /// specified pointer and character. Ptr is required to be some pointer type,
166 /// and the return value has 'i8*' type.
167 Value *LibCallOptimization::EmitStrChr(Value *Ptr, char C, IRBuilder<> &B) {
168 Module *M = Caller->getParent();
169 AttributeWithIndex AWI =
170 AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
172 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
173 const Type *I32Ty = Type::getInt32Ty(*Context);
174 Constant *StrChr = M->getOrInsertFunction("strchr", AttrListPtr::get(&AWI, 1),
175 I8Ptr, I8Ptr, I32Ty, NULL);
176 CallInst *CI = B.CreateCall2(StrChr, CastToCStr(Ptr, B),
177 ConstantInt::get(I32Ty, C), "strchr");
178 if (const Function *F = dyn_cast<Function>(StrChr->stripPointerCasts()))
179 CI->setCallingConv(F->getCallingConv());
183 /// EmitStrCpy - Emit a call to the strcpy function to the builder, for the
184 /// specified pointer arguments.
185 Value *LibCallOptimization::EmitStrCpy(Value *Dst, Value *Src, IRBuilder<> &B) {
186 Module *M = Caller->getParent();
187 AttributeWithIndex AWI[2];
188 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
189 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
190 const Type *I8Ptr = Type::getInt8PtrTy(*Context);
191 Value *StrCpy = M->getOrInsertFunction("strcpy", AttrListPtr::get(AWI, 2),
192 I8Ptr, I8Ptr, I8Ptr, NULL);
193 CallInst *CI = B.CreateCall2(StrCpy, CastToCStr(Dst, B), CastToCStr(Src, B),
198 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
199 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
200 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
201 unsigned Align, IRBuilder<> &B) {
202 Module *M = Caller->getParent();
203 const Type *Ty = Len->getType();
204 Value *MemCpy = Intrinsic::getDeclaration(M, Intrinsic::memcpy, &Ty, 1);
205 Dst = CastToCStr(Dst, B);
206 Src = CastToCStr(Src, B);
207 return B.CreateCall4(MemCpy, Dst, Src, Len,
208 ConstantInt::get(Type::getInt32Ty(*Context), Align));
211 /// EmitMemMove - Emit a call to the memmove function to the builder. This
212 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
213 Value *LibCallOptimization::EmitMemMove(Value *Dst, Value *Src, Value *Len,
214 unsigned Align, IRBuilder<> &B) {
215 Module *M = Caller->getParent();
216 const Type *Ty = TD->getIntPtrType(*Context);
217 Value *MemMove = Intrinsic::getDeclaration(M, Intrinsic::memmove, &Ty, 1);
218 Dst = CastToCStr(Dst, B);
219 Src = CastToCStr(Src, B);
220 Value *A = ConstantInt::get(Type::getInt32Ty(*Context), Align);
221 return B.CreateCall4(MemMove, Dst, Src, Len, A);
224 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
225 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
226 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
227 Value *Len, IRBuilder<> &B) {
228 Module *M = Caller->getParent();
229 AttributeWithIndex AWI;
230 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
232 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
233 Type::getInt8PtrTy(*Context),
234 Type::getInt8PtrTy(*Context),
235 Type::getInt32Ty(*Context),
236 TD->getIntPtrType(*Context),
238 CallInst *CI = B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
240 if (const Function *F = dyn_cast<Function>(MemChr->stripPointerCasts()))
241 CI->setCallingConv(F->getCallingConv());
246 /// EmitMemCmp - Emit a call to the memcmp function.
247 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
248 Value *Len, IRBuilder<> &B) {
249 Module *M = Caller->getParent();
250 AttributeWithIndex AWI[3];
251 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
252 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
253 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
254 Attribute::NoUnwind);
256 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
257 Type::getInt32Ty(*Context),
258 Type::getInt8PtrTy(*Context),
259 Type::getInt8PtrTy(*Context),
260 TD->getIntPtrType(*Context), NULL);
261 CallInst *CI = B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
264 if (const Function *F = dyn_cast<Function>(MemCmp->stripPointerCasts()))
265 CI->setCallingConv(F->getCallingConv());
270 /// EmitMemSet - Emit a call to the memset function
271 Value *LibCallOptimization::EmitMemSet(Value *Dst, Value *Val,
272 Value *Len, IRBuilder<> &B) {
273 Module *M = Caller->getParent();
274 Intrinsic::ID IID = Intrinsic::memset;
276 Tys[0] = Len->getType();
277 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
278 Value *Align = ConstantInt::get(Type::getInt32Ty(*Context), 1);
279 return B.CreateCall4(MemSet, CastToCStr(Dst, B), Val, Len, Align);
282 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
283 /// 'floor'). This function is known to take a single of type matching 'Op' and
284 /// returns one value with the same type. If 'Op' is a long double, 'l' is
285 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
286 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
288 const AttrListPtr &Attrs) {
290 if (!Op->getType()->isDoubleTy()) {
291 // If we need to add a suffix, copy into NameBuffer.
292 unsigned NameLen = strlen(Name);
293 assert(NameLen < sizeof(NameBuffer)-2);
294 memcpy(NameBuffer, Name, NameLen);
295 if (Op->getType()->isFloatTy())
296 NameBuffer[NameLen] = 'f'; // floorf
298 NameBuffer[NameLen] = 'l'; // floorl
299 NameBuffer[NameLen+1] = 0;
303 Module *M = Caller->getParent();
304 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
305 Op->getType(), NULL);
306 CallInst *CI = B.CreateCall(Callee, Op, Name);
307 CI->setAttributes(Attrs);
308 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
309 CI->setCallingConv(F->getCallingConv());
314 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
316 Value *LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
317 Module *M = Caller->getParent();
318 Value *PutChar = M->getOrInsertFunction("putchar", Type::getInt32Ty(*Context),
319 Type::getInt32Ty(*Context), NULL);
320 CallInst *CI = B.CreateCall(PutChar,
321 B.CreateIntCast(Char,
322 Type::getInt32Ty(*Context),
327 if (const Function *F = dyn_cast<Function>(PutChar->stripPointerCasts()))
328 CI->setCallingConv(F->getCallingConv());
332 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
334 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
335 Module *M = Caller->getParent();
336 AttributeWithIndex AWI[2];
337 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
338 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
340 Value *PutS = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
341 Type::getInt32Ty(*Context),
342 Type::getInt8PtrTy(*Context),
344 CallInst *CI = B.CreateCall(PutS, CastToCStr(Str, B), "puts");
345 if (const Function *F = dyn_cast<Function>(PutS->stripPointerCasts()))
346 CI->setCallingConv(F->getCallingConv());
350 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
351 /// an integer and File is a pointer to FILE.
352 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
353 Module *M = Caller->getParent();
354 AttributeWithIndex AWI[2];
355 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
356 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
358 if (isa<PointerType>(File->getType()))
359 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2),
360 Type::getInt32Ty(*Context),
361 Type::getInt32Ty(*Context), File->getType(),
364 F = M->getOrInsertFunction("fputc",
365 Type::getInt32Ty(*Context),
366 Type::getInt32Ty(*Context),
367 File->getType(), NULL);
368 Char = B.CreateIntCast(Char, Type::getInt32Ty(*Context), /*isSigned*/true,
370 CallInst *CI = B.CreateCall2(F, Char, File, "fputc");
372 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
373 CI->setCallingConv(Fn->getCallingConv());
376 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
377 /// pointer and File is a pointer to FILE.
378 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
379 Module *M = Caller->getParent();
380 AttributeWithIndex AWI[3];
381 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
382 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
383 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
385 if (isa<PointerType>(File->getType()))
386 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 3),
387 Type::getInt32Ty(*Context),
388 Type::getInt8PtrTy(*Context),
389 File->getType(), NULL);
391 F = M->getOrInsertFunction("fputs", Type::getInt32Ty(*Context),
392 Type::getInt8PtrTy(*Context),
393 File->getType(), NULL);
394 CallInst *CI = B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
396 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
397 CI->setCallingConv(Fn->getCallingConv());
400 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
401 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
402 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
404 Module *M = Caller->getParent();
405 AttributeWithIndex AWI[3];
406 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
407 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
408 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
410 if (isa<PointerType>(File->getType()))
411 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
412 TD->getIntPtrType(*Context),
413 Type::getInt8PtrTy(*Context),
414 TD->getIntPtrType(*Context),
415 TD->getIntPtrType(*Context),
416 File->getType(), NULL);
418 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(*Context),
419 Type::getInt8PtrTy(*Context),
420 TD->getIntPtrType(*Context),
421 TD->getIntPtrType(*Context),
422 File->getType(), NULL);
423 CallInst *CI = B.CreateCall4(F, CastToCStr(Ptr, B), Size,
424 ConstantInt::get(TD->getIntPtrType(*Context), 1), File);
426 if (const Function *Fn = dyn_cast<Function>(F->stripPointerCasts()))
427 CI->setCallingConv(Fn->getCallingConv());
430 //===----------------------------------------------------------------------===//
432 //===----------------------------------------------------------------------===//
434 /// GetStringLengthH - If we can compute the length of the string pointed to by
435 /// the specified pointer, return 'len+1'. If we can't, return 0.
436 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
437 // Look through noop bitcast instructions.
438 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
439 return GetStringLengthH(BCI->getOperand(0), PHIs);
441 // If this is a PHI node, there are two cases: either we have already seen it
443 if (PHINode *PN = dyn_cast<PHINode>(V)) {
444 if (!PHIs.insert(PN))
445 return ~0ULL; // already in the set.
447 // If it was new, see if all the input strings are the same length.
448 uint64_t LenSoFar = ~0ULL;
449 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
450 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
451 if (Len == 0) return 0; // Unknown length -> unknown.
453 if (Len == ~0ULL) continue;
455 if (Len != LenSoFar && LenSoFar != ~0ULL)
456 return 0; // Disagree -> unknown.
460 // Success, all agree.
464 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
465 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
466 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
467 if (Len1 == 0) return 0;
468 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
469 if (Len2 == 0) return 0;
470 if (Len1 == ~0ULL) return Len2;
471 if (Len2 == ~0ULL) return Len1;
472 if (Len1 != Len2) return 0;
476 // If the value is not a GEP instruction nor a constant expression with a
477 // GEP instruction, then return unknown.
479 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
481 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
482 if (CE->getOpcode() != Instruction::GetElementPtr)
489 // Make sure the GEP has exactly three arguments.
490 if (GEP->getNumOperands() != 3)
493 // Check to make sure that the first operand of the GEP is an integer and
494 // has value 0 so that we are sure we're indexing into the initializer.
495 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
501 // If the second index isn't a ConstantInt, then this is a variable index
502 // into the array. If this occurs, we can't say anything meaningful about
504 uint64_t StartIdx = 0;
505 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
506 StartIdx = CI->getZExtValue();
510 // The GEP instruction, constant or instruction, must reference a global
511 // variable that is a constant and is initialized. The referenced constant
512 // initializer is the array that we'll use for optimization.
513 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
514 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
515 GV->mayBeOverridden())
517 Constant *GlobalInit = GV->getInitializer();
519 // Handle the ConstantAggregateZero case, which is a degenerate case. The
520 // initializer is constant zero so the length of the string must be zero.
521 if (isa<ConstantAggregateZero>(GlobalInit))
522 return 1; // Len = 0 offset by 1.
524 // Must be a Constant Array
525 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
526 if (!Array || !Array->getType()->getElementType()->isInteger(8))
529 // Get the number of elements in the array
530 uint64_t NumElts = Array->getType()->getNumElements();
532 // Traverse the constant array from StartIdx (derived above) which is
533 // the place the GEP refers to in the array.
534 for (unsigned i = StartIdx; i != NumElts; ++i) {
535 Constant *Elt = Array->getOperand(i);
536 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
537 if (!CI) // This array isn't suitable, non-int initializer.
540 return i-StartIdx+1; // We found end of string, success!
543 return 0; // The array isn't null terminated, conservatively return 'unknown'.
546 /// GetStringLength - If we can compute the length of the string pointed to by
547 /// the specified pointer, return 'len+1'. If we can't, return 0.
548 static uint64_t GetStringLength(Value *V) {
549 if (!isa<PointerType>(V->getType())) return 0;
551 SmallPtrSet<PHINode*, 32> PHIs;
552 uint64_t Len = GetStringLengthH(V, PHIs);
553 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
554 // an empty string as a length.
555 return Len == ~0ULL ? 1 : Len;
558 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
559 /// value is equal or not-equal to zero.
560 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
561 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
563 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
564 if (IC->isEquality())
565 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
566 if (C->isNullValue())
568 // Unknown instruction.
574 //===----------------------------------------------------------------------===//
575 // String and Memory LibCall Optimizations
576 //===----------------------------------------------------------------------===//
578 //===---------------------------------------===//
579 // 'strcat' Optimizations
581 struct StrCatOpt : public LibCallOptimization {
582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
583 // Verify the "strcat" function prototype.
584 const FunctionType *FT = Callee->getFunctionType();
585 if (FT->getNumParams() != 2 ||
586 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
587 FT->getParamType(0) != FT->getReturnType() ||
588 FT->getParamType(1) != FT->getReturnType())
591 // Extract some information from the instruction
592 Value *Dst = CI->getOperand(1);
593 Value *Src = CI->getOperand(2);
595 // See if we can get the length of the input string.
596 uint64_t Len = GetStringLength(Src);
597 if (Len == 0) return 0;
598 --Len; // Unbias length.
600 // Handle the simple, do-nothing case: strcat(x, "") -> x
604 // These optimizations require TargetData.
607 EmitStrLenMemCpy(Src, Dst, Len, B);
611 void EmitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len, IRBuilder<> &B) {
612 // We need to find the end of the destination string. That's where the
613 // memory is to be moved to. We just generate a call to strlen.
614 Value *DstLen = EmitStrLen(Dst, B);
616 // Now that we have the destination's length, we must index into the
617 // destination's pointer to get the actual memcpy destination (end of
618 // the string .. we're concatenating).
619 Value *CpyDst = B.CreateGEP(Dst, DstLen, "endptr");
621 // We have enough information to now generate the memcpy call to do the
622 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
623 EmitMemCpy(CpyDst, Src,
624 ConstantInt::get(TD->getIntPtrType(*Context), Len+1), 1, B);
628 //===---------------------------------------===//
629 // 'strncat' Optimizations
631 struct StrNCatOpt : public StrCatOpt {
632 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
633 // Verify the "strncat" function prototype.
634 const FunctionType *FT = Callee->getFunctionType();
635 if (FT->getNumParams() != 3 ||
636 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
637 FT->getParamType(0) != FT->getReturnType() ||
638 FT->getParamType(1) != FT->getReturnType() ||
639 !isa<IntegerType>(FT->getParamType(2)))
642 // Extract some information from the instruction
643 Value *Dst = CI->getOperand(1);
644 Value *Src = CI->getOperand(2);
647 // We don't do anything if length is not constant
648 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
649 Len = LengthArg->getZExtValue();
653 // See if we can get the length of the input string.
654 uint64_t SrcLen = GetStringLength(Src);
655 if (SrcLen == 0) return 0;
656 --SrcLen; // Unbias length.
658 // Handle the simple, do-nothing cases:
659 // strncat(x, "", c) -> x
660 // strncat(x, c, 0) -> x
661 if (SrcLen == 0 || Len == 0) return Dst;
663 // These optimizations require TargetData.
666 // We don't optimize this case
667 if (Len < SrcLen) return 0;
669 // strncat(x, s, c) -> strcat(x, s)
670 // s is constant so the strcat can be optimized further
671 EmitStrLenMemCpy(Src, Dst, SrcLen, B);
676 //===---------------------------------------===//
677 // 'strchr' Optimizations
679 struct StrChrOpt : public LibCallOptimization {
680 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
681 // Verify the "strchr" function prototype.
682 const FunctionType *FT = Callee->getFunctionType();
683 if (FT->getNumParams() != 2 ||
684 FT->getReturnType() != Type::getInt8PtrTy(*Context) ||
685 FT->getParamType(0) != FT->getReturnType())
688 Value *SrcStr = CI->getOperand(1);
690 // If the second operand is non-constant, see if we can compute the length
691 // of the input string and turn this into memchr.
692 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
694 // These optimizations require TargetData.
697 uint64_t Len = GetStringLength(SrcStr);
698 if (Len == 0 || !FT->getParamType(1)->isInteger(32)) // memchr needs i32.
701 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
702 ConstantInt::get(TD->getIntPtrType(*Context), Len), B);
705 // Otherwise, the character is a constant, see if the first argument is
706 // a string literal. If so, we can constant fold.
708 if (!GetConstantStringInfo(SrcStr, Str))
711 // strchr can find the nul character.
713 char CharValue = CharC->getSExtValue();
715 // Compute the offset.
718 if (i == Str.size()) // Didn't find the char. strchr returns null.
719 return Constant::getNullValue(CI->getType());
720 // Did we find our match?
721 if (Str[i] == CharValue)
726 // strchr(s+n,c) -> gep(s+n+i,c)
727 Value *Idx = ConstantInt::get(Type::getInt64Ty(*Context), i);
728 return B.CreateGEP(SrcStr, Idx, "strchr");
732 //===---------------------------------------===//
733 // 'strcmp' Optimizations
735 struct StrCmpOpt : public LibCallOptimization {
736 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
737 // Verify the "strcmp" function prototype.
738 const FunctionType *FT = Callee->getFunctionType();
739 if (FT->getNumParams() != 2 ||
740 !FT->getReturnType()->isInteger(32) ||
741 FT->getParamType(0) != FT->getParamType(1) ||
742 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
745 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
746 if (Str1P == Str2P) // strcmp(x,x) -> 0
747 return ConstantInt::get(CI->getType(), 0);
749 std::string Str1, Str2;
750 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
751 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
753 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
754 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
756 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
757 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
759 // strcmp(x, y) -> cnst (if both x and y are constant strings)
760 if (HasStr1 && HasStr2)
761 return ConstantInt::get(CI->getType(),
762 strcmp(Str1.c_str(),Str2.c_str()));
764 // strcmp(P, "x") -> memcmp(P, "x", 2)
765 uint64_t Len1 = GetStringLength(Str1P);
766 uint64_t Len2 = GetStringLength(Str2P);
768 // These optimizations require TargetData.
771 return EmitMemCmp(Str1P, Str2P,
772 ConstantInt::get(TD->getIntPtrType(*Context),
773 std::min(Len1, Len2)), B);
780 //===---------------------------------------===//
781 // 'strncmp' Optimizations
783 struct StrNCmpOpt : public LibCallOptimization {
784 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
785 // Verify the "strncmp" function prototype.
786 const FunctionType *FT = Callee->getFunctionType();
787 if (FT->getNumParams() != 3 ||
788 !FT->getReturnType()->isInteger(32) ||
789 FT->getParamType(0) != FT->getParamType(1) ||
790 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
791 !isa<IntegerType>(FT->getParamType(2)))
794 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
795 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
796 return ConstantInt::get(CI->getType(), 0);
798 // Get the length argument if it is constant.
800 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
801 Length = LengthArg->getZExtValue();
805 if (Length == 0) // strncmp(x,y,0) -> 0
806 return ConstantInt::get(CI->getType(), 0);
808 std::string Str1, Str2;
809 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
810 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
812 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
813 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
815 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
816 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
818 // strncmp(x, y) -> cnst (if both x and y are constant strings)
819 if (HasStr1 && HasStr2)
820 return ConstantInt::get(CI->getType(),
821 strncmp(Str1.c_str(), Str2.c_str(), Length));
827 //===---------------------------------------===//
828 // 'strcpy' Optimizations
830 struct StrCpyOpt : public LibCallOptimization {
831 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
832 // Verify the "strcpy" function prototype.
833 const FunctionType *FT = Callee->getFunctionType();
834 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
835 FT->getParamType(0) != FT->getParamType(1) ||
836 FT->getParamType(0) != Type::getInt8PtrTy(*Context))
839 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
840 if (Dst == Src) // strcpy(x,x) -> x
843 // These optimizations require TargetData.
846 // See if we can get the length of the input string.
847 uint64_t Len = GetStringLength(Src);
848 if (Len == 0) return 0;
850 // We have enough information to now generate the memcpy call to do the
851 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
853 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
858 //===---------------------------------------===//
859 // 'strncpy' Optimizations
861 struct StrNCpyOpt : public LibCallOptimization {
862 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
863 const FunctionType *FT = Callee->getFunctionType();
864 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
865 FT->getParamType(0) != FT->getParamType(1) ||
866 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
867 !isa<IntegerType>(FT->getParamType(2)))
870 Value *Dst = CI->getOperand(1);
871 Value *Src = CI->getOperand(2);
872 Value *LenOp = CI->getOperand(3);
874 // See if we can get the length of the input string.
875 uint64_t SrcLen = GetStringLength(Src);
876 if (SrcLen == 0) return 0;
880 // strncpy(x, "", y) -> memset(x, '\0', y, 1)
881 EmitMemSet(Dst, ConstantInt::get(Type::getInt8Ty(*Context), '\0'), LenOp,
887 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
888 Len = LengthArg->getZExtValue();
892 if (Len == 0) return Dst; // strncpy(x, y, 0) -> x
894 // These optimizations require TargetData.
897 // Let strncpy handle the zero padding
898 if (Len > SrcLen+1) return 0;
900 // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
902 ConstantInt::get(TD->getIntPtrType(*Context), Len), 1, B);
908 //===---------------------------------------===//
909 // 'strlen' Optimizations
911 struct StrLenOpt : public LibCallOptimization {
912 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
913 const FunctionType *FT = Callee->getFunctionType();
914 if (FT->getNumParams() != 1 ||
915 FT->getParamType(0) != Type::getInt8PtrTy(*Context) ||
916 !isa<IntegerType>(FT->getReturnType()))
919 Value *Src = CI->getOperand(1);
921 // Constant folding: strlen("xyz") -> 3
922 if (uint64_t Len = GetStringLength(Src))
923 return ConstantInt::get(CI->getType(), Len-1);
925 // strlen(x) != 0 --> *x != 0
926 // strlen(x) == 0 --> *x == 0
927 if (IsOnlyUsedInZeroEqualityComparison(CI))
928 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
933 //===---------------------------------------===//
934 // 'strto*' Optimizations. This handles strtol, strtod, strtof, strtoul, etc.
936 struct StrToOpt : public LibCallOptimization {
937 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
938 const FunctionType *FT = Callee->getFunctionType();
939 if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
940 !isa<PointerType>(FT->getParamType(0)) ||
941 !isa<PointerType>(FT->getParamType(1)))
944 Value *EndPtr = CI->getOperand(2);
945 if (isa<ConstantPointerNull>(EndPtr)) {
946 CI->setOnlyReadsMemory();
947 CI->addAttribute(1, Attribute::NoCapture);
954 //===---------------------------------------===//
955 // 'strstr' Optimizations
957 struct StrStrOpt : public LibCallOptimization {
958 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
959 const FunctionType *FT = Callee->getFunctionType();
960 if (FT->getNumParams() != 2 ||
961 !isa<PointerType>(FT->getParamType(0)) ||
962 !isa<PointerType>(FT->getParamType(1)) ||
963 !isa<PointerType>(FT->getReturnType()))
966 // fold strstr(x, x) -> x.
967 if (CI->getOperand(1) == CI->getOperand(2))
968 return B.CreateBitCast(CI->getOperand(1), CI->getType());
970 // See if either input string is a constant string.
971 std::string SearchStr, ToFindStr;
972 bool HasStr1 = GetConstantStringInfo(CI->getOperand(1), SearchStr);
973 bool HasStr2 = GetConstantStringInfo(CI->getOperand(2), ToFindStr);
975 // fold strstr(x, "") -> x.
976 if (HasStr2 && ToFindStr.empty())
977 return B.CreateBitCast(CI->getOperand(1), CI->getType());
979 // If both strings are known, constant fold it.
980 if (HasStr1 && HasStr2) {
981 std::string::size_type Offset = SearchStr.find(ToFindStr);
983 if (Offset == std::string::npos) // strstr("foo", "bar") -> null
984 return Constant::getNullValue(CI->getType());
986 // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
987 Value *Result = CastToCStr(CI->getOperand(1), B);
988 Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
989 return B.CreateBitCast(Result, CI->getType());
992 // fold strstr(x, "y") -> strchr(x, 'y').
993 if (HasStr2 && ToFindStr.size() == 1)
994 return B.CreateBitCast(EmitStrChr(CI->getOperand(1), ToFindStr[0], B),
1001 //===---------------------------------------===//
1002 // 'memcmp' Optimizations
1004 struct MemCmpOpt : public LibCallOptimization {
1005 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1006 const FunctionType *FT = Callee->getFunctionType();
1007 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
1008 !isa<PointerType>(FT->getParamType(1)) ||
1009 !FT->getReturnType()->isInteger(32))
1012 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
1014 if (LHS == RHS) // memcmp(s,s,x) -> 0
1015 return Constant::getNullValue(CI->getType());
1017 // Make sure we have a constant length.
1018 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
1019 if (!LenC) return 0;
1020 uint64_t Len = LenC->getZExtValue();
1022 if (Len == 0) // memcmp(s1,s2,0) -> 0
1023 return Constant::getNullValue(CI->getType());
1025 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
1026 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
1027 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
1028 return B.CreateSExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
1031 // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
1032 std::string LHSStr, RHSStr;
1033 if (GetConstantStringInfo(LHS, LHSStr) &&
1034 GetConstantStringInfo(RHS, RHSStr)) {
1035 // Make sure we're not reading out-of-bounds memory.
1036 if (Len > LHSStr.length() || Len > RHSStr.length())
1038 uint64_t Ret = memcmp(LHSStr.data(), RHSStr.data(), Len);
1039 return ConstantInt::get(CI->getType(), Ret);
1046 //===---------------------------------------===//
1047 // 'memcpy' Optimizations
1049 struct MemCpyOpt : public LibCallOptimization {
1050 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1051 // These optimizations require TargetData.
1054 const FunctionType *FT = Callee->getFunctionType();
1055 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1056 !isa<PointerType>(FT->getParamType(0)) ||
1057 !isa<PointerType>(FT->getParamType(1)) ||
1058 FT->getParamType(2) != TD->getIntPtrType(*Context))
1061 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
1062 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1063 return CI->getOperand(1);
1067 //===---------------------------------------===//
1068 // 'memmove' Optimizations
1070 struct MemMoveOpt : public LibCallOptimization {
1071 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1072 // These optimizations require TargetData.
1075 const FunctionType *FT = Callee->getFunctionType();
1076 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1077 !isa<PointerType>(FT->getParamType(0)) ||
1078 !isa<PointerType>(FT->getParamType(1)) ||
1079 FT->getParamType(2) != TD->getIntPtrType(*Context))
1082 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
1083 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1084 return CI->getOperand(1);
1088 //===---------------------------------------===//
1089 // 'memset' Optimizations
1091 struct MemSetOpt : public LibCallOptimization {
1092 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1093 // These optimizations require TargetData.
1096 const FunctionType *FT = Callee->getFunctionType();
1097 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1098 !isa<PointerType>(FT->getParamType(0)) ||
1099 !isa<IntegerType>(FT->getParamType(1)) ||
1100 FT->getParamType(2) != TD->getIntPtrType(*Context))
1103 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
1104 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1106 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1107 return CI->getOperand(1);
1111 //===----------------------------------------------------------------------===//
1112 // Object Size Checking Optimizations
1113 //===----------------------------------------------------------------------===//
1115 //===---------------------------------------===//
1116 // 'memcpy_chk' Optimizations
1118 struct MemCpyChkOpt : public LibCallOptimization {
1119 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1120 // These optimizations require TargetData.
1123 const FunctionType *FT = Callee->getFunctionType();
1124 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1125 !isa<PointerType>(FT->getParamType(0)) ||
1126 !isa<PointerType>(FT->getParamType(1)) ||
1127 !isa<IntegerType>(FT->getParamType(3)) ||
1128 FT->getParamType(2) != TD->getIntPtrType(*Context))
1131 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1134 if (SizeCI->isAllOnesValue()) {
1135 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
1136 return CI->getOperand(1);
1143 //===---------------------------------------===//
1144 // 'memset_chk' Optimizations
1146 struct MemSetChkOpt : public LibCallOptimization {
1147 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1148 // These optimizations require TargetData.
1151 const FunctionType *FT = Callee->getFunctionType();
1152 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1153 !isa<PointerType>(FT->getParamType(0)) ||
1154 !isa<IntegerType>(FT->getParamType(1)) ||
1155 !isa<IntegerType>(FT->getParamType(3)) ||
1156 FT->getParamType(2) != TD->getIntPtrType(*Context))
1159 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1162 if (SizeCI->isAllOnesValue()) {
1163 Value *Val = B.CreateIntCast(CI->getOperand(2), Type::getInt8Ty(*Context),
1165 EmitMemSet(CI->getOperand(1), Val, CI->getOperand(3), B);
1166 return CI->getOperand(1);
1173 //===---------------------------------------===//
1174 // 'memmove_chk' Optimizations
1176 struct MemMoveChkOpt : public LibCallOptimization {
1177 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1178 // These optimizations require TargetData.
1181 const FunctionType *FT = Callee->getFunctionType();
1182 if (FT->getNumParams() != 4 || FT->getReturnType() != FT->getParamType(0) ||
1183 !isa<PointerType>(FT->getParamType(0)) ||
1184 !isa<PointerType>(FT->getParamType(1)) ||
1185 !isa<IntegerType>(FT->getParamType(3)) ||
1186 FT->getParamType(2) != TD->getIntPtrType(*Context))
1189 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(4));
1192 if (SizeCI->isAllOnesValue()) {
1193 EmitMemMove(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3),
1195 return CI->getOperand(1);
1202 struct StrCpyChkOpt : public LibCallOptimization {
1203 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1204 // These optimizations require TargetData.
1207 const FunctionType *FT = Callee->getFunctionType();
1208 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
1209 !isa<PointerType>(FT->getParamType(0)) ||
1210 !isa<PointerType>(FT->getParamType(1)) ||
1211 !isa<IntegerType>(FT->getParamType(2)))
1214 ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getOperand(3));
1218 // We don't have any length information, just lower to a plain strcpy.
1219 if (SizeCI->isAllOnesValue())
1220 return EmitStrCpy(CI->getOperand(1), CI->getOperand(2), B);
1227 //===----------------------------------------------------------------------===//
1228 // Math Library Optimizations
1229 //===----------------------------------------------------------------------===//
1231 //===---------------------------------------===//
1232 // 'pow*' Optimizations
1234 struct PowOpt : public LibCallOptimization {
1235 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1236 const FunctionType *FT = Callee->getFunctionType();
1237 // Just make sure this has 2 arguments of the same FP type, which match the
1239 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
1240 FT->getParamType(0) != FT->getParamType(1) ||
1241 !FT->getParamType(0)->isFloatingPoint())
1244 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
1245 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
1246 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
1248 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
1249 return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
1252 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
1253 if (Op2C == 0) return 0;
1255 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
1256 return ConstantFP::get(CI->getType(), 1.0);
1258 if (Op2C->isExactlyValue(0.5)) {
1259 // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
1260 // This is faster than calling pow, and still handles negative zero
1261 // and negative infinite correctly.
1262 // TODO: In fast-math mode, this could be just sqrt(x).
1263 // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
1264 Value *Inf = ConstantFP::getInfinity(CI->getType());
1265 Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
1266 Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B,
1267 Callee->getAttributes());
1268 Value *FAbs = EmitUnaryFloatFnCall(Sqrt, "fabs", B,
1269 Callee->getAttributes());
1270 Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf, "tmp");
1271 Value *Sel = B.CreateSelect(FCmp, Inf, FAbs, "tmp");
1275 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
1277 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
1278 return B.CreateFMul(Op1, Op1, "pow2");
1279 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
1280 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0),
1286 //===---------------------------------------===//
1287 // 'exp2' Optimizations
1289 struct Exp2Opt : public LibCallOptimization {
1290 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1291 const FunctionType *FT = Callee->getFunctionType();
1292 // Just make sure this has 1 argument of FP type, which matches the
1294 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1295 !FT->getParamType(0)->isFloatingPoint())
1298 Value *Op = CI->getOperand(1);
1299 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
1300 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
1301 Value *LdExpArg = 0;
1302 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
1303 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
1304 LdExpArg = B.CreateSExt(OpC->getOperand(0),
1305 Type::getInt32Ty(*Context), "tmp");
1306 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
1307 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
1308 LdExpArg = B.CreateZExt(OpC->getOperand(0),
1309 Type::getInt32Ty(*Context), "tmp");
1314 if (Op->getType()->isFloatTy())
1316 else if (Op->getType()->isDoubleTy())
1321 Constant *One = ConstantFP::get(*Context, APFloat(1.0f));
1322 if (!Op->getType()->isFloatTy())
1323 One = ConstantExpr::getFPExtend(One, Op->getType());
1325 Module *M = Caller->getParent();
1326 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
1328 Type::getInt32Ty(*Context),NULL);
1329 CallInst *CI = B.CreateCall2(Callee, One, LdExpArg);
1330 if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
1331 CI->setCallingConv(F->getCallingConv());
1339 //===---------------------------------------===//
1340 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
1342 struct UnaryDoubleFPOpt : public LibCallOptimization {
1343 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1344 const FunctionType *FT = Callee->getFunctionType();
1345 if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
1346 !FT->getParamType(0)->isDoubleTy())
1349 // If this is something like 'floor((double)floatval)', convert to floorf.
1350 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
1351 if (Cast == 0 || !Cast->getOperand(0)->getType()->isFloatTy())
1354 // floor((double)floatval) -> (double)floorf(floatval)
1355 Value *V = Cast->getOperand(0);
1356 V = EmitUnaryFloatFnCall(V, Callee->getName().data(), B,
1357 Callee->getAttributes());
1358 return B.CreateFPExt(V, Type::getDoubleTy(*Context));
1362 //===----------------------------------------------------------------------===//
1363 // Integer Optimizations
1364 //===----------------------------------------------------------------------===//
1366 //===---------------------------------------===//
1367 // 'ffs*' Optimizations
1369 struct FFSOpt : public LibCallOptimization {
1370 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1371 const FunctionType *FT = Callee->getFunctionType();
1372 // Just make sure this has 2 arguments of the same FP type, which match the
1374 if (FT->getNumParams() != 1 ||
1375 !FT->getReturnType()->isInteger(32) ||
1376 !isa<IntegerType>(FT->getParamType(0)))
1379 Value *Op = CI->getOperand(1);
1382 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
1383 if (CI->getValue() == 0) // ffs(0) -> 0.
1384 return Constant::getNullValue(CI->getType());
1385 return ConstantInt::get(Type::getInt32Ty(*Context), // ffs(c) -> cttz(c)+1
1386 CI->getValue().countTrailingZeros()+1);
1389 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
1390 const Type *ArgType = Op->getType();
1391 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
1392 Intrinsic::cttz, &ArgType, 1);
1393 Value *V = B.CreateCall(F, Op, "cttz");
1394 V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1), "tmp");
1395 V = B.CreateIntCast(V, Type::getInt32Ty(*Context), false, "tmp");
1397 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1398 return B.CreateSelect(Cond, V,
1399 ConstantInt::get(Type::getInt32Ty(*Context), 0));
1403 //===---------------------------------------===//
1404 // 'isdigit' Optimizations
1406 struct IsDigitOpt : public LibCallOptimization {
1407 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1408 const FunctionType *FT = Callee->getFunctionType();
1409 // We require integer(i32)
1410 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1411 !FT->getParamType(0)->isInteger(32))
1414 // isdigit(c) -> (c-'0') <u 10
1415 Value *Op = CI->getOperand(1);
1416 Op = B.CreateSub(Op, ConstantInt::get(Type::getInt32Ty(*Context), '0'),
1418 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 10),
1420 return B.CreateZExt(Op, CI->getType());
1424 //===---------------------------------------===//
1425 // 'isascii' Optimizations
1427 struct IsAsciiOpt : public LibCallOptimization {
1428 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1429 const FunctionType *FT = Callee->getFunctionType();
1430 // We require integer(i32)
1431 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1432 !FT->getParamType(0)->isInteger(32))
1435 // isascii(c) -> c <u 128
1436 Value *Op = CI->getOperand(1);
1437 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::getInt32Ty(*Context), 128),
1439 return B.CreateZExt(Op, CI->getType());
1443 //===---------------------------------------===//
1444 // 'abs', 'labs', 'llabs' Optimizations
1446 struct AbsOpt : public LibCallOptimization {
1447 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1448 const FunctionType *FT = Callee->getFunctionType();
1449 // We require integer(integer) where the types agree.
1450 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1451 FT->getParamType(0) != FT->getReturnType())
1454 // abs(x) -> x >s -1 ? x : -x
1455 Value *Op = CI->getOperand(1);
1456 Value *Pos = B.CreateICmpSGT(Op,
1457 Constant::getAllOnesValue(Op->getType()),
1459 Value *Neg = B.CreateNeg(Op, "neg");
1460 return B.CreateSelect(Pos, Op, Neg);
1465 //===---------------------------------------===//
1466 // 'toascii' Optimizations
1468 struct ToAsciiOpt : public LibCallOptimization {
1469 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1470 const FunctionType *FT = Callee->getFunctionType();
1471 // We require i32(i32)
1472 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1473 !FT->getParamType(0)->isInteger(32))
1476 // isascii(c) -> c & 0x7f
1477 return B.CreateAnd(CI->getOperand(1),
1478 ConstantInt::get(CI->getType(),0x7F));
1482 //===----------------------------------------------------------------------===//
1483 // Formatting and IO Optimizations
1484 //===----------------------------------------------------------------------===//
1486 //===---------------------------------------===//
1487 // 'printf' Optimizations
1489 struct PrintFOpt : public LibCallOptimization {
1490 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1491 // Require one fixed pointer argument and an integer/void result.
1492 const FunctionType *FT = Callee->getFunctionType();
1493 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1494 !(isa<IntegerType>(FT->getReturnType()) ||
1495 FT->getReturnType()->isVoidTy()))
1498 // Check for a fixed format string.
1499 std::string FormatStr;
1500 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1503 // Empty format string -> noop.
1504 if (FormatStr.empty()) // Tolerate printf's declared void.
1505 return CI->use_empty() ? (Value*)CI :
1506 ConstantInt::get(CI->getType(), 0);
1508 // printf("x") -> putchar('x'), even for '%'. Return the result of putchar
1509 // in case there is an error writing to stdout.
1510 if (FormatStr.size() == 1) {
1511 Value *Res = EmitPutChar(ConstantInt::get(Type::getInt32Ty(*Context),
1513 if (CI->use_empty()) return CI;
1514 return B.CreateIntCast(Res, CI->getType(), true);
1517 // printf("foo\n") --> puts("foo")
1518 if (FormatStr[FormatStr.size()-1] == '\n' &&
1519 FormatStr.find('%') == std::string::npos) { // no format characters.
1520 // Create a string literal with no \n on it. We expect the constant merge
1521 // pass to be run after this pass, to merge duplicate strings.
1522 FormatStr.erase(FormatStr.end()-1);
1523 Constant *C = ConstantArray::get(*Context, FormatStr, true);
1524 C = new GlobalVariable(*Callee->getParent(), C->getType(), true,
1525 GlobalVariable::InternalLinkage, C, "str");
1527 return CI->use_empty() ? (Value*)CI :
1528 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1531 // Optimize specific format strings.
1532 // printf("%c", chr) --> putchar(*(i8*)dst)
1533 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1534 isa<IntegerType>(CI->getOperand(2)->getType())) {
1535 Value *Res = EmitPutChar(CI->getOperand(2), B);
1537 if (CI->use_empty()) return CI;
1538 return B.CreateIntCast(Res, CI->getType(), true);
1541 // printf("%s\n", str) --> puts(str)
1542 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1543 isa<PointerType>(CI->getOperand(2)->getType()) &&
1545 EmitPutS(CI->getOperand(2), B);
1552 //===---------------------------------------===//
1553 // 'sprintf' Optimizations
1555 struct SPrintFOpt : public LibCallOptimization {
1556 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1557 // Require two fixed pointer arguments and an integer result.
1558 const FunctionType *FT = Callee->getFunctionType();
1559 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1560 !isa<PointerType>(FT->getParamType(1)) ||
1561 !isa<IntegerType>(FT->getReturnType()))
1564 // Check for a fixed format string.
1565 std::string FormatStr;
1566 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1569 // If we just have a format string (nothing else crazy) transform it.
1570 if (CI->getNumOperands() == 3) {
1571 // Make sure there's no % in the constant array. We could try to handle
1572 // %% -> % in the future if we cared.
1573 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1574 if (FormatStr[i] == '%')
1575 return 0; // we found a format specifier, bail out.
1577 // These optimizations require TargetData.
1580 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1581 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1583 (TD->getIntPtrType(*Context), FormatStr.size()+1),1,B);
1584 return ConstantInt::get(CI->getType(), FormatStr.size());
1587 // The remaining optimizations require the format string to be "%s" or "%c"
1588 // and have an extra operand.
1589 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1592 // Decode the second character of the format string.
1593 if (FormatStr[1] == 'c') {
1594 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1595 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1596 Value *V = B.CreateTrunc(CI->getOperand(3),
1597 Type::getInt8Ty(*Context), "char");
1598 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1599 B.CreateStore(V, Ptr);
1600 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::getInt32Ty(*Context), 1),
1602 B.CreateStore(Constant::getNullValue(Type::getInt8Ty(*Context)), Ptr);
1604 return ConstantInt::get(CI->getType(), 1);
1607 if (FormatStr[1] == 's') {
1608 // These optimizations require TargetData.
1611 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1612 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1614 Value *Len = EmitStrLen(CI->getOperand(3), B);
1615 Value *IncLen = B.CreateAdd(Len,
1616 ConstantInt::get(Len->getType(), 1),
1618 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1620 // The sprintf result is the unincremented number of bytes in the string.
1621 return B.CreateIntCast(Len, CI->getType(), false);
1627 //===---------------------------------------===//
1628 // 'fwrite' Optimizations
1630 struct FWriteOpt : public LibCallOptimization {
1631 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1632 // Require a pointer, an integer, an integer, a pointer, returning integer.
1633 const FunctionType *FT = Callee->getFunctionType();
1634 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1635 !isa<IntegerType>(FT->getParamType(1)) ||
1636 !isa<IntegerType>(FT->getParamType(2)) ||
1637 !isa<PointerType>(FT->getParamType(3)) ||
1638 !isa<IntegerType>(FT->getReturnType()))
1641 // Get the element size and count.
1642 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1643 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1644 if (!SizeC || !CountC) return 0;
1645 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1647 // If this is writing zero records, remove the call (it's a noop).
1649 return ConstantInt::get(CI->getType(), 0);
1651 // If this is writing one byte, turn it into fputc.
1652 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1653 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1654 EmitFPutC(Char, CI->getOperand(4), B);
1655 return ConstantInt::get(CI->getType(), 1);
1662 //===---------------------------------------===//
1663 // 'fputs' Optimizations
1665 struct FPutsOpt : public LibCallOptimization {
1666 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1667 // These optimizations require TargetData.
1670 // Require two pointers. Also, we can't optimize if return value is used.
1671 const FunctionType *FT = Callee->getFunctionType();
1672 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1673 !isa<PointerType>(FT->getParamType(1)) ||
1677 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1678 uint64_t Len = GetStringLength(CI->getOperand(1));
1680 EmitFWrite(CI->getOperand(1),
1681 ConstantInt::get(TD->getIntPtrType(*Context), Len-1),
1682 CI->getOperand(2), B);
1683 return CI; // Known to have no uses (see above).
1687 //===---------------------------------------===//
1688 // 'fprintf' Optimizations
1690 struct FPrintFOpt : public LibCallOptimization {
1691 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1692 // Require two fixed paramters as pointers and integer result.
1693 const FunctionType *FT = Callee->getFunctionType();
1694 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1695 !isa<PointerType>(FT->getParamType(1)) ||
1696 !isa<IntegerType>(FT->getReturnType()))
1699 // All the optimizations depend on the format string.
1700 std::string FormatStr;
1701 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1704 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1705 if (CI->getNumOperands() == 3) {
1706 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1707 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1708 return 0; // We found a format specifier.
1710 // These optimizations require TargetData.
1713 EmitFWrite(CI->getOperand(2),
1714 ConstantInt::get(TD->getIntPtrType(*Context),
1716 CI->getOperand(1), B);
1717 return ConstantInt::get(CI->getType(), FormatStr.size());
1720 // The remaining optimizations require the format string to be "%s" or "%c"
1721 // and have an extra operand.
1722 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1725 // Decode the second character of the format string.
1726 if (FormatStr[1] == 'c') {
1727 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1728 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1729 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1730 return ConstantInt::get(CI->getType(), 1);
1733 if (FormatStr[1] == 's') {
1734 // fprintf(F, "%s", str) -> fputs(str, F)
1735 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1737 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1744 } // end anonymous namespace.
1746 //===----------------------------------------------------------------------===//
1747 // SimplifyLibCalls Pass Implementation
1748 //===----------------------------------------------------------------------===//
1751 /// This pass optimizes well known library functions from libc and libm.
1753 class SimplifyLibCalls : public FunctionPass {
1754 StringMap<LibCallOptimization*> Optimizations;
1755 // String and Memory LibCall Optimizations
1756 StrCatOpt StrCat; StrNCatOpt StrNCat; StrChrOpt StrChr; StrCmpOpt StrCmp;
1757 StrNCmpOpt StrNCmp; StrCpyOpt StrCpy; StrNCpyOpt StrNCpy; StrLenOpt StrLen;
1758 StrToOpt StrTo; StrStrOpt StrStr;
1759 MemCmpOpt MemCmp; MemCpyOpt MemCpy; MemMoveOpt MemMove; MemSetOpt MemSet;
1760 // Math Library Optimizations
1761 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1762 // Integer Optimizations
1763 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1765 // Formatting and IO Optimizations
1766 SPrintFOpt SPrintF; PrintFOpt PrintF;
1767 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1769 // Object Size Checking
1770 MemCpyChkOpt MemCpyChk; MemSetChkOpt MemSetChk; MemMoveChkOpt MemMoveChk;
1771 StrCpyChkOpt StrCpyChk;
1773 bool Modified; // This is only used by doInitialization.
1775 static char ID; // Pass identification
1776 SimplifyLibCalls() : FunctionPass(&ID) {}
1778 void InitOptimizations();
1779 bool runOnFunction(Function &F);
1781 void setDoesNotAccessMemory(Function &F);
1782 void setOnlyReadsMemory(Function &F);
1783 void setDoesNotThrow(Function &F);
1784 void setDoesNotCapture(Function &F, unsigned n);
1785 void setDoesNotAlias(Function &F, unsigned n);
1786 bool doInitialization(Module &M);
1788 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1791 char SimplifyLibCalls::ID = 0;
1792 } // end anonymous namespace.
1794 static RegisterPass<SimplifyLibCalls>
1795 X("simplify-libcalls", "Simplify well-known library calls");
1797 // Public interface to the Simplify LibCalls pass.
1798 FunctionPass *llvm::createSimplifyLibCallsPass() {
1799 return new SimplifyLibCalls();
1802 /// Optimizations - Populate the Optimizations map with all the optimizations
1804 void SimplifyLibCalls::InitOptimizations() {
1805 // String and Memory LibCall Optimizations
1806 Optimizations["strcat"] = &StrCat;
1807 Optimizations["strncat"] = &StrNCat;
1808 Optimizations["strchr"] = &StrChr;
1809 Optimizations["strcmp"] = &StrCmp;
1810 Optimizations["strncmp"] = &StrNCmp;
1811 Optimizations["strcpy"] = &StrCpy;
1812 Optimizations["strncpy"] = &StrNCpy;
1813 Optimizations["strlen"] = &StrLen;
1814 Optimizations["strtol"] = &StrTo;
1815 Optimizations["strtod"] = &StrTo;
1816 Optimizations["strtof"] = &StrTo;
1817 Optimizations["strtoul"] = &StrTo;
1818 Optimizations["strtoll"] = &StrTo;
1819 Optimizations["strtold"] = &StrTo;
1820 Optimizations["strtoull"] = &StrTo;
1821 Optimizations["strstr"] = &StrStr;
1822 Optimizations["memcmp"] = &MemCmp;
1823 Optimizations["memcpy"] = &MemCpy;
1824 Optimizations["memmove"] = &MemMove;
1825 Optimizations["memset"] = &MemSet;
1827 // Math Library Optimizations
1828 Optimizations["powf"] = &Pow;
1829 Optimizations["pow"] = &Pow;
1830 Optimizations["powl"] = &Pow;
1831 Optimizations["llvm.pow.f32"] = &Pow;
1832 Optimizations["llvm.pow.f64"] = &Pow;
1833 Optimizations["llvm.pow.f80"] = &Pow;
1834 Optimizations["llvm.pow.f128"] = &Pow;
1835 Optimizations["llvm.pow.ppcf128"] = &Pow;
1836 Optimizations["exp2l"] = &Exp2;
1837 Optimizations["exp2"] = &Exp2;
1838 Optimizations["exp2f"] = &Exp2;
1839 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1840 Optimizations["llvm.exp2.f128"] = &Exp2;
1841 Optimizations["llvm.exp2.f80"] = &Exp2;
1842 Optimizations["llvm.exp2.f64"] = &Exp2;
1843 Optimizations["llvm.exp2.f32"] = &Exp2;
1846 Optimizations["floor"] = &UnaryDoubleFP;
1849 Optimizations["ceil"] = &UnaryDoubleFP;
1852 Optimizations["round"] = &UnaryDoubleFP;
1855 Optimizations["rint"] = &UnaryDoubleFP;
1857 #ifdef HAVE_NEARBYINTF
1858 Optimizations["nearbyint"] = &UnaryDoubleFP;
1861 // Integer Optimizations
1862 Optimizations["ffs"] = &FFS;
1863 Optimizations["ffsl"] = &FFS;
1864 Optimizations["ffsll"] = &FFS;
1865 Optimizations["abs"] = &Abs;
1866 Optimizations["labs"] = &Abs;
1867 Optimizations["llabs"] = &Abs;
1868 Optimizations["isdigit"] = &IsDigit;
1869 Optimizations["isascii"] = &IsAscii;
1870 Optimizations["toascii"] = &ToAscii;
1872 // Formatting and IO Optimizations
1873 Optimizations["sprintf"] = &SPrintF;
1874 Optimizations["printf"] = &PrintF;
1875 Optimizations["fwrite"] = &FWrite;
1876 Optimizations["fputs"] = &FPuts;
1877 Optimizations["fprintf"] = &FPrintF;
1879 // Object Size Checking
1880 Optimizations["__memcpy_chk"] = &MemCpyChk;
1881 Optimizations["__memset_chk"] = &MemSetChk;
1882 Optimizations["__memmove_chk"] = &MemMoveChk;
1883 Optimizations["__strcpy_chk"] = &StrCpyChk;
1887 /// runOnFunction - Top level algorithm.
1889 bool SimplifyLibCalls::runOnFunction(Function &F) {
1890 if (Optimizations.empty())
1891 InitOptimizations();
1893 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
1895 IRBuilder<> Builder(F.getContext());
1897 bool Changed = false;
1898 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1899 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1900 // Ignore non-calls.
1901 CallInst *CI = dyn_cast<CallInst>(I++);
1904 // Ignore indirect calls and calls to non-external functions.
1905 Function *Callee = CI->getCalledFunction();
1906 if (Callee == 0 || !Callee->isDeclaration() ||
1907 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1910 // Ignore unknown calls.
1911 LibCallOptimization *LCO = Optimizations.lookup(Callee->getName());
1914 // Set the builder to the instruction after the call.
1915 Builder.SetInsertPoint(BB, I);
1917 // Try to optimize this call.
1918 Value *Result = LCO->OptimizeCall(CI, TD, Builder);
1919 if (Result == 0) continue;
1921 DEBUG(dbgs() << "SimplifyLibCalls simplified: " << *CI;
1922 dbgs() << " into: " << *Result << "\n");
1924 // Something changed!
1928 // Inspect the instruction after the call (which was potentially just
1932 if (CI != Result && !CI->use_empty()) {
1933 CI->replaceAllUsesWith(Result);
1934 if (!Result->hasName())
1935 Result->takeName(CI);
1937 CI->eraseFromParent();
1943 // Utility methods for doInitialization.
1945 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1946 if (!F.doesNotAccessMemory()) {
1947 F.setDoesNotAccessMemory();
1952 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1953 if (!F.onlyReadsMemory()) {
1954 F.setOnlyReadsMemory();
1959 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1960 if (!F.doesNotThrow()) {
1961 F.setDoesNotThrow();
1966 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1967 if (!F.doesNotCapture(n)) {
1968 F.setDoesNotCapture(n);
1973 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1974 if (!F.doesNotAlias(n)) {
1975 F.setDoesNotAlias(n);
1981 /// doInitialization - Add attributes to well-known functions.
1983 bool SimplifyLibCalls::doInitialization(Module &M) {
1985 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1987 if (!F.isDeclaration())
1993 const FunctionType *FTy = F.getFunctionType();
1995 StringRef Name = F.getName();
1998 if (Name == "strlen") {
1999 if (FTy->getNumParams() != 1 ||
2000 !isa<PointerType>(FTy->getParamType(0)))
2002 setOnlyReadsMemory(F);
2004 setDoesNotCapture(F, 1);
2005 } else if (Name == "strcpy" ||
2011 Name == "strtoul" ||
2012 Name == "strtoll" ||
2013 Name == "strtold" ||
2014 Name == "strncat" ||
2015 Name == "strncpy" ||
2016 Name == "strtoull") {
2017 if (FTy->getNumParams() < 2 ||
2018 !isa<PointerType>(FTy->getParamType(1)))
2021 setDoesNotCapture(F, 2);
2022 } else if (Name == "strxfrm") {
2023 if (FTy->getNumParams() != 3 ||
2024 !isa<PointerType>(FTy->getParamType(0)) ||
2025 !isa<PointerType>(FTy->getParamType(1)))
2028 setDoesNotCapture(F, 1);
2029 setDoesNotCapture(F, 2);
2030 } else if (Name == "strcmp" ||
2032 Name == "strncmp" ||
2033 Name ==" strcspn" ||
2034 Name == "strcoll" ||
2035 Name == "strcasecmp" ||
2036 Name == "strncasecmp") {
2037 if (FTy->getNumParams() < 2 ||
2038 !isa<PointerType>(FTy->getParamType(0)) ||
2039 !isa<PointerType>(FTy->getParamType(1)))
2041 setOnlyReadsMemory(F);
2043 setDoesNotCapture(F, 1);
2044 setDoesNotCapture(F, 2);
2045 } else if (Name == "strstr" ||
2046 Name == "strpbrk") {
2047 if (FTy->getNumParams() != 2 ||
2048 !isa<PointerType>(FTy->getParamType(1)))
2050 setOnlyReadsMemory(F);
2052 setDoesNotCapture(F, 2);
2053 } else if (Name == "strtok" ||
2054 Name == "strtok_r") {
2055 if (FTy->getNumParams() < 2 ||
2056 !isa<PointerType>(FTy->getParamType(1)))
2059 setDoesNotCapture(F, 2);
2060 } else if (Name == "scanf" ||
2062 Name == "setvbuf") {
2063 if (FTy->getNumParams() < 1 ||
2064 !isa<PointerType>(FTy->getParamType(0)))
2067 setDoesNotCapture(F, 1);
2068 } else if (Name == "strdup" ||
2069 Name == "strndup") {
2070 if (FTy->getNumParams() < 1 ||
2071 !isa<PointerType>(FTy->getReturnType()) ||
2072 !isa<PointerType>(FTy->getParamType(0)))
2075 setDoesNotAlias(F, 0);
2076 setDoesNotCapture(F, 1);
2077 } else if (Name == "stat" ||
2079 Name == "sprintf" ||
2080 Name == "statvfs") {
2081 if (FTy->getNumParams() < 2 ||
2082 !isa<PointerType>(FTy->getParamType(0)) ||
2083 !isa<PointerType>(FTy->getParamType(1)))
2086 setDoesNotCapture(F, 1);
2087 setDoesNotCapture(F, 2);
2088 } else if (Name == "snprintf") {
2089 if (FTy->getNumParams() != 3 ||
2090 !isa<PointerType>(FTy->getParamType(0)) ||
2091 !isa<PointerType>(FTy->getParamType(2)))
2094 setDoesNotCapture(F, 1);
2095 setDoesNotCapture(F, 3);
2096 } else if (Name == "setitimer") {
2097 if (FTy->getNumParams() != 3 ||
2098 !isa<PointerType>(FTy->getParamType(1)) ||
2099 !isa<PointerType>(FTy->getParamType(2)))
2102 setDoesNotCapture(F, 2);
2103 setDoesNotCapture(F, 3);
2104 } else if (Name == "system") {
2105 if (FTy->getNumParams() != 1 ||
2106 !isa<PointerType>(FTy->getParamType(0)))
2108 // May throw; "system" is a valid pthread cancellation point.
2109 setDoesNotCapture(F, 1);
2113 if (Name == "malloc") {
2114 if (FTy->getNumParams() != 1 ||
2115 !isa<PointerType>(FTy->getReturnType()))
2118 setDoesNotAlias(F, 0);
2119 } else if (Name == "memcmp") {
2120 if (FTy->getNumParams() != 3 ||
2121 !isa<PointerType>(FTy->getParamType(0)) ||
2122 !isa<PointerType>(FTy->getParamType(1)))
2124 setOnlyReadsMemory(F);
2126 setDoesNotCapture(F, 1);
2127 setDoesNotCapture(F, 2);
2128 } else if (Name == "memchr" ||
2129 Name == "memrchr") {
2130 if (FTy->getNumParams() != 3)
2132 setOnlyReadsMemory(F);
2134 } else if (Name == "modf" ||
2138 Name == "memccpy" ||
2139 Name == "memmove") {
2140 if (FTy->getNumParams() < 2 ||
2141 !isa<PointerType>(FTy->getParamType(1)))
2144 setDoesNotCapture(F, 2);
2145 } else if (Name == "memalign") {
2146 if (!isa<PointerType>(FTy->getReturnType()))
2148 setDoesNotAlias(F, 0);
2149 } else if (Name == "mkdir" ||
2151 if (FTy->getNumParams() == 0 ||
2152 !isa<PointerType>(FTy->getParamType(0)))
2155 setDoesNotCapture(F, 1);
2159 if (Name == "realloc") {
2160 if (FTy->getNumParams() != 2 ||
2161 !isa<PointerType>(FTy->getParamType(0)) ||
2162 !isa<PointerType>(FTy->getReturnType()))
2165 setDoesNotAlias(F, 0);
2166 setDoesNotCapture(F, 1);
2167 } else if (Name == "read") {
2168 if (FTy->getNumParams() != 3 ||
2169 !isa<PointerType>(FTy->getParamType(1)))
2171 // May throw; "read" is a valid pthread cancellation point.
2172 setDoesNotCapture(F, 2);
2173 } else if (Name == "rmdir" ||
2176 Name == "realpath") {
2177 if (FTy->getNumParams() < 1 ||
2178 !isa<PointerType>(FTy->getParamType(0)))
2181 setDoesNotCapture(F, 1);
2182 } else if (Name == "rename" ||
2183 Name == "readlink") {
2184 if (FTy->getNumParams() < 2 ||
2185 !isa<PointerType>(FTy->getParamType(0)) ||
2186 !isa<PointerType>(FTy->getParamType(1)))
2189 setDoesNotCapture(F, 1);
2190 setDoesNotCapture(F, 2);
2194 if (Name == "write") {
2195 if (FTy->getNumParams() != 3 ||
2196 !isa<PointerType>(FTy->getParamType(1)))
2198 // May throw; "write" is a valid pthread cancellation point.
2199 setDoesNotCapture(F, 2);
2203 if (Name == "bcopy") {
2204 if (FTy->getNumParams() != 3 ||
2205 !isa<PointerType>(FTy->getParamType(0)) ||
2206 !isa<PointerType>(FTy->getParamType(1)))
2209 setDoesNotCapture(F, 1);
2210 setDoesNotCapture(F, 2);
2211 } else if (Name == "bcmp") {
2212 if (FTy->getNumParams() != 3 ||
2213 !isa<PointerType>(FTy->getParamType(0)) ||
2214 !isa<PointerType>(FTy->getParamType(1)))
2217 setOnlyReadsMemory(F);
2218 setDoesNotCapture(F, 1);
2219 setDoesNotCapture(F, 2);
2220 } else if (Name == "bzero") {
2221 if (FTy->getNumParams() != 2 ||
2222 !isa<PointerType>(FTy->getParamType(0)))
2225 setDoesNotCapture(F, 1);
2229 if (Name == "calloc") {
2230 if (FTy->getNumParams() != 2 ||
2231 !isa<PointerType>(FTy->getReturnType()))
2234 setDoesNotAlias(F, 0);
2235 } else if (Name == "chmod" ||
2237 Name == "ctermid" ||
2238 Name == "clearerr" ||
2239 Name == "closedir") {
2240 if (FTy->getNumParams() == 0 ||
2241 !isa<PointerType>(FTy->getParamType(0)))
2244 setDoesNotCapture(F, 1);
2248 if (Name == "atoi" ||
2252 if (FTy->getNumParams() != 1 ||
2253 !isa<PointerType>(FTy->getParamType(0)))
2256 setOnlyReadsMemory(F);
2257 setDoesNotCapture(F, 1);
2258 } else if (Name == "access") {
2259 if (FTy->getNumParams() != 2 ||
2260 !isa<PointerType>(FTy->getParamType(0)))
2263 setDoesNotCapture(F, 1);
2267 if (Name == "fopen") {
2268 if (FTy->getNumParams() != 2 ||
2269 !isa<PointerType>(FTy->getReturnType()) ||
2270 !isa<PointerType>(FTy->getParamType(0)) ||
2271 !isa<PointerType>(FTy->getParamType(1)))
2274 setDoesNotAlias(F, 0);
2275 setDoesNotCapture(F, 1);
2276 setDoesNotCapture(F, 2);
2277 } else if (Name == "fdopen") {
2278 if (FTy->getNumParams() != 2 ||
2279 !isa<PointerType>(FTy->getReturnType()) ||
2280 !isa<PointerType>(FTy->getParamType(1)))
2283 setDoesNotAlias(F, 0);
2284 setDoesNotCapture(F, 2);
2285 } else if (Name == "feof" ||
2295 Name == "fsetpos" ||
2296 Name == "flockfile" ||
2297 Name == "funlockfile" ||
2298 Name == "ftrylockfile") {
2299 if (FTy->getNumParams() == 0 ||
2300 !isa<PointerType>(FTy->getParamType(0)))
2303 setDoesNotCapture(F, 1);
2304 } else if (Name == "ferror") {
2305 if (FTy->getNumParams() != 1 ||
2306 !isa<PointerType>(FTy->getParamType(0)))
2309 setDoesNotCapture(F, 1);
2310 setOnlyReadsMemory(F);
2311 } else if (Name == "fputc" ||
2316 Name == "fstatvfs") {
2317 if (FTy->getNumParams() != 2 ||
2318 !isa<PointerType>(FTy->getParamType(1)))
2321 setDoesNotCapture(F, 2);
2322 } else if (Name == "fgets") {
2323 if (FTy->getNumParams() != 3 ||
2324 !isa<PointerType>(FTy->getParamType(0)) ||
2325 !isa<PointerType>(FTy->getParamType(2)))
2328 setDoesNotCapture(F, 3);
2329 } else if (Name == "fread" ||
2331 if (FTy->getNumParams() != 4 ||
2332 !isa<PointerType>(FTy->getParamType(0)) ||
2333 !isa<PointerType>(FTy->getParamType(3)))
2336 setDoesNotCapture(F, 1);
2337 setDoesNotCapture(F, 4);
2338 } else if (Name == "fputs" ||
2340 Name == "fprintf" ||
2341 Name == "fgetpos") {
2342 if (FTy->getNumParams() < 2 ||
2343 !isa<PointerType>(FTy->getParamType(0)) ||
2344 !isa<PointerType>(FTy->getParamType(1)))
2347 setDoesNotCapture(F, 1);
2348 setDoesNotCapture(F, 2);
2352 if (Name == "getc" ||
2353 Name == "getlogin_r" ||
2354 Name == "getc_unlocked") {
2355 if (FTy->getNumParams() == 0 ||
2356 !isa<PointerType>(FTy->getParamType(0)))
2359 setDoesNotCapture(F, 1);
2360 } else if (Name == "getenv") {
2361 if (FTy->getNumParams() != 1 ||
2362 !isa<PointerType>(FTy->getParamType(0)))
2365 setOnlyReadsMemory(F);
2366 setDoesNotCapture(F, 1);
2367 } else if (Name == "gets" ||
2368 Name == "getchar") {
2370 } else if (Name == "getitimer") {
2371 if (FTy->getNumParams() != 2 ||
2372 !isa<PointerType>(FTy->getParamType(1)))
2375 setDoesNotCapture(F, 2);
2376 } else if (Name == "getpwnam") {
2377 if (FTy->getNumParams() != 1 ||
2378 !isa<PointerType>(FTy->getParamType(0)))
2381 setDoesNotCapture(F, 1);
2385 if (Name == "ungetc") {
2386 if (FTy->getNumParams() != 2 ||
2387 !isa<PointerType>(FTy->getParamType(1)))
2390 setDoesNotCapture(F, 2);
2391 } else if (Name == "uname" ||
2393 Name == "unsetenv") {
2394 if (FTy->getNumParams() != 1 ||
2395 !isa<PointerType>(FTy->getParamType(0)))
2398 setDoesNotCapture(F, 1);
2399 } else if (Name == "utime" ||
2401 if (FTy->getNumParams() != 2 ||
2402 !isa<PointerType>(FTy->getParamType(0)) ||
2403 !isa<PointerType>(FTy->getParamType(1)))
2406 setDoesNotCapture(F, 1);
2407 setDoesNotCapture(F, 2);
2411 if (Name == "putc") {
2412 if (FTy->getNumParams() != 2 ||
2413 !isa<PointerType>(FTy->getParamType(1)))
2416 setDoesNotCapture(F, 2);
2417 } else if (Name == "puts" ||
2420 if (FTy->getNumParams() != 1 ||
2421 !isa<PointerType>(FTy->getParamType(0)))
2424 setDoesNotCapture(F, 1);
2425 } else if (Name == "pread" ||
2427 if (FTy->getNumParams() != 4 ||
2428 !isa<PointerType>(FTy->getParamType(1)))
2430 // May throw; these are valid pthread cancellation points.
2431 setDoesNotCapture(F, 2);
2432 } else if (Name == "putchar") {
2434 } else if (Name == "popen") {
2435 if (FTy->getNumParams() != 2 ||
2436 !isa<PointerType>(FTy->getReturnType()) ||
2437 !isa<PointerType>(FTy->getParamType(0)) ||
2438 !isa<PointerType>(FTy->getParamType(1)))
2441 setDoesNotAlias(F, 0);
2442 setDoesNotCapture(F, 1);
2443 setDoesNotCapture(F, 2);
2444 } else if (Name == "pclose") {
2445 if (FTy->getNumParams() != 1 ||
2446 !isa<PointerType>(FTy->getParamType(0)))
2449 setDoesNotCapture(F, 1);
2453 if (Name == "vscanf") {
2454 if (FTy->getNumParams() != 2 ||
2455 !isa<PointerType>(FTy->getParamType(1)))
2458 setDoesNotCapture(F, 1);
2459 } else if (Name == "vsscanf" ||
2460 Name == "vfscanf") {
2461 if (FTy->getNumParams() != 3 ||
2462 !isa<PointerType>(FTy->getParamType(1)) ||
2463 !isa<PointerType>(FTy->getParamType(2)))
2466 setDoesNotCapture(F, 1);
2467 setDoesNotCapture(F, 2);
2468 } else if (Name == "valloc") {
2469 if (!isa<PointerType>(FTy->getReturnType()))
2472 setDoesNotAlias(F, 0);
2473 } else if (Name == "vprintf") {
2474 if (FTy->getNumParams() != 2 ||
2475 !isa<PointerType>(FTy->getParamType(0)))
2478 setDoesNotCapture(F, 1);
2479 } else if (Name == "vfprintf" ||
2480 Name == "vsprintf") {
2481 if (FTy->getNumParams() != 3 ||
2482 !isa<PointerType>(FTy->getParamType(0)) ||
2483 !isa<PointerType>(FTy->getParamType(1)))
2486 setDoesNotCapture(F, 1);
2487 setDoesNotCapture(F, 2);
2488 } else if (Name == "vsnprintf") {
2489 if (FTy->getNumParams() != 4 ||
2490 !isa<PointerType>(FTy->getParamType(0)) ||
2491 !isa<PointerType>(FTy->getParamType(2)))
2494 setDoesNotCapture(F, 1);
2495 setDoesNotCapture(F, 3);
2499 if (Name == "open") {
2500 if (FTy->getNumParams() < 2 ||
2501 !isa<PointerType>(FTy->getParamType(0)))
2503 // May throw; "open" is a valid pthread cancellation point.
2504 setDoesNotCapture(F, 1);
2505 } else if (Name == "opendir") {
2506 if (FTy->getNumParams() != 1 ||
2507 !isa<PointerType>(FTy->getReturnType()) ||
2508 !isa<PointerType>(FTy->getParamType(0)))
2511 setDoesNotAlias(F, 0);
2512 setDoesNotCapture(F, 1);
2516 if (Name == "tmpfile") {
2517 if (!isa<PointerType>(FTy->getReturnType()))
2520 setDoesNotAlias(F, 0);
2521 } else if (Name == "times") {
2522 if (FTy->getNumParams() != 1 ||
2523 !isa<PointerType>(FTy->getParamType(0)))
2526 setDoesNotCapture(F, 1);
2530 if (Name == "htonl" ||
2533 setDoesNotAccessMemory(F);
2537 if (Name == "ntohl" ||
2540 setDoesNotAccessMemory(F);
2544 if (Name == "lstat") {
2545 if (FTy->getNumParams() != 2 ||
2546 !isa<PointerType>(FTy->getParamType(0)) ||
2547 !isa<PointerType>(FTy->getParamType(1)))
2550 setDoesNotCapture(F, 1);
2551 setDoesNotCapture(F, 2);
2552 } else if (Name == "lchown") {
2553 if (FTy->getNumParams() != 3 ||
2554 !isa<PointerType>(FTy->getParamType(0)))
2557 setDoesNotCapture(F, 1);
2561 if (Name == "qsort") {
2562 if (FTy->getNumParams() != 4 ||
2563 !isa<PointerType>(FTy->getParamType(3)))
2565 // May throw; places call through function pointer.
2566 setDoesNotCapture(F, 4);
2570 if (Name == "__strdup" ||
2571 Name == "__strndup") {
2572 if (FTy->getNumParams() < 1 ||
2573 !isa<PointerType>(FTy->getReturnType()) ||
2574 !isa<PointerType>(FTy->getParamType(0)))
2577 setDoesNotAlias(F, 0);
2578 setDoesNotCapture(F, 1);
2579 } else if (Name == "__strtok_r") {
2580 if (FTy->getNumParams() != 3 ||
2581 !isa<PointerType>(FTy->getParamType(1)))
2584 setDoesNotCapture(F, 2);
2585 } else if (Name == "_IO_getc") {
2586 if (FTy->getNumParams() != 1 ||
2587 !isa<PointerType>(FTy->getParamType(0)))
2590 setDoesNotCapture(F, 1);
2591 } else if (Name == "_IO_putc") {
2592 if (FTy->getNumParams() != 2 ||
2593 !isa<PointerType>(FTy->getParamType(1)))
2596 setDoesNotCapture(F, 2);
2600 if (Name == "\1__isoc99_scanf") {
2601 if (FTy->getNumParams() < 1 ||
2602 !isa<PointerType>(FTy->getParamType(0)))
2605 setDoesNotCapture(F, 1);
2606 } else if (Name == "\1stat64" ||
2607 Name == "\1lstat64" ||
2608 Name == "\1statvfs64" ||
2609 Name == "\1__isoc99_sscanf") {
2610 if (FTy->getNumParams() < 1 ||
2611 !isa<PointerType>(FTy->getParamType(0)) ||
2612 !isa<PointerType>(FTy->getParamType(1)))
2615 setDoesNotCapture(F, 1);
2616 setDoesNotCapture(F, 2);
2617 } else if (Name == "\1fopen64") {
2618 if (FTy->getNumParams() != 2 ||
2619 !isa<PointerType>(FTy->getReturnType()) ||
2620 !isa<PointerType>(FTy->getParamType(0)) ||
2621 !isa<PointerType>(FTy->getParamType(1)))
2624 setDoesNotAlias(F, 0);
2625 setDoesNotCapture(F, 1);
2626 setDoesNotCapture(F, 2);
2627 } else if (Name == "\1fseeko64" ||
2628 Name == "\1ftello64") {
2629 if (FTy->getNumParams() == 0 ||
2630 !isa<PointerType>(FTy->getParamType(0)))
2633 setDoesNotCapture(F, 1);
2634 } else if (Name == "\1tmpfile64") {
2635 if (!isa<PointerType>(FTy->getReturnType()))
2638 setDoesNotAlias(F, 0);
2639 } else if (Name == "\1fstat64" ||
2640 Name == "\1fstatvfs64") {
2641 if (FTy->getNumParams() != 2 ||
2642 !isa<PointerType>(FTy->getParamType(1)))
2645 setDoesNotCapture(F, 2);
2646 } else if (Name == "\1open64") {
2647 if (FTy->getNumParams() < 2 ||
2648 !isa<PointerType>(FTy->getParamType(0)))
2650 // May throw; "open" is a valid pthread cancellation point.
2651 setDoesNotCapture(F, 1);
2660 // Additional cases that we need to add to this file:
2663 // * cbrt(expN(X)) -> expN(x/3)
2664 // * cbrt(sqrt(x)) -> pow(x,1/6)
2665 // * cbrt(sqrt(x)) -> pow(x,1/9)
2668 // * cos(-x) -> cos(x)
2671 // * exp(log(x)) -> x
2674 // * log(exp(x)) -> x
2675 // * log(x**y) -> y*log(x)
2676 // * log(exp(y)) -> y*log(e)
2677 // * log(exp2(y)) -> y*log(2)
2678 // * log(exp10(y)) -> y*log(10)
2679 // * log(sqrt(x)) -> 0.5*log(x)
2680 // * log(pow(x,y)) -> y*log(x)
2682 // lround, lroundf, lroundl:
2683 // * lround(cnst) -> cnst'
2686 // * pow(exp(x),y) -> exp(x*y)
2687 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2688 // * pow(pow(x,y),z)-> pow(x,y*z)
2691 // * puts("") -> putchar("\n")
2693 // round, roundf, roundl:
2694 // * round(cnst) -> cnst'
2697 // * signbit(cnst) -> cnst'
2698 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2700 // sqrt, sqrtf, sqrtl:
2701 // * sqrt(expN(x)) -> expN(x*0.5)
2702 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2703 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2706 // * stpcpy(str, "literal") ->
2707 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2709 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2710 // (if c is a constant integer and s is a constant string)
2711 // * strrchr(s1,0) -> strchr(s1,0)
2714 // * strpbrk(s,a) -> offset_in_for(s,a)
2715 // (if s and a are both constant strings)
2716 // * strpbrk(s,"") -> 0
2717 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2720 // * strspn(s,a) -> const_int (if both args are constant)
2721 // * strspn("",a) -> 0
2722 // * strspn(s,"") -> 0
2723 // * strcspn(s,a) -> const_int (if both args are constant)
2724 // * strcspn("",a) -> 0
2725 // * strcspn(s,"") -> strlen(a)
2728 // * tan(atan(x)) -> x
2730 // trunc, truncf, truncl:
2731 // * trunc(cnst) -> cnst'