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");
38 //===----------------------------------------------------------------------===//
39 // Optimizer Base Class
40 //===----------------------------------------------------------------------===//
42 /// This class is the abstract base class for the set of optimizations that
43 /// corresponds to one library call.
45 class VISIBILITY_HIDDEN LibCallOptimization {
50 LibCallOptimization() { }
51 virtual ~LibCallOptimization() {}
53 /// CallOptimizer - This pure virtual method is implemented by base classes to
54 /// do various optimizations. If this returns null then no transformation was
55 /// performed. If it returns CI, then it transformed the call and CI is to be
56 /// deleted. If it returns something else, replace CI with the new value and
58 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B)
61 Value *OptimizeCall(CallInst *CI, const TargetData &TD, IRBuilder<> &B) {
62 Caller = CI->getParent()->getParent();
64 return CallOptimizer(CI->getCalledFunction(), CI, B);
67 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
68 Value *CastToCStr(Value *V, IRBuilder<> &B);
70 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
71 /// specified pointer. Ptr is required to be some pointer type, and the
72 /// return value has 'intptr_t' type.
73 Value *EmitStrLen(Value *Ptr, IRBuilder<> &B);
75 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This
76 /// always expects that the size has type 'intptr_t' and Dst/Src are pointers.
77 Value *EmitMemCpy(Value *Dst, Value *Src, Value *Len,
78 unsigned Align, IRBuilder<> &B);
80 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
81 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
82 Value *EmitMemChr(Value *Ptr, Value *Val, Value *Len, IRBuilder<> &B);
84 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
85 /// 'floor'). This function is known to take a single of type matching 'Op'
86 /// and returns one value with the same type. If 'Op' is a long double, 'l'
87 /// is added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
88 Value *EmitUnaryFloatFnCall(Value *Op, const char *Name, IRBuilder<> &B);
90 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
92 void EmitPutChar(Value *Char, IRBuilder<> &B);
94 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
96 void EmitPutS(Value *Str, IRBuilder<> &B);
98 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
99 /// an i32, and File is a pointer to FILE.
100 void EmitFPutC(Value *Char, Value *File, IRBuilder<> &B);
102 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
103 /// pointer and File is a pointer to FILE.
104 void EmitFPutS(Value *Str, Value *File, IRBuilder<> &B);
106 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
107 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
108 void EmitFWrite(Value *Ptr, Value *Size, Value *File, IRBuilder<> &B);
111 } // End anonymous namespace.
113 /// CastToCStr - Return V if it is an i8*, otherwise cast it to i8*.
114 Value *LibCallOptimization::CastToCStr(Value *V, IRBuilder<> &B) {
115 return B.CreateBitCast(V, PointerType::getUnqual(Type::Int8Ty), "cstr");
118 /// EmitStrLen - Emit a call to the strlen function to the builder, for the
119 /// specified pointer. This always returns an integer value of size intptr_t.
120 Value *LibCallOptimization::EmitStrLen(Value *Ptr, IRBuilder<> &B) {
121 Module *M = Caller->getParent();
122 Constant *StrLen =M->getOrInsertFunction("strlen", TD->getIntPtrType(),
123 PointerType::getUnqual(Type::Int8Ty),
125 return B.CreateCall(StrLen, CastToCStr(Ptr, B), "strlen");
128 /// EmitMemCpy - Emit a call to the memcpy function to the builder. This always
129 /// expects that the size has type 'intptr_t' and Dst/Src are pointers.
130 Value *LibCallOptimization::EmitMemCpy(Value *Dst, Value *Src, Value *Len,
131 unsigned Align, IRBuilder<> &B) {
132 Module *M = Caller->getParent();
133 Intrinsic::ID IID = Len->getType() == Type::Int32Ty ?
134 Intrinsic::memcpy_i32 : Intrinsic::memcpy_i64;
135 Value *MemCpy = Intrinsic::getDeclaration(M, IID);
136 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
137 ConstantInt::get(Type::Int32Ty, Align));
140 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
141 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
142 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
143 Value *Len, IRBuilder<> &B) {
144 Module *M = Caller->getParent();
145 Value *MemChr = M->getOrInsertFunction("memchr",
146 PointerType::getUnqual(Type::Int8Ty),
147 PointerType::getUnqual(Type::Int8Ty),
148 Type::Int32Ty, TD->getIntPtrType(),
150 return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
153 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
154 /// 'floor'). This function is known to take a single of type matching 'Op' and
155 /// returns one value with the same type. If 'Op' is a long double, 'l' is
156 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
157 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
160 if (Op->getType() != Type::DoubleTy) {
161 // If we need to add a suffix, copy into NameBuffer.
162 unsigned NameLen = strlen(Name);
163 assert(NameLen < sizeof(NameBuffer)-2);
164 memcpy(NameBuffer, Name, NameLen);
165 if (Op->getType() == Type::FloatTy)
166 NameBuffer[NameLen] = 'f'; // floorf
168 NameBuffer[NameLen] = 'l'; // floorl
169 NameBuffer[NameLen+1] = 0;
173 Module *M = Caller->getParent();
174 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
175 Op->getType(), NULL);
176 return B.CreateCall(Callee, Op, Name);
179 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
181 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
182 Module *M = Caller->getParent();
183 Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
184 Type::Int32Ty, NULL);
185 B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
188 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
190 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
191 Module *M = Caller->getParent();
192 Value *F = M->getOrInsertFunction("puts", Type::Int32Ty,
193 PointerType::getUnqual(Type::Int8Ty), NULL);
194 B.CreateCall(F, CastToCStr(Str, B), "puts");
197 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
198 /// an integer and File is a pointer to FILE.
199 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
200 Module *M = Caller->getParent();
201 Constant *F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
202 File->getType(), NULL);
203 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
204 B.CreateCall2(F, Char, File, "fputc");
207 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
208 /// pointer and File is a pointer to FILE.
209 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
210 Module *M = Caller->getParent();
211 Constant *F = M->getOrInsertFunction("fputs", Type::Int32Ty,
212 PointerType::getUnqual(Type::Int8Ty),
213 File->getType(), NULL);
214 B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
217 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
218 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
219 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
221 Module *M = Caller->getParent();
222 Constant *F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
223 PointerType::getUnqual(Type::Int8Ty),
224 TD->getIntPtrType(), TD->getIntPtrType(),
225 File->getType(), NULL);
226 B.CreateCall4(F, CastToCStr(Ptr, B), Size,
227 ConstantInt::get(TD->getIntPtrType(), 1), File);
230 //===----------------------------------------------------------------------===//
232 //===----------------------------------------------------------------------===//
234 /// GetStringLengthH - If we can compute the length of the string pointed to by
235 /// the specified pointer, return 'len+1'. If we can't, return 0.
236 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
237 // Look through noop bitcast instructions.
238 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
239 return GetStringLengthH(BCI->getOperand(0), PHIs);
241 // If this is a PHI node, there are two cases: either we have already seen it
243 if (PHINode *PN = dyn_cast<PHINode>(V)) {
244 if (!PHIs.insert(PN))
245 return ~0ULL; // already in the set.
247 // If it was new, see if all the input strings are the same length.
248 uint64_t LenSoFar = ~0ULL;
249 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
250 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
251 if (Len == 0) return 0; // Unknown length -> unknown.
253 if (Len == ~0ULL) continue;
255 if (Len != LenSoFar && LenSoFar != ~0ULL)
256 return 0; // Disagree -> unknown.
260 // Success, all agree.
264 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
265 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
266 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
267 if (Len1 == 0) return 0;
268 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
269 if (Len2 == 0) return 0;
270 if (Len1 == ~0ULL) return Len2;
271 if (Len2 == ~0ULL) return Len1;
272 if (Len1 != Len2) return 0;
276 // If the value is not a GEP instruction nor a constant expression with a
277 // GEP instruction, then return unknown.
279 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
281 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
282 if (CE->getOpcode() != Instruction::GetElementPtr)
289 // Make sure the GEP has exactly three arguments.
290 if (GEP->getNumOperands() != 3)
293 // Check to make sure that the first operand of the GEP is an integer and
294 // has value 0 so that we are sure we're indexing into the initializer.
295 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
301 // If the second index isn't a ConstantInt, then this is a variable index
302 // into the array. If this occurs, we can't say anything meaningful about
304 uint64_t StartIdx = 0;
305 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
306 StartIdx = CI->getZExtValue();
310 // The GEP instruction, constant or instruction, must reference a global
311 // variable that is a constant and is initialized. The referenced constant
312 // initializer is the array that we'll use for optimization.
313 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
314 if (!GV || !GV->isConstant() || !GV->hasInitializer())
316 Constant *GlobalInit = GV->getInitializer();
318 // Handle the ConstantAggregateZero case, which is a degenerate case. The
319 // initializer is constant zero so the length of the string must be zero.
320 if (isa<ConstantAggregateZero>(GlobalInit))
321 return 1; // Len = 0 offset by 1.
323 // Must be a Constant Array
324 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
325 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
328 // Get the number of elements in the array
329 uint64_t NumElts = Array->getType()->getNumElements();
331 // Traverse the constant array from StartIdx (derived above) which is
332 // the place the GEP refers to in the array.
333 for (unsigned i = StartIdx; i != NumElts; ++i) {
334 Constant *Elt = Array->getOperand(i);
335 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
336 if (!CI) // This array isn't suitable, non-int initializer.
339 return i-StartIdx+1; // We found end of string, success!
342 return 0; // The array isn't null terminated, conservatively return 'unknown'.
345 /// GetStringLength - If we can compute the length of the string pointed to by
346 /// the specified pointer, return 'len+1'. If we can't, return 0.
347 static uint64_t GetStringLength(Value *V) {
348 if (!isa<PointerType>(V->getType())) return 0;
350 SmallPtrSet<PHINode*, 32> PHIs;
351 uint64_t Len = GetStringLengthH(V, PHIs);
352 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
353 // an empty string as a length.
354 return Len == ~0ULL ? 1 : Len;
357 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
358 /// value is equal or not-equal to zero.
359 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
360 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
362 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
363 if (IC->isEquality())
364 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
365 if (C->isNullValue())
367 // Unknown instruction.
373 //===----------------------------------------------------------------------===//
374 // Miscellaneous LibCall Optimizations
375 //===----------------------------------------------------------------------===//
378 //===---------------------------------------===//
379 // 'exit' Optimizations
381 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
382 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
383 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
384 // Verify we have a reasonable prototype for exit.
385 if (Callee->arg_size() == 0 || !CI->use_empty())
388 // Verify the caller is main, and that the result type of main matches the
389 // argument type of exit.
390 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
391 Caller->getReturnType() != CI->getOperand(1)->getType())
394 TerminatorInst *OldTI = CI->getParent()->getTerminator();
396 // Create the return after the call.
397 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
399 // Drop all successor phi node entries.
400 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
401 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
403 // Erase all instructions from after our return instruction until the end of
405 BasicBlock::iterator FirstDead = RI; ++FirstDead;
406 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
411 //===----------------------------------------------------------------------===//
412 // String and Memory LibCall Optimizations
413 //===----------------------------------------------------------------------===//
415 //===---------------------------------------===//
416 // 'strcat' Optimizations
418 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
419 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
420 // Verify the "strcat" function prototype.
421 const FunctionType *FT = Callee->getFunctionType();
422 if (FT->getNumParams() != 2 ||
423 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
424 FT->getParamType(0) != FT->getReturnType() ||
425 FT->getParamType(1) != FT->getReturnType())
428 // Extract some information from the instruction
429 Value *Dst = CI->getOperand(1);
430 Value *Src = CI->getOperand(2);
432 // See if we can get the length of the input string.
433 uint64_t Len = GetStringLength(Src);
434 if (Len == 0) return 0;
435 --Len; // Unbias length.
437 // Handle the simple, do-nothing case: strcat(x, "") -> x
441 // We need to find the end of the destination string. That's where the
442 // memory is to be moved to. We just generate a call to strlen.
443 Value *DstLen = EmitStrLen(Dst, B);
445 // Now that we have the destination's length, we must index into the
446 // destination's pointer to get the actual memcpy destination (end of
447 // the string .. we're concatenating).
448 Dst = B.CreateGEP(Dst, DstLen, "endptr");
450 // We have enough information to now generate the memcpy call to do the
451 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
452 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
457 //===---------------------------------------===//
458 // 'strchr' Optimizations
460 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
461 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
462 // Verify the "strchr" function prototype.
463 const FunctionType *FT = Callee->getFunctionType();
464 if (FT->getNumParams() != 2 ||
465 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
466 FT->getParamType(0) != FT->getReturnType())
469 Value *SrcStr = CI->getOperand(1);
471 // If the second operand is non-constant, see if we can compute the length
472 // of the input string and turn this into memchr.
473 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
475 uint64_t Len = GetStringLength(SrcStr);
476 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
479 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
480 ConstantInt::get(TD->getIntPtrType(), Len), B);
483 // Otherwise, the character is a constant, see if the first argument is
484 // a string literal. If so, we can constant fold.
486 if (!GetConstantStringInfo(SrcStr, Str))
489 // strchr can find the nul character.
491 char CharValue = CharC->getSExtValue();
493 // Compute the offset.
496 if (i == Str.size()) // Didn't find the char. strchr returns null.
497 return Constant::getNullValue(CI->getType());
498 // Did we find our match?
499 if (Str[i] == CharValue)
504 // strchr(s+n,c) -> gep(s+n+i,c)
505 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
506 return B.CreateGEP(SrcStr, Idx, "strchr");
510 //===---------------------------------------===//
511 // 'strcmp' Optimizations
513 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
514 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
515 // Verify the "strcmp" function prototype.
516 const FunctionType *FT = Callee->getFunctionType();
517 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
518 FT->getParamType(0) != FT->getParamType(1) ||
519 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
522 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
523 if (Str1P == Str2P) // strcmp(x,x) -> 0
524 return ConstantInt::get(CI->getType(), 0);
526 std::string Str1, Str2;
527 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
528 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
530 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
531 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
533 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
534 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
536 // strcmp(x, y) -> cnst (if both x and y are constant strings)
537 if (HasStr1 && HasStr2)
538 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
543 //===---------------------------------------===//
544 // 'strncmp' Optimizations
546 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
547 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
548 // Verify the "strncmp" function prototype.
549 const FunctionType *FT = Callee->getFunctionType();
550 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
551 FT->getParamType(0) != FT->getParamType(1) ||
552 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
553 !isa<IntegerType>(FT->getParamType(2)))
556 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
557 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
558 return ConstantInt::get(CI->getType(), 0);
560 // Get the length argument if it is constant.
562 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
563 Length = LengthArg->getZExtValue();
567 if (Length == 0) // strncmp(x,y,0) -> 0
568 return ConstantInt::get(CI->getType(), 0);
570 std::string Str1, Str2;
571 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
572 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
574 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
575 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
577 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
578 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
580 // strncmp(x, y) -> cnst (if both x and y are constant strings)
581 if (HasStr1 && HasStr2)
582 return ConstantInt::get(CI->getType(),
583 strncmp(Str1.c_str(), Str2.c_str(), Length));
589 //===---------------------------------------===//
590 // 'strcpy' Optimizations
592 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
593 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
594 // Verify the "strcpy" function prototype.
595 const FunctionType *FT = Callee->getFunctionType();
596 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
597 FT->getParamType(0) != FT->getParamType(1) ||
598 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
601 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
602 if (Dst == Src) // strcpy(x,x) -> x
605 // See if we can get the length of the input string.
606 uint64_t Len = GetStringLength(Src);
607 if (Len == 0) return 0;
609 // We have enough information to now generate the memcpy call to do the
610 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
611 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
618 //===---------------------------------------===//
619 // 'strlen' Optimizations
621 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
622 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
623 const FunctionType *FT = Callee->getFunctionType();
624 if (FT->getNumParams() != 1 ||
625 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
626 !isa<IntegerType>(FT->getReturnType()))
629 Value *Src = CI->getOperand(1);
631 // Constant folding: strlen("xyz") -> 3
632 if (uint64_t Len = GetStringLength(Src))
633 return ConstantInt::get(CI->getType(), Len-1);
635 // Handle strlen(p) != 0.
636 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
638 // strlen(x) != 0 --> *x != 0
639 // strlen(x) == 0 --> *x == 0
640 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
644 //===---------------------------------------===//
645 // 'memcmp' Optimizations
647 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
648 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
649 const FunctionType *FT = Callee->getFunctionType();
650 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
651 !isa<PointerType>(FT->getParamType(1)) ||
652 FT->getReturnType() != Type::Int32Ty)
655 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
657 if (LHS == RHS) // memcmp(s,s,x) -> 0
658 return Constant::getNullValue(CI->getType());
660 // Make sure we have a constant length.
661 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
663 uint64_t Len = LenC->getZExtValue();
665 if (Len == 0) // memcmp(s1,s2,0) -> 0
666 return Constant::getNullValue(CI->getType());
668 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
669 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
670 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
671 return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
674 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
675 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
676 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
677 const Type *PTy = PointerType::getUnqual(Len == 2 ?
678 Type::Int16Ty : Type::Int32Ty);
679 LHS = B.CreateBitCast(LHS, PTy, "tmp");
680 RHS = B.CreateBitCast(RHS, PTy, "tmp");
681 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
682 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
683 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
684 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
691 //===---------------------------------------===//
692 // 'memcpy' Optimizations
694 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
695 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
696 const FunctionType *FT = Callee->getFunctionType();
697 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
698 !isa<PointerType>(FT->getParamType(0)) ||
699 !isa<PointerType>(FT->getParamType(1)) ||
700 FT->getParamType(2) != TD->getIntPtrType())
703 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
704 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
705 return CI->getOperand(1);
709 //===----------------------------------------------------------------------===//
710 // Math Library Optimizations
711 //===----------------------------------------------------------------------===//
713 //===---------------------------------------===//
714 // 'pow*' Optimizations
716 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
717 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
718 const FunctionType *FT = Callee->getFunctionType();
719 // Just make sure this has 2 arguments of the same FP type, which match the
721 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
722 FT->getParamType(0) != FT->getParamType(1) ||
723 !FT->getParamType(0)->isFloatingPoint())
726 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
727 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
728 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
730 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
731 return EmitUnaryFloatFnCall(Op2, "exp2", B);
734 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
735 if (Op2C == 0) return 0;
737 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
738 return ConstantFP::get(CI->getType(), 1.0);
740 if (Op2C->isExactlyValue(0.5)) {
741 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
742 // 'unsafe' math optimizations are allowed.
743 // x pow(x, 0.5) sqrt(x)
744 // ---------------------------------------------
748 // pow(x, 0.5) -> sqrt(x)
749 return B.CreateCall(get_sqrt(), Op1, "sqrt");
753 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
755 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
756 return B.CreateMul(Op1, Op1, "pow2");
757 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
758 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
763 //===---------------------------------------===//
764 // 'exp2' Optimizations
766 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
767 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
768 const FunctionType *FT = Callee->getFunctionType();
769 // Just make sure this has 1 argument of FP type, which matches the
771 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
772 !FT->getParamType(0)->isFloatingPoint())
775 Value *Op = CI->getOperand(1);
776 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
777 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
779 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
780 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
781 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
782 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
783 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
784 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
789 if (Op->getType() == Type::FloatTy)
791 else if (Op->getType() == Type::DoubleTy)
796 Constant *One = ConstantFP::get(APFloat(1.0f));
797 if (Op->getType() != Type::FloatTy)
798 One = ConstantExpr::getFPExtend(One, Op->getType());
800 Module *M = Caller->getParent();
801 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
802 Op->getType(), Type::Int32Ty,NULL);
803 return B.CreateCall2(Callee, One, LdExpArg);
810 //===---------------------------------------===//
811 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
813 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
814 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
815 const FunctionType *FT = Callee->getFunctionType();
816 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
817 FT->getParamType(0) != Type::DoubleTy)
820 // If this is something like 'floor((double)floatval)', convert to floorf.
821 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
822 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
825 // floor((double)floatval) -> (double)floorf(floatval)
826 Value *V = Cast->getOperand(0);
827 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
828 return B.CreateFPExt(V, Type::DoubleTy);
832 //===----------------------------------------------------------------------===//
833 // Integer Optimizations
834 //===----------------------------------------------------------------------===//
836 //===---------------------------------------===//
837 // 'ffs*' Optimizations
839 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
840 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
841 const FunctionType *FT = Callee->getFunctionType();
842 // Just make sure this has 2 arguments of the same FP type, which match the
844 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
845 !isa<IntegerType>(FT->getParamType(0)))
848 Value *Op = CI->getOperand(1);
851 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
852 if (CI->getValue() == 0) // ffs(0) -> 0.
853 return Constant::getNullValue(CI->getType());
854 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
855 CI->getValue().countTrailingZeros()+1);
858 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
859 const Type *ArgType = Op->getType();
860 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
861 Intrinsic::cttz, &ArgType, 1);
862 Value *V = B.CreateCall(F, Op, "cttz");
863 V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
864 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
866 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
867 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
871 //===---------------------------------------===//
872 // 'isdigit' Optimizations
874 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
875 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
876 const FunctionType *FT = Callee->getFunctionType();
877 // We require integer(i32)
878 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
879 FT->getParamType(0) != Type::Int32Ty)
882 // isdigit(c) -> (c-'0') <u 10
883 Value *Op = CI->getOperand(1);
884 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
885 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
886 return B.CreateZExt(Op, CI->getType());
890 //===---------------------------------------===//
891 // 'isascii' Optimizations
893 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
894 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
895 const FunctionType *FT = Callee->getFunctionType();
896 // We require integer(i32)
897 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
898 FT->getParamType(0) != Type::Int32Ty)
901 // isascii(c) -> c <u 128
902 Value *Op = CI->getOperand(1);
903 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
904 return B.CreateZExt(Op, CI->getType());
908 //===---------------------------------------===//
909 // 'abs', 'labs', 'llabs' Optimizations
911 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
912 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
913 const FunctionType *FT = Callee->getFunctionType();
914 // We require integer(integer) where the types agree.
915 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
916 FT->getParamType(0) != FT->getReturnType())
919 // abs(x) -> x >s -1 ? x : -x
920 Value *Op = CI->getOperand(1);
921 Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
923 Value *Neg = B.CreateNeg(Op, "neg");
924 return B.CreateSelect(Pos, Op, Neg);
929 //===---------------------------------------===//
930 // 'toascii' Optimizations
932 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
933 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
934 const FunctionType *FT = Callee->getFunctionType();
935 // We require i32(i32)
936 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
937 FT->getParamType(0) != Type::Int32Ty)
940 // isascii(c) -> c & 0x7f
941 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
945 //===----------------------------------------------------------------------===//
946 // Formatting and IO Optimizations
947 //===----------------------------------------------------------------------===//
949 //===---------------------------------------===//
950 // 'printf' Optimizations
952 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
953 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
954 // Require one fixed pointer argument and an integer/void result.
955 const FunctionType *FT = Callee->getFunctionType();
956 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
957 !(isa<IntegerType>(FT->getReturnType()) ||
958 FT->getReturnType() == Type::VoidTy))
961 // Check for a fixed format string.
962 std::string FormatStr;
963 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
966 // Empty format string -> noop.
967 if (FormatStr.empty()) // Tolerate printf's declared void.
968 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
970 // printf("x") -> putchar('x'), even for '%'.
971 if (FormatStr.size() == 1) {
972 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
973 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
976 // printf("foo\n") --> puts("foo")
977 if (FormatStr[FormatStr.size()-1] == '\n' &&
978 FormatStr.find('%') == std::string::npos) { // no format characters.
979 // Create a string literal with no \n on it. We expect the constant merge
980 // pass to be run after this pass, to merge duplicate strings.
981 FormatStr.erase(FormatStr.end()-1);
982 Constant *C = ConstantArray::get(FormatStr, true);
983 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
984 C, "str", Callee->getParent());
986 return CI->use_empty() ? (Value*)CI :
987 ConstantInt::get(CI->getType(), FormatStr.size()+1);
990 // Optimize specific format strings.
991 // printf("%c", chr) --> putchar(*(i8*)dst)
992 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
993 isa<IntegerType>(CI->getOperand(2)->getType())) {
994 EmitPutChar(CI->getOperand(2), B);
995 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
998 // printf("%s\n", str) --> puts(str)
999 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1000 isa<PointerType>(CI->getOperand(2)->getType()) &&
1002 EmitPutS(CI->getOperand(2), B);
1009 //===---------------------------------------===//
1010 // 'sprintf' Optimizations
1012 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1013 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1014 // Require two fixed pointer arguments and an integer result.
1015 const FunctionType *FT = Callee->getFunctionType();
1016 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1017 !isa<PointerType>(FT->getParamType(1)) ||
1018 !isa<IntegerType>(FT->getReturnType()))
1021 // Check for a fixed format string.
1022 std::string FormatStr;
1023 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1026 // If we just have a format string (nothing else crazy) transform it.
1027 if (CI->getNumOperands() == 3) {
1028 // Make sure there's no % in the constant array. We could try to handle
1029 // %% -> % in the future if we cared.
1030 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1031 if (FormatStr[i] == '%')
1032 return 0; // we found a format specifier, bail out.
1034 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1035 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1036 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1037 return ConstantInt::get(CI->getType(), FormatStr.size());
1040 // The remaining optimizations require the format string to be "%s" or "%c"
1041 // and have an extra operand.
1042 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1045 // Decode the second character of the format string.
1046 if (FormatStr[1] == 'c') {
1047 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1048 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1049 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1050 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1051 B.CreateStore(V, Ptr);
1052 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1053 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1055 return ConstantInt::get(CI->getType(), 1);
1058 if (FormatStr[1] == 's') {
1059 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1060 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1062 Value *Len = EmitStrLen(CI->getOperand(3), B);
1063 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1065 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1067 // The sprintf result is the unincremented number of bytes in the string.
1068 return B.CreateIntCast(Len, CI->getType(), false);
1074 //===---------------------------------------===//
1075 // 'fwrite' Optimizations
1077 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1078 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1079 // Require a pointer, an integer, an integer, a pointer, returning integer.
1080 const FunctionType *FT = Callee->getFunctionType();
1081 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1082 !isa<IntegerType>(FT->getParamType(1)) ||
1083 !isa<IntegerType>(FT->getParamType(2)) ||
1084 !isa<PointerType>(FT->getParamType(3)) ||
1085 !isa<IntegerType>(FT->getReturnType()))
1088 // Get the element size and count.
1089 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1090 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1091 if (!SizeC || !CountC) return 0;
1092 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1094 // If this is writing zero records, remove the call (it's a noop).
1096 return ConstantInt::get(CI->getType(), 0);
1098 // If this is writing one byte, turn it into fputc.
1099 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1100 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1101 EmitFPutC(Char, CI->getOperand(4), B);
1102 return ConstantInt::get(CI->getType(), 1);
1109 //===---------------------------------------===//
1110 // 'fputs' Optimizations
1112 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1113 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1114 // Require two pointers. Also, we can't optimize if return value is used.
1115 const FunctionType *FT = Callee->getFunctionType();
1116 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1117 !isa<PointerType>(FT->getParamType(1)) ||
1121 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1122 uint64_t Len = GetStringLength(CI->getOperand(1));
1124 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1125 CI->getOperand(2), B);
1126 return CI; // Known to have no uses (see above).
1130 //===---------------------------------------===//
1131 // 'fprintf' Optimizations
1133 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1134 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1135 // Require two fixed paramters as pointers and integer result.
1136 const FunctionType *FT = Callee->getFunctionType();
1137 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1138 !isa<PointerType>(FT->getParamType(1)) ||
1139 !isa<IntegerType>(FT->getReturnType()))
1142 // All the optimizations depend on the format string.
1143 std::string FormatStr;
1144 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1147 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1148 if (CI->getNumOperands() == 3) {
1149 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1150 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1151 return 0; // We found a format specifier.
1153 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1155 CI->getOperand(1), B);
1156 return ConstantInt::get(CI->getType(), FormatStr.size());
1159 // The remaining optimizations require the format string to be "%s" or "%c"
1160 // and have an extra operand.
1161 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1164 // Decode the second character of the format string.
1165 if (FormatStr[1] == 'c') {
1166 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1167 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1168 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1169 return ConstantInt::get(CI->getType(), 1);
1172 if (FormatStr[1] == 's') {
1173 // fprintf(F, "%s", str) -> fputs(str, F)
1174 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1176 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1183 } // end anonymous namespace.
1185 //===----------------------------------------------------------------------===//
1186 // SimplifyLibCalls Pass Implementation
1187 //===----------------------------------------------------------------------===//
1190 /// This pass optimizes well known library functions from libc and libm.
1192 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1193 StringMap<LibCallOptimization*> Optimizations;
1194 // Miscellaneous LibCall Optimizations
1196 // String and Memory LibCall Optimizations
1197 StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1198 StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt MemCpy;
1199 // Math Library Optimizations
1200 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1201 // Integer Optimizations
1202 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1204 // Formatting and IO Optimizations
1205 SPrintFOpt SPrintF; PrintFOpt PrintF;
1206 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1208 static char ID; // Pass identification
1209 SimplifyLibCalls() : FunctionPass(&ID) {}
1211 void InitOptimizations();
1212 bool runOnFunction(Function &F);
1214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1215 AU.addRequired<TargetData>();
1218 char SimplifyLibCalls::ID = 0;
1219 } // end anonymous namespace.
1221 static RegisterPass<SimplifyLibCalls>
1222 X("simplify-libcalls", "Simplify well-known library calls");
1224 // Public interface to the Simplify LibCalls pass.
1225 FunctionPass *llvm::createSimplifyLibCallsPass() {
1226 return new SimplifyLibCalls();
1229 /// Optimizations - Populate the Optimizations map with all the optimizations
1231 void SimplifyLibCalls::InitOptimizations() {
1232 // Miscellaneous LibCall Optimizations
1233 Optimizations["exit"] = &Exit;
1235 // String and Memory LibCall Optimizations
1236 Optimizations["strcat"] = &StrCat;
1237 Optimizations["strchr"] = &StrChr;
1238 Optimizations["strcmp"] = &StrCmp;
1239 Optimizations["strncmp"] = &StrNCmp;
1240 Optimizations["strcpy"] = &StrCpy;
1241 Optimizations["strlen"] = &StrLen;
1242 Optimizations["memcmp"] = &MemCmp;
1243 Optimizations["memcpy"] = &MemCpy;
1245 // Math Library Optimizations
1246 Optimizations["powf"] = &Pow;
1247 Optimizations["pow"] = &Pow;
1248 Optimizations["powl"] = &Pow;
1249 Optimizations["llvm.pow.f32"] = &Pow;
1250 Optimizations["llvm.pow.f64"] = &Pow;
1251 Optimizations["llvm.pow.f80"] = &Pow;
1252 Optimizations["llvm.pow.f128"] = &Pow;
1253 Optimizations["llvm.pow.ppcf128"] = &Pow;
1254 Optimizations["exp2l"] = &Exp2;
1255 Optimizations["exp2"] = &Exp2;
1256 Optimizations["exp2f"] = &Exp2;
1257 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1258 Optimizations["llvm.exp2.f128"] = &Exp2;
1259 Optimizations["llvm.exp2.f80"] = &Exp2;
1260 Optimizations["llvm.exp2.f64"] = &Exp2;
1261 Optimizations["llvm.exp2.f32"] = &Exp2;
1264 Optimizations["floor"] = &UnaryDoubleFP;
1267 Optimizations["ceil"] = &UnaryDoubleFP;
1270 Optimizations["round"] = &UnaryDoubleFP;
1273 Optimizations["rint"] = &UnaryDoubleFP;
1275 #ifdef HAVE_NEARBYINTF
1276 Optimizations["nearbyint"] = &UnaryDoubleFP;
1279 // Integer Optimizations
1280 Optimizations["ffs"] = &FFS;
1281 Optimizations["ffsl"] = &FFS;
1282 Optimizations["ffsll"] = &FFS;
1283 Optimizations["abs"] = &Abs;
1284 Optimizations["labs"] = &Abs;
1285 Optimizations["llabs"] = &Abs;
1286 Optimizations["isdigit"] = &IsDigit;
1287 Optimizations["isascii"] = &IsAscii;
1288 Optimizations["toascii"] = &ToAscii;
1290 // Formatting and IO Optimizations
1291 Optimizations["sprintf"] = &SPrintF;
1292 Optimizations["printf"] = &PrintF;
1293 Optimizations["fwrite"] = &FWrite;
1294 Optimizations["fputs"] = &FPuts;
1295 Optimizations["fprintf"] = &FPrintF;
1299 /// runOnFunction - Top level algorithm.
1301 bool SimplifyLibCalls::runOnFunction(Function &F) {
1302 if (Optimizations.empty())
1303 InitOptimizations();
1305 const TargetData &TD = getAnalysis<TargetData>();
1307 IRBuilder<> Builder;
1309 bool Changed = false;
1310 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1311 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1312 // Ignore non-calls.
1313 CallInst *CI = dyn_cast<CallInst>(I++);
1316 // Ignore indirect calls and calls to non-external functions.
1317 Function *Callee = CI->getCalledFunction();
1318 if (Callee == 0 || !Callee->isDeclaration() ||
1319 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1322 // Ignore unknown calls.
1323 const char *CalleeName = Callee->getNameStart();
1324 StringMap<LibCallOptimization*>::iterator OMI =
1325 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1326 if (OMI == Optimizations.end()) continue;
1328 // Set the builder to the instruction after the call.
1329 Builder.SetInsertPoint(BB, I);
1331 // Try to optimize this call.
1332 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1333 if (Result == 0) continue;
1335 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1336 DOUT << " into: " << *Result << "\n");
1338 // Something changed!
1342 // Inspect the instruction after the call (which was potentially just
1346 if (CI != Result && !CI->use_empty()) {
1347 CI->replaceAllUsesWith(Result);
1348 if (!Result->hasName())
1349 Result->takeName(CI);
1351 CI->eraseFromParent();
1359 // Additional cases that we need to add to this file:
1362 // * cbrt(expN(X)) -> expN(x/3)
1363 // * cbrt(sqrt(x)) -> pow(x,1/6)
1364 // * cbrt(sqrt(x)) -> pow(x,1/9)
1367 // * cos(-x) -> cos(x)
1370 // * exp(log(x)) -> x
1373 // * log(exp(x)) -> x
1374 // * log(x**y) -> y*log(x)
1375 // * log(exp(y)) -> y*log(e)
1376 // * log(exp2(y)) -> y*log(2)
1377 // * log(exp10(y)) -> y*log(10)
1378 // * log(sqrt(x)) -> 0.5*log(x)
1379 // * log(pow(x,y)) -> y*log(x)
1381 // lround, lroundf, lroundl:
1382 // * lround(cnst) -> cnst'
1385 // * memcmp(x,y,l) -> cnst
1386 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1389 // * memmove(d,s,l,a) -> memcpy(d,s,l,a)
1390 // (if s is a global constant array)
1393 // * pow(exp(x),y) -> exp(x*y)
1394 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1395 // * pow(pow(x,y),z)-> pow(x,y*z)
1398 // * puts("") -> putchar("\n")
1400 // round, roundf, roundl:
1401 // * round(cnst) -> cnst'
1404 // * signbit(cnst) -> cnst'
1405 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1407 // sqrt, sqrtf, sqrtl:
1408 // * sqrt(expN(x)) -> expN(x*0.5)
1409 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1410 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1413 // * stpcpy(str, "literal") ->
1414 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
1416 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1417 // (if c is a constant integer and s is a constant string)
1418 // * strrchr(s1,0) -> strchr(s1,0)
1421 // * strncat(x,y,0) -> x
1422 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1423 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1426 // * strncpy(d,s,0) -> d
1427 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1428 // (if s and l are constants)
1431 // * strpbrk(s,a) -> offset_in_for(s,a)
1432 // (if s and a are both constant strings)
1433 // * strpbrk(s,"") -> 0
1434 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1437 // * strspn(s,a) -> const_int (if both args are constant)
1438 // * strspn("",a) -> 0
1439 // * strspn(s,"") -> 0
1440 // * strcspn(s,a) -> const_int (if both args are constant)
1441 // * strcspn("",a) -> 0
1442 // * strcspn(s,"") -> strlen(a)
1445 // * strstr(x,x) -> x
1446 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1447 // (if s1 and s2 are constant strings)
1450 // * tan(atan(x)) -> x
1452 // trunc, truncf, truncl:
1453 // * trunc(cnst) -> cnst'