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). For example, a call to the function "exit(3)" that
13 // occurs within the main() function can be transformed into a simple "return 3"
14 // instruction. Any optimization that takes this form (replace call to library
15 // function with simpler code that provides the same result) belongs in this
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "simplify-libcalls"
21 #include "llvm/Transforms/Scalar.h"
22 #include "llvm/Intrinsics.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Support/IRBuilder.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/ADT/SmallPtrSet.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/Support/Compiler.h"
32 #include "llvm/Support/Debug.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 VISIBILITY_HIDDEN LibCallOptimization {
51 LibCallOptimization() { }
52 virtual ~LibCallOptimization() {}
54 /// CallOptimizer - This pure virtual method is implemented by base classes to
55 /// do various optimizations. If this returns null then no transformation was
56 /// performed. If it returns CI, then it transformed the call and CI is to be
57 /// deleted. If it returns something else, replace CI with the new value and
59 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
62 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
63 Caller = CI->getParent()->getParent();
65 return CallOptimizer(CI->getCalledFunction(), CI, B);
68 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
69 Value *CastToCStr(Value *V, IRBuilder<> &B);
71 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
72 /// specified pointer. Ptr is required to be some pointer type, and the
73 /// return value has 'intptr_t' type.
74 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
76 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
77 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
78 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
79 unsigned Align, IRBuilder<> &B);
81 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
82 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
83 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
85 /// EmitMemCmp - Emit a call to the memcmp function.
86 Value *EmitMemCmp(Value *Ptr1, Value *Ptr2, Value *Len, IRBuilder<> &B);
88 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
89 /// 'floor'). This function is known to take a single of type matching 'Op'
90 /// and returns one value with the same type. If 'Op' is a long double, 'l'
91 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
92 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
94 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
96 void EmitPutChar(Value *Char, IRBuilder<> &B);
98 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
100 void EmitPutS(Value *Str, IRBuilder<> &B);
102 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
103 /// an i32, and File is a pointer to FILE.
104 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
106 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
107 /// pointer and File is a pointer to FILE.
108 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
110 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
111 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
112 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
115 } // End anonymous namespace.
117 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
118 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
119 return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
122 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
123 /// specified pointer. This always returns an integer value of size intptr_t.
124 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
125 Module *M = Caller->getParent();
126 AttributeWithIndex AWI[2];
127 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
128 AWI[1] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
129 Attribute::NoUnwind);
131 Constant *StrLen =M->getOrInsertFunction("strlen", AttrListPtr::get(AWI, 2),
133 PointerType::getUnqual(Type::Int8Ty),
135 return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
138 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
139 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
140 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
141 unsigned Align, IRBuilder<> &B) {
142 Module *M = Caller->getParent();
143 Intrinsic::ID IID = Intrinsic::memcpy;
145 Tys[0] = Len->getType();
146 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
147 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
148 ConstantInt::get(Type::Int32Ty, Align));
151 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
152 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
153 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
154 Value *Len, IRBuilder<> &B) {
155 Module *M = Caller->getParent();
156 AttributeWithIndex AWI;
157 AWI = AttributeWithIndex::get(~0u, Attribute::ReadOnly | Attribute::NoUnwind);
159 Value *MemChr = M->getOrInsertFunction("memchr", AttrListPtr::get(&AWI, 1),
160 PointerType::getUnqual(Type::Int8Ty),
161 PointerType::getUnqual(Type::Int8Ty),
162 Type::Int32Ty, TD->getIntPtrType(),
164 return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
167 /// EmitMemCmp - Emit a call to the memcmp function.
168 Value *LibCallOptimization::EmitMemCmp(Value *Ptr1, Value *Ptr2,
169 Value *Len, IRBuilder<> &B) {
170 Module *M = Caller->getParent();
171 AttributeWithIndex AWI[3];
172 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
173 AWI[1] = AttributeWithIndex::get(2, Attribute::NoCapture);
174 AWI[2] = AttributeWithIndex::get(~0u, Attribute::ReadOnly |
175 Attribute::NoUnwind);
177 Value *MemCmp = M->getOrInsertFunction("memcmp", AttrListPtr::get(AWI, 3),
179 PointerType::getUnqual(Type::Int8Ty),
180 PointerType::getUnqual(Type::Int8Ty),
181 TD->getIntPtrType(), NULL);
182 return B.CreateCall3(MemCmp, CastToCStr(Ptr1, B), CastToCStr(Ptr2, B),
186 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
187 /// 'floor'). This function is known to take a single of type matching 'Op' and
188 /// returns one value with the same type. If 'Op' is a long double, 'l' is
189 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
190 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
193 if (Op->getType() != Type::DoubleTy) {
194 // If we need to add a suffix, copy into NameBuffer.
195 unsigned NameLen = strlen(Name);
196 assert(NameLen < sizeof(NameBuffer)-2);
197 memcpy(NameBuffer, Name, NameLen);
198 if (Op->getType() == Type::FloatTy)
199 NameBuffer[NameLen] = 'f'; // floorf
201 NameBuffer[NameLen] = 'l'; // floorl
202 NameBuffer[NameLen+1] = 0;
206 Module *M = Caller->getParent();
207 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
208 Op->getType(), NULL);
209 return B.CreateCall(Callee, Op, Name);
212 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
214 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
215 Module *M = Caller->getParent();
216 Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
217 Type::Int32Ty, NULL);
218 B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
221 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
223 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
224 Module *M = Caller->getParent();
225 AttributeWithIndex AWI[2];
226 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
227 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
229 Value *F = M->getOrInsertFunction("puts", AttrListPtr::get(AWI, 2),
231 PointerType::getUnqual(Type::Int8Ty), NULL);
232 B.CreateCall(F, CastToCStr(Str, B), "puts");
235 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
236 /// an integer and File is a pointer to FILE.
237 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
238 Module *M = Caller->getParent();
239 AttributeWithIndex AWI[2];
240 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
241 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
243 if (isa<PointerType>(File->getType()))
244 F = M->getOrInsertFunction("fputc", AttrListPtr::get(AWI, 2), Type::Int32Ty,
245 Type::Int32Ty, File->getType(), NULL);
248 F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
249 File->getType(), NULL);
250 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
251 B.CreateCall2(F, Char, File, "fputc");
254 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
255 /// pointer and File is a pointer to FILE.
256 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
257 Module *M = Caller->getParent();
258 AttributeWithIndex AWI[2];
259 AWI[0] = AttributeWithIndex::get(2, Attribute::NoCapture);
260 AWI[1] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
262 if (isa<PointerType>(File->getType()))
263 F = M->getOrInsertFunction("fputs", AttrListPtr::get(AWI, 2), Type::Int32Ty,
264 PointerType::getUnqual(Type::Int8Ty),
265 File->getType(), NULL);
267 F = M->getOrInsertFunction("fputs", Type::Int32Ty,
268 PointerType::getUnqual(Type::Int8Ty),
269 File->getType(), NULL);
270 B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
273 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
274 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
275 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
277 Module *M = Caller->getParent();
278 AttributeWithIndex AWI[3];
279 AWI[0] = AttributeWithIndex::get(1, Attribute::NoCapture);
280 AWI[1] = AttributeWithIndex::get(4, Attribute::NoCapture);
281 AWI[2] = AttributeWithIndex::get(~0u, Attribute::NoUnwind);
283 if (isa<PointerType>(File->getType()))
284 F = M->getOrInsertFunction("fwrite", AttrListPtr::get(AWI, 3),
286 PointerType::getUnqual(Type::Int8Ty),
287 TD->getIntPtrType(), TD->getIntPtrType(),
288 File->getType(), NULL);
290 F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
291 PointerType::getUnqual(Type::Int8Ty),
292 TD->getIntPtrType(), TD->getIntPtrType(),
293 File->getType(), NULL);
294 B.CreateCall4(F, CastToCStr(Ptr, B), Size,
295 ConstantInt::get(TD->getIntPtrType(), 1), File);
298 //===----------------------------------------------------------------------===//
300 //===----------------------------------------------------------------------===//
302 /// GetStringLengthH - If we can compute the length of the string pointed to by
303 /// the specified pointer, return 'len+1'. If we can't, return 0.
304 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
305 // Look through noop bitcast instructions.
306 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
307 return GetStringLengthH(BCI->getOperand(0), PHIs);
309 // If this is a PHI node, there are two cases: either we have already seen it
311 if (PHINode *PN = dyn_cast<PHINode>(V)) {
312 if (!PHIs.insert(PN))
313 return ~0ULL; // already in the set.
315 // If it was new, see if all the input strings are the same length.
316 uint64_t LenSoFar = ~0ULL;
317 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
318 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
319 if (Len == 0) return 0; // Unknown length -> unknown.
321 if (Len == ~0ULL) continue;
323 if (Len != LenSoFar && LenSoFar != ~0ULL)
324 return 0; // Disagree -> unknown.
328 // Success, all agree.
332 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
333 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
334 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
335 if (Len1 == 0) return 0;
336 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
337 if (Len2 == 0) return 0;
338 if (Len1 == ~0ULL) return Len2;
339 if (Len2 == ~0ULL) return Len1;
340 if (Len1 != Len2) return 0;
344 // If the value is not a GEP instruction nor a constant expression with a
345 // GEP instruction, then return unknown.
347 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
349 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
350 if (CE->getOpcode() != Instruction::GetElementPtr)
357 // Make sure the GEP has exactly three arguments.
358 if (GEP->getNumOperands() != 3)
361 // Check to make sure that the first operand of the GEP is an integer and
362 // has value 0 so that we are sure we're indexing into the initializer.
363 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
369 // If the second index isn't a ConstantInt, then this is a variable index
370 // into the array. If this occurs, we can't say anything meaningful about
372 uint64_t StartIdx = 0;
373 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
374 StartIdx = CI->getZExtValue();
378 // The GEP instruction, constant or instruction, must reference a global
379 // variable that is a constant and is initialized. The referenced constant
380 // initializer is the array that we'll use for optimization.
381 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
382 if (!GV || !GV->isConstant() || !GV->hasInitializer())
384 Constant *GlobalInit = GV->getInitializer();
386 // Handle the ConstantAggregateZero case, which is a degenerate case. The
387 // initializer is constant zero so the length of the string must be zero.
388 if (isa<ConstantAggregateZero>(GlobalInit))
389 return 1; // Len = 0 offset by 1.
391 // Must be a Constant Array
392 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
393 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
396 // Get the number of elements in the array
397 uint64_t NumElts = Array->getType()->getNumElements();
399 // Traverse the constant array from StartIdx (derived above) which is
400 // the place the GEP refers to in the array.
401 for (unsigned i = StartIdx; i != NumElts; ++i) {
402 Constant *Elt = Array->getOperand(i);
403 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
404 if (!CI) // This array isn't suitable, non-int initializer.
407 return i-StartIdx+1; // We found end of string, success!
410 return 0; // The array isn't null terminated, conservatively return 'unknown'.
413 /// GetStringLength - If we can compute the length of the string pointed to by
414 /// the specified pointer, return 'len+1'. If we can't, return 0.
415 static uint64_t GetStringLength(Value *V) {
416 if (!isa<PointerType>(V->getType())) return 0;
418 SmallPtrSet<PHINode*, 32> PHIs;
419 uint64_t Len = GetStringLengthH(V, PHIs);
420 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
421 // an empty string as a length.
422 return Len == ~0ULL ? 1 : Len;
425 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
426 /// value is equal or not-equal to zero.
427 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
428 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
430 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
431 if (IC->isEquality())
432 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
433 if (C->isNullValue())
435 // Unknown instruction.
441 //===----------------------------------------------------------------------===//
442 // Miscellaneous LibCall Optimizations
443 //===----------------------------------------------------------------------===//
446 //===---------------------------------------===//
447 // 'exit' Optimizations
449 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
450 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
451 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
452 // Verify we have a reasonable prototype for exit.
453 if (Callee->arg_size() == 0 || !CI->use_empty())
456 // Verify the caller is main, and that the result type of main matches the
457 // argument type of exit.
458 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
459 Caller->getReturnType() != CI->getOperand(1)->getType())
462 TerminatorInst *OldTI = CI->getParent()->getTerminator();
464 // Create the return after the call.
465 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
467 // Drop all successor phi node entries.
468 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
469 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
471 // Erase all instructions from after our return instruction until the end of
473 BasicBlock::iterator FirstDead = RI; ++FirstDead;
474 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
479 //===----------------------------------------------------------------------===//
480 // String and Memory LibCall Optimizations
481 //===----------------------------------------------------------------------===//
483 //===---------------------------------------===//
484 // 'strcat' Optimizations
486 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
487 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
488 // Verify the "strcat" function prototype.
489 const FunctionType *FT = Callee->getFunctionType();
490 if (FT->getNumParams() != 2 ||
491 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
492 FT->getParamType(0) != FT->getReturnType() ||
493 FT->getParamType(1) != FT->getReturnType())
496 // Extract some information from the instruction
497 Value *Dst = CI->getOperand(1);
498 Value *Src = CI->getOperand(2);
500 // See if we can get the length of the input string.
501 uint64_t Len = GetStringLength(Src);
502 if (Len == 0) return 0;
503 --Len; // Unbias length.
505 // Handle the simple, do-nothing case: strcat(x, "") -> x
509 // We need to find the end of the destination string. That's where the
510 // memory is to be moved to. We just generate a call to strlen.
511 Value *DstLen = EmitStrLen(Dst, B);
513 // Now that we have the destination's length, we must index into the
514 // destination's pointer to get the actual memcpy destination (end of
515 // the string .. we're concatenating).
516 Dst = B.CreateGEP(Dst, DstLen, "endptr");
518 // We have enough information to now generate the memcpy call to do the
519 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
520 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
525 //===---------------------------------------===//
526 // 'strchr' Optimizations
528 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
529 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
530 // Verify the "strchr" function prototype.
531 const FunctionType *FT = Callee->getFunctionType();
532 if (FT->getNumParams() != 2 ||
533 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
534 FT->getParamType(0) != FT->getReturnType())
537 Value *SrcStr = CI->getOperand(1);
539 // If the second operand is non-constant, see if we can compute the length
540 // of the input string and turn this into memchr.
541 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
543 uint64_t Len = GetStringLength(SrcStr);
544 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
547 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
548 ConstantInt::get(TD->getIntPtrType(), Len), B);
551 // Otherwise, the character is a constant, see if the first argument is
552 // a string literal. If so, we can constant fold.
554 if (!GetConstantStringInfo(SrcStr, Str))
557 // strchr can find the nul character.
559 char CharValue = CharC->getSExtValue();
561 // Compute the offset.
564 if (i == Str.size()) // Didn't find the char. strchr returns null.
565 return Constant::getNullValue(CI->getType());
566 // Did we find our match?
567 if (Str[i] == CharValue)
572 // strchr(s+n,c) -> gep(s+n+i,c)
573 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
574 return B.CreateGEP(SrcStr, Idx, "strchr");
578 //===---------------------------------------===//
579 // 'strcmp' Optimizations
581 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
582 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
583 // Verify the "strcmp" function prototype.
584 const FunctionType *FT = Callee->getFunctionType();
585 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
586 FT->getParamType(0) != FT->getParamType(1) ||
587 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
590 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
591 if (Str1P == Str2P) // strcmp(x,x) -> 0
592 return ConstantInt::get(CI->getType(), 0);
594 std::string Str1, Str2;
595 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
596 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
598 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
599 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
601 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
602 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
604 // strcmp(x, y) -> cnst (if both x and y are constant strings)
605 if (HasStr1 && HasStr2)
606 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
608 // strcmp(P, "x") -> memcmp(P, "x", 2)
609 uint64_t Len1 = GetStringLength(Str1P);
610 uint64_t Len2 = GetStringLength(Str2P);
612 // Choose the smallest Len excluding 0 which means 'unknown'.
613 if (!Len1 || (Len2 && Len2 < Len1))
615 return EmitMemCmp(Str1P, Str2P,
616 ConstantInt::get(TD->getIntPtrType(), Len1), B);
623 //===---------------------------------------===//
624 // 'strncmp' Optimizations
626 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
627 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
628 // Verify the "strncmp" function prototype.
629 const FunctionType *FT = Callee->getFunctionType();
630 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
631 FT->getParamType(0) != FT->getParamType(1) ||
632 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
633 !isa<IntegerType>(FT->getParamType(2)))
636 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
637 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
638 return ConstantInt::get(CI->getType(), 0);
640 // Get the length argument if it is constant.
642 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
643 Length = LengthArg->getZExtValue();
647 if (Length == 0) // strncmp(x,y,0) -> 0
648 return ConstantInt::get(CI->getType(), 0);
650 std::string Str1, Str2;
651 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
652 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
654 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
655 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
657 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
658 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
660 // strncmp(x, y) -> cnst (if both x and y are constant strings)
661 if (HasStr1 && HasStr2)
662 return ConstantInt::get(CI->getType(),
663 strncmp(Str1.c_str(), Str2.c_str(), Length));
669 //===---------------------------------------===//
670 // 'strcpy' Optimizations
672 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
673 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
674 // Verify the "strcpy" function prototype.
675 const FunctionType *FT = Callee->getFunctionType();
676 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
677 FT->getParamType(0) != FT->getParamType(1) ||
678 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
681 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
682 if (Dst == Src) // strcpy(x,x) -> x
685 // See if we can get the length of the input string.
686 uint64_t Len = GetStringLength(Src);
687 if (Len == 0) return 0;
689 // We have enough information to now generate the memcpy call to do the
690 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
691 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
698 //===---------------------------------------===//
699 // 'strlen' Optimizations
701 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
702 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
703 const FunctionType *FT = Callee->getFunctionType();
704 if (FT->getNumParams() != 1 ||
705 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
706 !isa<IntegerType>(FT->getReturnType()))
709 Value *Src = CI->getOperand(1);
711 // Constant folding: strlen("xyz") -> 3
712 if (uint64_t Len = GetStringLength(Src))
713 return ConstantInt::get(CI->getType(), Len-1);
715 // Handle strlen(p) != 0.
716 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
718 // strlen(x) != 0 --> *x != 0
719 // strlen(x) == 0 --> *x == 0
720 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
724 //===---------------------------------------===//
725 // 'memcmp' Optimizations
727 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
728 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
729 const FunctionType *FT = Callee->getFunctionType();
730 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
731 !isa<PointerType>(FT->getParamType(1)) ||
732 FT->getReturnType() != Type::Int32Ty)
735 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
737 if (LHS == RHS) // memcmp(s,s,x) -> 0
738 return Constant::getNullValue(CI->getType());
740 // Make sure we have a constant length.
741 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
743 uint64_t Len = LenC->getZExtValue();
745 if (Len == 0) // memcmp(s1,s2,0) -> 0
746 return Constant::getNullValue(CI->getType());
748 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
749 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
750 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
751 return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
754 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
755 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
756 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
757 const Type *PTy = PointerType::getUnqual(Len == 2 ?
758 Type::Int16Ty : Type::Int32Ty);
759 LHS = B.CreateBitCast(LHS, PTy, "tmp");
760 RHS = B.CreateBitCast(RHS, PTy, "tmp");
761 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
762 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
763 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
764 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
771 //===---------------------------------------===//
772 // 'memcpy' Optimizations
774 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
775 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
776 const FunctionType *FT = Callee->getFunctionType();
777 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
778 !isa<PointerType>(FT->getParamType(0)) ||
779 !isa<PointerType>(FT->getParamType(1)) ||
780 FT->getParamType(2) != TD->getIntPtrType())
783 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
784 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
785 return CI->getOperand(1);
789 //===---------------------------------------===//
790 // 'memmove' Optimizations
792 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
793 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
794 const FunctionType *FT = Callee->getFunctionType();
795 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
796 !isa<PointerType>(FT->getParamType(0)) ||
797 !isa<PointerType>(FT->getParamType(1)) ||
798 FT->getParamType(2) != TD->getIntPtrType())
801 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
802 Module *M = Caller->getParent();
803 Intrinsic::ID IID = Intrinsic::memmove;
805 Tys[0] = TD->getIntPtrType();
806 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
807 Value *Dst = CastToCStr(CI->getOperand(1), B);
808 Value *Src = CastToCStr(CI->getOperand(2), B);
809 Value *Size = CI->getOperand(3);
810 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
811 B.CreateCall4(MemMove, Dst, Src, Size, Align);
812 return CI->getOperand(1);
816 //===---------------------------------------===//
817 // 'memset' Optimizations
819 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
820 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
821 const FunctionType *FT = Callee->getFunctionType();
822 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
823 !isa<PointerType>(FT->getParamType(0)) ||
824 FT->getParamType(1) != TD->getIntPtrType() ||
825 FT->getParamType(2) != TD->getIntPtrType())
828 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
829 Module *M = Caller->getParent();
830 Intrinsic::ID IID = Intrinsic::memset;
832 Tys[0] = TD->getIntPtrType();
833 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
834 Value *Dst = CastToCStr(CI->getOperand(1), B);
835 Value *Val = B.CreateTrunc(CI->getOperand(2), Type::Int8Ty);
836 Value *Size = CI->getOperand(3);
837 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
838 B.CreateCall4(MemSet, Dst, Val, Size, Align);
839 return CI->getOperand(1);
843 //===----------------------------------------------------------------------===//
844 // Math Library Optimizations
845 //===----------------------------------------------------------------------===//
847 //===---------------------------------------===//
848 // 'pow*' Optimizations
850 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
851 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
852 const FunctionType *FT = Callee->getFunctionType();
853 // Just make sure this has 2 arguments of the same FP type, which match the
855 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
856 FT->getParamType(0) != FT->getParamType(1) ||
857 !FT->getParamType(0)->isFloatingPoint())
860 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
861 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
862 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
864 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
865 return EmitUnaryFloatFnCall(Op2, "exp2", B);
868 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
869 if (Op2C == 0) return 0;
871 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
872 return ConstantFP::get(CI->getType(), 1.0);
874 if (Op2C->isExactlyValue(0.5)) {
875 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
876 // 'unsafe' math optimizations are allowed.
877 // x pow(x, 0.5) sqrt(x)
878 // ---------------------------------------------
882 // pow(x, 0.5) -> sqrt(x)
883 return B.CreateCall(get_sqrt(), Op1, "sqrt");
887 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
889 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
890 return B.CreateMul(Op1, Op1, "pow2");
891 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
892 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
897 //===---------------------------------------===//
898 // 'exp2' Optimizations
900 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
901 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
902 const FunctionType *FT = Callee->getFunctionType();
903 // Just make sure this has 1 argument of FP type, which matches the
905 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
906 !FT->getParamType(0)->isFloatingPoint())
909 Value *Op = CI->getOperand(1);
910 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
911 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
913 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
914 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
915 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
916 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
917 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
918 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
923 if (Op->getType() == Type::FloatTy)
925 else if (Op->getType() == Type::DoubleTy)
930 Constant *One = ConstantFP::get(APFloat(1.0f));
931 if (Op->getType() != Type::FloatTy)
932 One = ConstantExpr::getFPExtend(One, Op->getType());
934 Module *M = Caller->getParent();
935 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
936 Op->getType(), Type::Int32Ty,NULL);
937 return B.CreateCall2(Callee, One, LdExpArg);
944 //===---------------------------------------===//
945 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
947 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
948 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
949 const FunctionType *FT = Callee->getFunctionType();
950 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
951 FT->getParamType(0) != Type::DoubleTy)
954 // If this is something like 'floor((double)floatval)', convert to floorf.
955 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
956 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
959 // floor((double)floatval) -> (double)floorf(floatval)
960 Value *V = Cast->getOperand(0);
961 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
962 return B.CreateFPExt(V, Type::DoubleTy);
966 //===----------------------------------------------------------------------===//
967 // Integer Optimizations
968 //===----------------------------------------------------------------------===//
970 //===---------------------------------------===//
971 // 'ffs*' Optimizations
973 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
974 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
975 const FunctionType *FT = Callee->getFunctionType();
976 // Just make sure this has 2 arguments of the same FP type, which match the
978 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
979 !isa<IntegerType>(FT->getParamType(0)))
982 Value *Op = CI->getOperand(1);
985 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
986 if (CI->getValue() == 0) // ffs(0) -> 0.
987 return Constant::getNullValue(CI->getType());
988 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
989 CI->getValue().countTrailingZeros()+1);
992 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
993 const Type *ArgType = Op->getType();
994 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
995 Intrinsic::cttz, &ArgType, 1);
996 Value *V = B.CreateCall(F, Op, "cttz");
997 V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
998 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
1000 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
1001 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
1005 //===---------------------------------------===//
1006 // 'isdigit' Optimizations
1008 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
1009 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1010 const FunctionType *FT = Callee->getFunctionType();
1011 // We require integer(i32)
1012 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1013 FT->getParamType(0) != Type::Int32Ty)
1016 // isdigit(c) -> (c-'0') <u 10
1017 Value *Op = CI->getOperand(1);
1018 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
1019 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
1020 return B.CreateZExt(Op, CI->getType());
1024 //===---------------------------------------===//
1025 // 'isascii' Optimizations
1027 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
1028 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1029 const FunctionType *FT = Callee->getFunctionType();
1030 // We require integer(i32)
1031 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1032 FT->getParamType(0) != Type::Int32Ty)
1035 // isascii(c) -> c <u 128
1036 Value *Op = CI->getOperand(1);
1037 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
1038 return B.CreateZExt(Op, CI->getType());
1042 //===---------------------------------------===//
1043 // 'abs', 'labs', 'llabs' Optimizations
1045 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
1046 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1047 const FunctionType *FT = Callee->getFunctionType();
1048 // We require integer(integer) where the types agree.
1049 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
1050 FT->getParamType(0) != FT->getReturnType())
1053 // abs(x) -> x >s -1 ? x : -x
1054 Value *Op = CI->getOperand(1);
1055 Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
1057 Value *Neg = B.CreateNeg(Op, "neg");
1058 return B.CreateSelect(Pos, Op, Neg);
1063 //===---------------------------------------===//
1064 // 'toascii' Optimizations
1066 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
1067 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1068 const FunctionType *FT = Callee->getFunctionType();
1069 // We require i32(i32)
1070 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
1071 FT->getParamType(0) != Type::Int32Ty)
1074 // isascii(c) -> c & 0x7f
1075 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
1079 //===----------------------------------------------------------------------===//
1080 // Formatting and IO Optimizations
1081 //===----------------------------------------------------------------------===//
1083 //===---------------------------------------===//
1084 // 'printf' Optimizations
1086 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1087 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1088 // Require one fixed pointer argument and an integer/void result.
1089 const FunctionType *FT = Callee->getFunctionType();
1090 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1091 !(isa<IntegerType>(FT->getReturnType()) ||
1092 FT->getReturnType() == Type::VoidTy))
1095 // Check for a fixed format string.
1096 std::string FormatStr;
1097 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1100 // Empty format string -> noop.
1101 if (FormatStr.empty()) // Tolerate printf's declared void.
1102 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
1104 // printf("x") -> putchar('x'), even for '%'.
1105 if (FormatStr.size() == 1) {
1106 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1107 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1110 // printf("foo\n") --> puts("foo")
1111 if (FormatStr[FormatStr.size()-1] == '\n' &&
1112 FormatStr.find('%') == std::string::npos) { // no format characters.
1113 // Create a string literal with no \n on it. We expect the constant merge
1114 // pass to be run after this pass, to merge duplicate strings.
1115 FormatStr.erase(FormatStr.end()-1);
1116 Constant *C = ConstantArray::get(FormatStr, true);
1117 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
1118 C, "str", Callee->getParent());
1120 return CI->use_empty() ? (Value*)CI :
1121 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1124 // Optimize specific format strings.
1125 // printf("%c", chr) --> putchar(*(i8*)dst)
1126 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1127 isa<IntegerType>(CI->getOperand(2)->getType())) {
1128 EmitPutChar(CI->getOperand(2), B);
1129 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1132 // printf("%s\n", str) --> puts(str)
1133 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1134 isa<PointerType>(CI->getOperand(2)->getType()) &&
1136 EmitPutS(CI->getOperand(2), B);
1143 //===---------------------------------------===//
1144 // 'sprintf' Optimizations
1146 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1147 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1148 // Require two fixed pointer arguments and an integer result.
1149 const FunctionType *FT = Callee->getFunctionType();
1150 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1151 !isa<PointerType>(FT->getParamType(1)) ||
1152 !isa<IntegerType>(FT->getReturnType()))
1155 // Check for a fixed format string.
1156 std::string FormatStr;
1157 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1160 // If we just have a format string (nothing else crazy) transform it.
1161 if (CI->getNumOperands() == 3) {
1162 // Make sure there's no % in the constant array. We could try to handle
1163 // %% -> % in the future if we cared.
1164 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1165 if (FormatStr[i] == '%')
1166 return 0; // we found a format specifier, bail out.
1168 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1169 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1170 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1171 return ConstantInt::get(CI->getType(), FormatStr.size());
1174 // The remaining optimizations require the format string to be "%s" or "%c"
1175 // and have an extra operand.
1176 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1179 // Decode the second character of the format string.
1180 if (FormatStr[1] == 'c') {
1181 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1182 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1183 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1184 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1185 B.CreateStore(V, Ptr);
1186 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1187 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1189 return ConstantInt::get(CI->getType(), 1);
1192 if (FormatStr[1] == 's') {
1193 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1194 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1196 Value *Len = EmitStrLen(CI->getOperand(3), B);
1197 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1199 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1201 // The sprintf result is the unincremented number of bytes in the string.
1202 return B.CreateIntCast(Len, CI->getType(), false);
1208 //===---------------------------------------===//
1209 // 'fwrite' Optimizations
1211 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1212 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1213 // Require a pointer, an integer, an integer, a pointer, returning integer.
1214 const FunctionType *FT = Callee->getFunctionType();
1215 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1216 !isa<IntegerType>(FT->getParamType(1)) ||
1217 !isa<IntegerType>(FT->getParamType(2)) ||
1218 !isa<PointerType>(FT->getParamType(3)) ||
1219 !isa<IntegerType>(FT->getReturnType()))
1222 // Get the element size and count.
1223 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1224 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1225 if (!SizeC || !CountC) return 0;
1226 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1228 // If this is writing zero records, remove the call (it's a noop).
1230 return ConstantInt::get(CI->getType(), 0);
1232 // If this is writing one byte, turn it into fputc.
1233 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1234 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1235 EmitFPutC(Char, CI->getOperand(4), B);
1236 return ConstantInt::get(CI->getType(), 1);
1243 //===---------------------------------------===//
1244 // 'fputs' Optimizations
1246 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1247 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1248 // Require two pointers. Also, we can't optimize if return value is used.
1249 const FunctionType *FT = Callee->getFunctionType();
1250 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1251 !isa<PointerType>(FT->getParamType(1)) ||
1255 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1256 uint64_t Len = GetStringLength(CI->getOperand(1));
1258 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1259 CI->getOperand(2), B);
1260 return CI; // Known to have no uses (see above).
1264 //===---------------------------------------===//
1265 // 'fprintf' Optimizations
1267 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1268 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1269 // Require two fixed paramters as pointers and integer result.
1270 const FunctionType *FT = Callee->getFunctionType();
1271 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1272 !isa<PointerType>(FT->getParamType(1)) ||
1273 !isa<IntegerType>(FT->getReturnType()))
1276 // All the optimizations depend on the format string.
1277 std::string FormatStr;
1278 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1281 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1282 if (CI->getNumOperands() == 3) {
1283 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1284 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1285 return 0; // We found a format specifier.
1287 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1289 CI->getOperand(1), B);
1290 return ConstantInt::get(CI->getType(), FormatStr.size());
1293 // The remaining optimizations require the format string to be "%s" or "%c"
1294 // and have an extra operand.
1295 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1298 // Decode the second character of the format string.
1299 if (FormatStr[1] == 'c') {
1300 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1301 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1302 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1303 return ConstantInt::get(CI->getType(), 1);
1306 if (FormatStr[1] == 's') {
1307 // fprintf(F, "%s", str) -> fputs(str, F)
1308 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1310 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1317 } // end anonymous namespace.
1319 //===----------------------------------------------------------------------===//
1320 // SimplifyLibCalls Pass Implementation
1321 //===----------------------------------------------------------------------===//
1324 /// This pass optimizes well known library functions from libc and libm.
1326 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1327 StringMap<LibCallOptimization*> Optimizations;
1328 // Miscellaneous LibCall Optimizations
1330 // String and Memory LibCall Optimizations
1331 StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1332 StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt MemCpy;
1333 MemMoveOpt MemMove; MemSetOpt MemSet;
1334 // Math Library Optimizations
1335 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1336 // Integer Optimizations
1337 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1339 // Formatting and IO Optimizations
1340 SPrintFOpt SPrintF; PrintFOpt PrintF;
1341 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1343 bool Modified; // This is only used by doInitialization.
1345 static char ID; // Pass identification
1346 SimplifyLibCalls() : FunctionPass(&ID) {}
1348 void InitOptimizations();
1349 bool runOnFunction(Function &F);
1351 void setDoesNotAccessMemory(Function &F);
1352 void setOnlyReadsMemory(Function &F);
1353 void setDoesNotThrow(Function &F);
1354 void setDoesNotCapture(Function &F, unsigned n);
1355 void setDoesNotAlias(Function &F, unsigned n);
1356 bool doInitialization(Module &M);
1358 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1359 AU.addRequired<TargetData>();
1362 char SimplifyLibCalls::ID = 0;
1363 } // end anonymous namespace.
1365 static RegisterPass<SimplifyLibCalls>
1366 X("simplify-libcalls", "Simplify well-known library calls");
1368 // Public interface to the Simplify LibCalls pass.
1369 FunctionPass *llvm::createSimplifyLibCallsPass() {
1370 return new SimplifyLibCalls();
1373 /// Optimizations - Populate the Optimizations map with all the optimizations
1375 void SimplifyLibCalls::InitOptimizations() {
1376 // Miscellaneous LibCall Optimizations
1377 Optimizations["exit"] = &Exit;
1379 // String and Memory LibCall Optimizations
1380 Optimizations["strcat"] = &StrCat;
1381 Optimizations["strchr"] = &StrChr;
1382 Optimizations["strcmp"] = &StrCmp;
1383 Optimizations["strncmp"] = &StrNCmp;
1384 Optimizations["strcpy"] = &StrCpy;
1385 Optimizations["strlen"] = &StrLen;
1386 Optimizations["memcmp"] = &MemCmp;
1387 Optimizations["memcpy"] = &MemCpy;
1388 Optimizations["memmove"] = &MemMove;
1389 Optimizations["memset"] = &MemSet;
1391 // Math Library Optimizations
1392 Optimizations["powf"] = &Pow;
1393 Optimizations["pow"] = &Pow;
1394 Optimizations["powl"] = &Pow;
1395 Optimizations["llvm.pow.f32"] = &Pow;
1396 Optimizations["llvm.pow.f64"] = &Pow;
1397 Optimizations["llvm.pow.f80"] = &Pow;
1398 Optimizations["llvm.pow.f128"] = &Pow;
1399 Optimizations["llvm.pow.ppcf128"] = &Pow;
1400 Optimizations["exp2l"] = &Exp2;
1401 Optimizations["exp2"] = &Exp2;
1402 Optimizations["exp2f"] = &Exp2;
1403 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1404 Optimizations["llvm.exp2.f128"] = &Exp2;
1405 Optimizations["llvm.exp2.f80"] = &Exp2;
1406 Optimizations["llvm.exp2.f64"] = &Exp2;
1407 Optimizations["llvm.exp2.f32"] = &Exp2;
1410 Optimizations["floor"] = &UnaryDoubleFP;
1413 Optimizations["ceil"] = &UnaryDoubleFP;
1416 Optimizations["round"] = &UnaryDoubleFP;
1419 Optimizations["rint"] = &UnaryDoubleFP;
1421 #ifdef HAVE_NEARBYINTF
1422 Optimizations["nearbyint"] = &UnaryDoubleFP;
1425 // Integer Optimizations
1426 Optimizations["ffs"] = &FFS;
1427 Optimizations["ffsl"] = &FFS;
1428 Optimizations["ffsll"] = &FFS;
1429 Optimizations["abs"] = &Abs;
1430 Optimizations["labs"] = &Abs;
1431 Optimizations["llabs"] = &Abs;
1432 Optimizations["isdigit"] = &IsDigit;
1433 Optimizations["isascii"] = &IsAscii;
1434 Optimizations["toascii"] = &ToAscii;
1436 // Formatting and IO Optimizations
1437 Optimizations["sprintf"] = &SPrintF;
1438 Optimizations["printf"] = &PrintF;
1439 Optimizations["fwrite"] = &FWrite;
1440 Optimizations["fputs"] = &FPuts;
1441 Optimizations["fprintf"] = &FPrintF;
1445 /// runOnFunction - Top level algorithm.
1447 bool SimplifyLibCalls::runOnFunction(Function &F) {
1448 if (Optimizations.empty())
1449 InitOptimizations();
1451 const TargetData &TD = getAnalysis<TargetData>();
1453 IRBuilder<> Builder;
1455 bool Changed = false;
1456 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1457 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1458 // Ignore non-calls.
1459 CallInst *CI = dyn_cast<CallInst>(I++);
1462 // Ignore indirect calls and calls to non-external functions.
1463 Function *Callee = CI->getCalledFunction();
1464 if (Callee == 0 || !Callee->isDeclaration() ||
1465 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1468 // Ignore unknown calls.
1469 const char *CalleeName = Callee->getNameStart();
1470 StringMap<LibCallOptimization*>::iterator OMI =
1471 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1472 if (OMI == Optimizations.end()) continue;
1474 // Set the builder to the instruction after the call.
1475 Builder.SetInsertPoint(BB, I);
1477 // Try to optimize this call.
1478 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1479 if (Result == 0) continue;
1481 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1482 DOUT << " into: " << *Result << "\n");
1484 // Something changed!
1488 // Inspect the instruction after the call (which was potentially just
1492 if (CI != Result && !CI->use_empty()) {
1493 CI->replaceAllUsesWith(Result);
1494 if (!Result->hasName())
1495 Result->takeName(CI);
1497 CI->eraseFromParent();
1503 // Utility methods for doInitialization.
1505 void SimplifyLibCalls::setDoesNotAccessMemory(Function &F) {
1506 if (!F.doesNotAccessMemory()) {
1507 F.setDoesNotAccessMemory();
1512 void SimplifyLibCalls::setOnlyReadsMemory(Function &F) {
1513 if (!F.onlyReadsMemory()) {
1514 F.setOnlyReadsMemory();
1519 void SimplifyLibCalls::setDoesNotThrow(Function &F) {
1520 if (!F.doesNotThrow()) {
1521 F.setDoesNotThrow();
1526 void SimplifyLibCalls::setDoesNotCapture(Function &F, unsigned n) {
1527 if (!F.doesNotCapture(n)) {
1528 F.setDoesNotCapture(n);
1533 void SimplifyLibCalls::setDoesNotAlias(Function &F, unsigned n) {
1534 if (!F.doesNotAlias(n)) {
1535 F.setDoesNotAlias(n);
1541 /// doInitialization - Add attributes to well-known functions.
1543 bool SimplifyLibCalls::doInitialization(Module &M) {
1545 for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
1547 if (!F.isDeclaration())
1550 unsigned NameLen = F.getNameLen();
1554 const FunctionType *FTy = F.getFunctionType();
1556 const char *NameStr = F.getNameStart();
1557 switch (NameStr[0]) {
1559 if (NameLen == 6 && !strcmp(NameStr, "strlen")) {
1560 if (FTy->getNumParams() != 1 ||
1561 !isa<PointerType>(FTy->getParamType(0)))
1563 setOnlyReadsMemory(F);
1565 setDoesNotCapture(F, 1);
1566 } else if ((NameLen == 6 && !strcmp(NameStr, "strcpy")) ||
1567 (NameLen == 6 && !strcmp(NameStr, "stpcpy")) ||
1568 (NameLen == 6 && !strcmp(NameStr, "strcat")) ||
1569 (NameLen == 7 && !strcmp(NameStr, "strncat")) ||
1570 (NameLen == 7 && !strcmp(NameStr, "strncpy"))) {
1571 if (FTy->getNumParams() < 2 ||
1572 !isa<PointerType>(FTy->getParamType(1)))
1575 setDoesNotCapture(F, 2);
1576 } else if (NameLen == 7 && !strcmp(NameStr, "strxfrm")) {
1577 if (FTy->getNumParams() != 3 ||
1578 !isa<PointerType>(FTy->getParamType(0)) ||
1579 !isa<PointerType>(FTy->getParamType(1)))
1582 setDoesNotCapture(F, 1);
1583 setDoesNotCapture(F, 2);
1584 } else if ((NameLen == 6 && !strcmp(NameStr, "strcmp")) ||
1585 (NameLen == 6 && !strcmp(NameStr, "strspn")) ||
1586 (NameLen == 6 && !strcmp(NameStr, "strtol")) ||
1587 (NameLen == 6 && !strcmp(NameStr, "strtod")) ||
1588 (NameLen == 6 && !strcmp(NameStr, "strtof")) ||
1589 (NameLen == 7 && !strcmp(NameStr, "strtoul")) ||
1590 (NameLen == 7 && !strcmp(NameStr, "strtoll")) ||
1591 (NameLen == 7 && !strcmp(NameStr, "strtold")) ||
1592 (NameLen == 7 && !strcmp(NameStr, "strncmp")) ||
1593 (NameLen == 7 && !strcmp(NameStr, "strcspn")) ||
1594 (NameLen == 7 && !strcmp(NameStr, "strcoll")) ||
1595 (NameLen == 8 && !strcmp(NameStr, "strtoull")) ||
1596 (NameLen == 10 && !strcmp(NameStr, "strcasecmp")) ||
1597 (NameLen == 11 && !strcmp(NameStr, "strncasecmp"))) {
1598 if (FTy->getNumParams() < 2 ||
1599 !isa<PointerType>(FTy->getParamType(0)) ||
1600 !isa<PointerType>(FTy->getParamType(1)))
1602 setOnlyReadsMemory(F);
1604 setDoesNotCapture(F, 1);
1605 setDoesNotCapture(F, 2);
1606 } else if ((NameLen == 6 && !strcmp(NameStr, "strstr")) ||
1607 (NameLen == 7 && !strcmp(NameStr, "strpbrk"))) {
1608 if (FTy->getNumParams() != 2 ||
1609 !isa<PointerType>(FTy->getParamType(1)))
1611 setOnlyReadsMemory(F);
1613 setDoesNotCapture(F, 2);
1614 } else if ((NameLen == 6 && !strcmp(NameStr, "strtok")) ||
1615 (NameLen == 8 && !strcmp(NameStr, "strtok_r"))) {
1616 if (FTy->getNumParams() < 2 ||
1617 !isa<PointerType>(FTy->getParamType(1)))
1620 setDoesNotCapture(F, 2);
1621 } else if ((NameLen == 5 && !strcmp(NameStr, "scanf")) ||
1622 (NameLen == 6 && !strcmp(NameStr, "setbuf")) ||
1623 (NameLen == 7 && !strcmp(NameStr, "setvbuf"))) {
1624 if (FTy->getNumParams() < 1 ||
1625 !isa<PointerType>(FTy->getParamType(0)))
1628 setDoesNotCapture(F, 1);
1629 } else if (NameLen == 6 && !strcmp(NameStr, "sscanf")) {
1630 if (FTy->getNumParams() < 2 ||
1631 !isa<PointerType>(FTy->getParamType(0)) ||
1632 !isa<PointerType>(FTy->getParamType(1)))
1635 setDoesNotCapture(F, 1);
1636 setDoesNotCapture(F, 2);
1637 } else if ((NameLen == 6 && !strcmp(NameStr, "strdup")) ||
1638 (NameLen == 7 && !strcmp(NameStr, "strndup"))) {
1639 if (FTy->getNumParams() < 1 ||
1640 !isa<PointerType>(FTy->getReturnType()) ||
1641 !isa<PointerType>(FTy->getParamType(0)))
1644 setDoesNotAlias(F, 0);
1645 setDoesNotCapture(F, 1);
1646 } else if (NameLen == 7 && !strcmp(NameStr, "sprintf")) {
1647 if (FTy->getNumParams() != 2 ||
1648 !isa<PointerType>(FTy->getParamType(0)) ||
1649 !isa<PointerType>(FTy->getParamType(1)))
1652 setDoesNotCapture(F, 1);
1653 setDoesNotCapture(F, 2);
1654 } else if (NameLen == 8 && !strcmp(NameStr, "snprintf")) {
1655 if (FTy->getNumParams() != 3 ||
1656 !isa<PointerType>(FTy->getParamType(0)) ||
1657 !isa<PointerType>(FTy->getParamType(2)))
1660 setDoesNotCapture(F, 1);
1661 setDoesNotCapture(F, 3);
1665 if (NameLen == 6 && !strcmp(NameStr, "memcmp")) {
1666 if (FTy->getNumParams() != 3 ||
1667 !isa<PointerType>(FTy->getParamType(0)) ||
1668 !isa<PointerType>(FTy->getParamType(1)))
1670 setOnlyReadsMemory(F);
1672 setDoesNotCapture(F, 1);
1673 setDoesNotCapture(F, 2);
1674 } else if ((NameLen == 6 && !strcmp(NameStr, "memchr")) ||
1675 (NameLen == 7 && !strcmp(NameStr, "memrchr"))) {
1676 if (FTy->getNumParams() != 3)
1678 setOnlyReadsMemory(F);
1680 } else if ((NameLen == 6 && !strcmp(NameStr, "memcpy")) ||
1681 (NameLen == 7 && !strcmp(NameStr, "memccpy")) ||
1682 (NameLen == 7 && !strcmp(NameStr, "memmove"))) {
1683 if (FTy->getNumParams() < 3 ||
1684 !isa<PointerType>(FTy->getParamType(1)))
1687 setDoesNotCapture(F, 2);
1688 } else if (NameLen == 8 && !strcmp(NameStr, "memalign")) {
1689 if (!isa<PointerType>(FTy->getReturnType()))
1691 setDoesNotAlias(F, 0);
1695 if (NameLen == 7 && !strcmp(NameStr, "realloc")) {
1696 if (FTy->getNumParams() != 2 ||
1697 !isa<PointerType>(FTy->getParamType(0)) ||
1698 !isa<PointerType>(FTy->getReturnType()))
1701 setDoesNotAlias(F, 0);
1702 setDoesNotCapture(F, 1);
1703 } else if (NameLen == 4 && !strcmp(NameStr, "read")) {
1704 if (FTy->getNumParams() != 3 ||
1705 !isa<PointerType>(FTy->getParamType(1)))
1707 // May throw; "read" is a valid pthread cancellation point.
1708 setDoesNotCapture(F, 2);
1709 } else if ((NameLen == 5 && !strcmp(NameStr, "rmdir")) ||
1710 (NameLen == 6 && !strcmp(NameStr, "rewind")) ||
1711 (NameLen == 6 && !strcmp(NameStr, "remove"))) {
1712 if (FTy->getNumParams() != 1 ||
1713 !isa<PointerType>(FTy->getParamType(0)))
1716 setDoesNotCapture(F, 1);
1717 } else if (NameLen == 6 && !strcmp(NameStr, "rename")) {
1718 if (FTy->getNumParams() != 2 ||
1719 !isa<PointerType>(FTy->getParamType(0)) ||
1720 !isa<PointerType>(FTy->getParamType(1)))
1723 setDoesNotCapture(F, 1);
1724 setDoesNotCapture(F, 2);
1728 if (NameLen == 5 && !strcmp(NameStr, "write")) {
1729 if (FTy->getNumParams() != 3 ||
1730 !isa<PointerType>(FTy->getParamType(1)))
1732 // May throw; "write" is a valid pthread cancellation point.
1733 setDoesNotCapture(F, 2);
1737 if (NameLen == 5 && !strcmp(NameStr, "bcopy")) {
1738 if (FTy->getNumParams() != 3 ||
1739 !isa<PointerType>(FTy->getParamType(0)) ||
1740 !isa<PointerType>(FTy->getParamType(1)))
1743 setDoesNotCapture(F, 1);
1744 setDoesNotCapture(F, 2);
1745 } else if (NameLen == 4 && !strcmp(NameStr, "bcmp")) {
1746 if (FTy->getNumParams() != 3 ||
1747 !isa<PointerType>(FTy->getParamType(0)) ||
1748 !isa<PointerType>(FTy->getParamType(1)))
1751 setOnlyReadsMemory(F);
1752 setDoesNotCapture(F, 1);
1753 setDoesNotCapture(F, 2);
1754 } else if (NameLen == 5 && !strcmp(NameStr, "bzero")) {
1755 if (FTy->getNumParams() != 2 ||
1756 !isa<PointerType>(FTy->getParamType(0)))
1759 setDoesNotCapture(F, 1);
1763 if (NameLen == 6 && !strcmp(NameStr, "calloc")) {
1764 if (FTy->getNumParams() != 2 ||
1765 !isa<PointerType>(FTy->getReturnType()))
1768 setDoesNotAlias(F, 0);
1769 } else if ((NameLen == 5 && !strcmp(NameStr, "chown")) ||
1770 (NameLen == 8 && !strcmp(NameStr, "clearerr")) ||
1771 (NameLen == 8 && !strcmp(NameStr, "closedir"))) {
1772 if (FTy->getNumParams() == 0 ||
1773 !isa<PointerType>(FTy->getParamType(0)))
1776 setDoesNotCapture(F, 1);
1780 if ((NameLen == 4 && !strcmp(NameStr, "atoi")) ||
1781 (NameLen == 4 && !strcmp(NameStr, "atol")) ||
1782 (NameLen == 4 && !strcmp(NameStr, "atof")) ||
1783 (NameLen == 5 && !strcmp(NameStr, "atoll"))) {
1784 if (FTy->getNumParams() != 1 ||
1785 !isa<PointerType>(FTy->getParamType(0)))
1788 setOnlyReadsMemory(F);
1789 setDoesNotCapture(F, 1);
1790 } else if (NameLen == 6 && !strcmp(NameStr, "access")) {
1791 if (FTy->getNumParams() != 2 ||
1792 !isa<PointerType>(FTy->getParamType(0)))
1795 setDoesNotCapture(F, 1);
1799 if (NameLen == 5 && !strcmp(NameStr, "fopen")) {
1800 if (FTy->getNumParams() != 2 ||
1801 !isa<PointerType>(FTy->getReturnType()) ||
1802 !isa<PointerType>(FTy->getParamType(0)) ||
1803 !isa<PointerType>(FTy->getParamType(1)))
1806 setDoesNotAlias(F, 0);
1807 setDoesNotCapture(F, 1);
1808 setDoesNotCapture(F, 2);
1809 } else if (NameLen == 6 && !strcmp(NameStr, "fdopen")) {
1810 if (FTy->getNumParams() != 2 ||
1811 !isa<PointerType>(FTy->getReturnType()) ||
1812 !isa<PointerType>(FTy->getParamType(1)))
1815 setDoesNotAlias(F, 0);
1816 setDoesNotCapture(F, 2);
1817 } else if ((NameLen == 4 && !strcmp(NameStr, "feof")) ||
1818 (NameLen == 4 && !strcmp(NameStr, "free")) ||
1819 (NameLen == 5 && !strcmp(NameStr, "fseek")) ||
1820 (NameLen == 5 && !strcmp(NameStr, "ftell")) ||
1821 (NameLen == 5 && !strcmp(NameStr, "fgetc")) ||
1822 (NameLen == 6 && !strcmp(NameStr, "fseeko")) ||
1823 (NameLen == 6 && !strcmp(NameStr, "ftello")) ||
1824 (NameLen == 6 && !strcmp(NameStr, "fileno")) ||
1825 (NameLen == 6 && !strcmp(NameStr, "fflush")) ||
1826 (NameLen == 6 && !strcmp(NameStr, "fclose")) ||
1827 (NameLen == 7 && !strcmp(NameStr, "fsetpos"))) {
1828 if (FTy->getNumParams() == 0 ||
1829 !isa<PointerType>(FTy->getParamType(0)))
1832 setDoesNotCapture(F, 1);
1833 } else if (NameLen == 6 && !strcmp(NameStr, "ferror")) {
1834 if (FTy->getNumParams() != 1 ||
1835 !isa<PointerType>(FTy->getParamType(0)))
1838 setDoesNotCapture(F, 1);
1839 setOnlyReadsMemory(F);
1840 } else if ((NameLen == 5 && !strcmp(NameStr, "fputc")) ||
1841 (NameLen == 5 && !strcmp(NameStr, "fputs"))) {
1842 if (FTy->getNumParams() != 2 ||
1843 !isa<PointerType>(FTy->getParamType(1)))
1846 setDoesNotCapture(F, 2);
1847 } else if (NameLen == 5 && !strcmp(NameStr, "fgets")) {
1848 if (FTy->getNumParams() != 3 ||
1849 !isa<PointerType>(FTy->getParamType(0)) ||
1850 !isa<PointerType>(FTy->getParamType(2)))
1853 setDoesNotCapture(F, 3);
1854 } else if ((NameLen == 5 && !strcmp(NameStr, "fread")) ||
1855 (NameLen == 6 && !strcmp(NameStr, "fwrite"))) {
1856 if (FTy->getNumParams() != 4 ||
1857 !isa<PointerType>(FTy->getParamType(0)) ||
1858 !isa<PointerType>(FTy->getParamType(3)))
1861 setDoesNotCapture(F, 1);
1862 setDoesNotCapture(F, 4);
1863 } else if (NameLen == 7 && !strcmp(NameStr, "fgetpos")) {
1864 if (FTy->getNumParams() != 2 ||
1865 !isa<PointerType>(FTy->getParamType(0)) ||
1866 !isa<PointerType>(FTy->getParamType(1)))
1869 setDoesNotCapture(F, 1);
1870 setDoesNotCapture(F, 2);
1871 } else if (NameLen == 6 && !strcmp(NameStr, "fscanf")) {
1872 if (FTy->getNumParams() < 2 ||
1873 !isa<PointerType>(FTy->getParamType(0)) ||
1874 !isa<PointerType>(FTy->getParamType(1)))
1877 setDoesNotCapture(F, 1);
1878 setDoesNotCapture(F, 2);
1879 } else if (NameLen == 7 && !strcmp(NameStr, "fprintf")) {
1880 if (FTy->getNumParams() != 2 ||
1881 !isa<PointerType>(FTy->getParamType(0)) ||
1882 !isa<PointerType>(FTy->getParamType(1)))
1885 setDoesNotCapture(F, 1);
1886 setDoesNotCapture(F, 2);
1890 if ((NameLen == 4 && !strcmp(NameStr, "getc")) ||
1891 (NameLen == 10 && !strcmp(NameStr, "getlogin_r"))) {
1892 if (FTy->getNumParams() == 0 ||
1893 !isa<PointerType>(FTy->getParamType(0)))
1896 setDoesNotCapture(F, 1);
1897 } else if (NameLen == 6 && !strcmp(NameStr, "getenv")) {
1898 if (FTy->getNumParams() != 1 ||
1899 !isa<PointerType>(FTy->getParamType(0)))
1902 setOnlyReadsMemory(F);
1903 setDoesNotCapture(F, 1);
1904 } else if ((NameLen == 4 && !strcmp(NameStr, "gets")) ||
1905 (NameLen == 7 && !strcmp(NameStr, "getchar"))) {
1910 if (NameLen == 6 && !strcmp(NameStr, "ungetc")) {
1911 if (FTy->getNumParams() != 2 ||
1912 !isa<PointerType>(FTy->getParamType(1)))
1915 setDoesNotCapture(F, 2);
1916 } else if (NameLen == 6 && !strcmp(NameStr, "unlink")) {
1917 if (FTy->getNumParams() != 1 ||
1918 !isa<PointerType>(FTy->getParamType(0)))
1921 setDoesNotCapture(F, 1);
1925 if (NameLen == 4 && !strcmp(NameStr, "putc")) {
1926 if (FTy->getNumParams() != 2 ||
1927 !isa<PointerType>(FTy->getParamType(1)))
1930 setDoesNotCapture(F, 2);
1931 } else if ((NameLen == 4 && !strcmp(NameStr, "puts")) ||
1932 (NameLen == 6 && !strcmp(NameStr, "printf")) ||
1933 (NameLen == 6 && !strcmp(NameStr, "perror"))) {
1934 if (FTy->getNumParams() != 1 ||
1935 !isa<PointerType>(FTy->getParamType(0)))
1938 setDoesNotCapture(F, 1);
1939 } else if ((NameLen == 5 && !strcmp(NameStr, "pread")) ||
1940 (NameLen == 6 && !strcmp(NameStr, "pwrite"))) {
1941 if (FTy->getNumParams() != 4 ||
1942 !isa<PointerType>(FTy->getParamType(1)))
1944 // May throw; these are valid pthread cancellation points.
1945 setDoesNotCapture(F, 2);
1946 } else if (NameLen == 7 && !strcmp(NameStr, "putchar")) {
1951 if (NameLen == 6 && !strcmp(NameStr, "vscanf")) {
1952 if (FTy->getNumParams() != 2 ||
1953 !isa<PointerType>(FTy->getParamType(1)))
1956 setDoesNotCapture(F, 1);
1957 } else if ((NameLen == 7 && !strcmp(NameStr, "vsscanf")) ||
1958 (NameLen == 7 && !strcmp(NameStr, "vfscanf"))) {
1959 if (FTy->getNumParams() != 3 ||
1960 !isa<PointerType>(FTy->getParamType(1)) ||
1961 !isa<PointerType>(FTy->getParamType(2)))
1964 setDoesNotCapture(F, 1);
1965 setDoesNotCapture(F, 2);
1966 } else if (NameLen == 6 && !strcmp(NameStr, "valloc")) {
1967 if (!isa<PointerType>(FTy->getReturnType()))
1970 setDoesNotAlias(F, 0);
1971 } else if (NameLen == 7 && !strcmp(NameStr, "vprintf")) {
1972 if (FTy->getNumParams() != 2 ||
1973 !isa<PointerType>(FTy->getParamType(0)))
1976 setDoesNotCapture(F, 1);
1977 } else if ((NameLen == 8 && !strcmp(NameStr, "vfprintf")) ||
1978 (NameLen == 8 && !strcmp(NameStr, "vsprintf"))) {
1979 if (FTy->getNumParams() != 3 ||
1980 !isa<PointerType>(FTy->getParamType(0)) ||
1981 !isa<PointerType>(FTy->getParamType(1)))
1984 setDoesNotCapture(F, 1);
1985 setDoesNotCapture(F, 2);
1986 } else if (NameLen == 9 && !strcmp(NameStr, "vsnprintf")) {
1987 if (FTy->getNumParams() != 4 ||
1988 !isa<PointerType>(FTy->getParamType(0)) ||
1989 !isa<PointerType>(FTy->getParamType(2)))
1992 setDoesNotCapture(F, 1);
1993 setDoesNotCapture(F, 3);
1997 if (NameLen == 7 && !strcmp(NameStr, "opendir")) {
1998 // The description of fdopendir sounds like opening the same fd
1999 // twice might result in the same DIR* !
2000 if (!isa<PointerType>(FTy->getReturnType()))
2003 setDoesNotAlias(F, 0);
2007 if (NameLen == 7 && !strcmp(NameStr, "tmpfile")) {
2008 if (!isa<PointerType>(FTy->getReturnType()))
2011 setDoesNotAlias(F, 0);
2014 if ((NameLen == 5 && !strcmp(NameStr, "htonl")) ||
2015 (NameLen == 5 && !strcmp(NameStr, "htons"))) {
2017 setDoesNotAccessMemory(F);
2021 if ((NameLen == 5 && !strcmp(NameStr, "ntohl")) ||
2022 (NameLen == 5 && !strcmp(NameStr, "ntohs"))) {
2024 setDoesNotAccessMemory(F);
2027 if ((NameLen == 8 && !strcmp(NameStr, "__strdup")) ||
2028 (NameLen == 9 && !strcmp(NameStr, "__strndup"))) {
2029 if (FTy->getNumParams() < 1 ||
2030 !isa<PointerType>(FTy->getReturnType()) ||
2031 !isa<PointerType>(FTy->getParamType(0)))
2034 setDoesNotAlias(F, 0);
2035 setDoesNotCapture(F, 1);
2036 } else if (NameLen == 10 && !strcmp(NameStr, "__strtok_r")) {
2037 if (FTy->getNumParams() != 3 ||
2038 !isa<PointerType>(FTy->getParamType(1)))
2041 setDoesNotCapture(F, 2);
2042 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_getc")) {
2043 if (FTy->getNumParams() != 1 ||
2044 !isa<PointerType>(FTy->getParamType(0)))
2047 setDoesNotCapture(F, 1);
2048 } else if (NameLen == 8 && !strcmp(NameStr, "_IO_putc")) {
2049 if (FTy->getNumParams() != 2 ||
2050 !isa<PointerType>(FTy->getParamType(1)))
2053 setDoesNotCapture(F, 2);
2056 if (NameLen == 15 && !strcmp(NameStr, "\1__isoc99_scanf")) {
2057 if (FTy->getNumParams() < 1 ||
2058 !isa<PointerType>(FTy->getParamType(0)))
2061 setDoesNotCapture(F, 1);
2062 } else if (NameLen == 16 && !strcmp(NameStr, "\1__isoc99_sscanf")) {
2063 if (FTy->getNumParams() < 1 ||
2064 !isa<PointerType>(FTy->getParamType(0)))
2067 setDoesNotCapture(F, 1);
2068 setDoesNotCapture(F, 2);
2077 // Additional cases that we need to add to this file:
2080 // * cbrt(expN(X)) -> expN(x/3)
2081 // * cbrt(sqrt(x)) -> pow(x,1/6)
2082 // * cbrt(sqrt(x)) -> pow(x,1/9)
2085 // * cos(-x) -> cos(x)
2088 // * exp(log(x)) -> x
2091 // * log(exp(x)) -> x
2092 // * log(x**y) -> y*log(x)
2093 // * log(exp(y)) -> y*log(e)
2094 // * log(exp2(y)) -> y*log(2)
2095 // * log(exp10(y)) -> y*log(10)
2096 // * log(sqrt(x)) -> 0.5*log(x)
2097 // * log(pow(x,y)) -> y*log(x)
2099 // lround, lroundf, lroundl:
2100 // * lround(cnst) -> cnst'
2103 // * memcmp(x,y,l) -> cnst
2104 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
2107 // * pow(exp(x),y) -> exp(x*y)
2108 // * pow(sqrt(x),y) -> pow(x,y*0.5)
2109 // * pow(pow(x,y),z)-> pow(x,y*z)
2112 // * puts("") -> putchar("\n")
2114 // round, roundf, roundl:
2115 // * round(cnst) -> cnst'
2118 // * signbit(cnst) -> cnst'
2119 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
2121 // sqrt, sqrtf, sqrtl:
2122 // * sqrt(expN(x)) -> expN(x*0.5)
2123 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
2124 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
2127 // * stpcpy(str, "literal") ->
2128 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
2130 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
2131 // (if c is a constant integer and s is a constant string)
2132 // * strrchr(s1,0) -> strchr(s1,0)
2135 // * strncat(x,y,0) -> x
2136 // * strncat(x,y,0) -> x (if strlen(y) = 0)
2137 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
2140 // * strncpy(d,s,0) -> d
2141 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
2142 // (if s and l are constants)
2145 // * strpbrk(s,a) -> offset_in_for(s,a)
2146 // (if s and a are both constant strings)
2147 // * strpbrk(s,"") -> 0
2148 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
2151 // * strspn(s,a) -> const_int (if both args are constant)
2152 // * strspn("",a) -> 0
2153 // * strspn(s,"") -> 0
2154 // * strcspn(s,a) -> const_int (if both args are constant)
2155 // * strcspn("",a) -> 0
2156 // * strcspn(s,"") -> strlen(a)
2159 // * strstr(x,x) -> x
2160 // * strstr(s1,s2) -> offset_of_s2_in(s1)
2161 // (if s1 and s2 are constant strings)
2164 // * tan(atan(x)) -> x
2166 // trunc, truncf, truncl:
2167 // * trunc(cnst) -> cnst'