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 = Intrinsic::memcpy;
135 Tys[0] = Len->getType();
136 Value *MemCpy = Intrinsic::getDeclaration(M, IID, Tys, 1);
137 return B.CreateCall4(MemCpy, CastToCStr(Dst, B), CastToCStr(Src, B), Len,
138 ConstantInt::get(Type::Int32Ty, Align));
141 /// EmitMemChr - Emit a call to the memchr function. This assumes that Ptr is
142 /// a pointer, Val is an i32 value, and Len is an 'intptr_t' value.
143 Value *LibCallOptimization::EmitMemChr(Value *Ptr, Value *Val,
144 Value *Len, IRBuilder<> &B) {
145 Module *M = Caller->getParent();
146 Value *MemChr = M->getOrInsertFunction("memchr",
147 PointerType::getUnqual(Type::Int8Ty),
148 PointerType::getUnqual(Type::Int8Ty),
149 Type::Int32Ty, TD->getIntPtrType(),
151 return B.CreateCall3(MemChr, CastToCStr(Ptr, B), Val, Len, "memchr");
154 /// EmitUnaryFloatFnCall - Emit a call to the unary function named 'Name' (e.g.
155 /// 'floor'). This function is known to take a single of type matching 'Op' and
156 /// returns one value with the same type. If 'Op' is a long double, 'l' is
157 /// added as the suffix of name, if 'Op' is a float, we add a 'f' suffix.
158 Value *LibCallOptimization::EmitUnaryFloatFnCall(Value *Op, const char *Name,
161 if (Op->getType() != Type::DoubleTy) {
162 // If we need to add a suffix, copy into NameBuffer.
163 unsigned NameLen = strlen(Name);
164 assert(NameLen < sizeof(NameBuffer)-2);
165 memcpy(NameBuffer, Name, NameLen);
166 if (Op->getType() == Type::FloatTy)
167 NameBuffer[NameLen] = 'f'; // floorf
169 NameBuffer[NameLen] = 'l'; // floorl
170 NameBuffer[NameLen+1] = 0;
174 Module *M = Caller->getParent();
175 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
176 Op->getType(), NULL);
177 return B.CreateCall(Callee, Op, Name);
180 /// EmitPutChar - Emit a call to the putchar function. This assumes that Char
182 void LibCallOptimization::EmitPutChar(Value *Char, IRBuilder<> &B) {
183 Module *M = Caller->getParent();
184 Value *F = M->getOrInsertFunction("putchar", Type::Int32Ty,
185 Type::Int32Ty, NULL);
186 B.CreateCall(F, B.CreateIntCast(Char, Type::Int32Ty, "chari"), "putchar");
189 /// EmitPutS - Emit a call to the puts function. This assumes that Str is
191 void LibCallOptimization::EmitPutS(Value *Str, IRBuilder<> &B) {
192 Module *M = Caller->getParent();
193 Value *F = M->getOrInsertFunction("puts", Type::Int32Ty,
194 PointerType::getUnqual(Type::Int8Ty), NULL);
195 B.CreateCall(F, CastToCStr(Str, B), "puts");
198 /// EmitFPutC - Emit a call to the fputc function. This assumes that Char is
199 /// an integer and File is a pointer to FILE.
200 void LibCallOptimization::EmitFPutC(Value *Char, Value *File, IRBuilder<> &B) {
201 Module *M = Caller->getParent();
202 Constant *F = M->getOrInsertFunction("fputc", Type::Int32Ty, Type::Int32Ty,
203 File->getType(), NULL);
204 Char = B.CreateIntCast(Char, Type::Int32Ty, "chari");
205 B.CreateCall2(F, Char, File, "fputc");
208 /// EmitFPutS - Emit a call to the puts function. Str is required to be a
209 /// pointer and File is a pointer to FILE.
210 void LibCallOptimization::EmitFPutS(Value *Str, Value *File, IRBuilder<> &B) {
211 Module *M = Caller->getParent();
212 Constant *F = M->getOrInsertFunction("fputs", Type::Int32Ty,
213 PointerType::getUnqual(Type::Int8Ty),
214 File->getType(), NULL);
215 B.CreateCall2(F, CastToCStr(Str, B), File, "fputs");
218 /// EmitFWrite - Emit a call to the fwrite function. This assumes that Ptr is
219 /// a pointer, Size is an 'intptr_t', and File is a pointer to FILE.
220 void LibCallOptimization::EmitFWrite(Value *Ptr, Value *Size, Value *File,
222 Module *M = Caller->getParent();
223 Constant *F = M->getOrInsertFunction("fwrite", TD->getIntPtrType(),
224 PointerType::getUnqual(Type::Int8Ty),
225 TD->getIntPtrType(), TD->getIntPtrType(),
226 File->getType(), NULL);
227 B.CreateCall4(F, CastToCStr(Ptr, B), Size,
228 ConstantInt::get(TD->getIntPtrType(), 1), File);
231 //===----------------------------------------------------------------------===//
233 //===----------------------------------------------------------------------===//
235 /// GetStringLengthH - If we can compute the length of the string pointed to by
236 /// the specified pointer, return 'len+1'. If we can't, return 0.
237 static uint64_t GetStringLengthH(Value *V, SmallPtrSet<PHINode*, 32> &PHIs) {
238 // Look through noop bitcast instructions.
239 if (BitCastInst *BCI = dyn_cast<BitCastInst>(V))
240 return GetStringLengthH(BCI->getOperand(0), PHIs);
242 // If this is a PHI node, there are two cases: either we have already seen it
244 if (PHINode *PN = dyn_cast<PHINode>(V)) {
245 if (!PHIs.insert(PN))
246 return ~0ULL; // already in the set.
248 // If it was new, see if all the input strings are the same length.
249 uint64_t LenSoFar = ~0ULL;
250 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
251 uint64_t Len = GetStringLengthH(PN->getIncomingValue(i), PHIs);
252 if (Len == 0) return 0; // Unknown length -> unknown.
254 if (Len == ~0ULL) continue;
256 if (Len != LenSoFar && LenSoFar != ~0ULL)
257 return 0; // Disagree -> unknown.
261 // Success, all agree.
265 // strlen(select(c,x,y)) -> strlen(x) ^ strlen(y)
266 if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
267 uint64_t Len1 = GetStringLengthH(SI->getTrueValue(), PHIs);
268 if (Len1 == 0) return 0;
269 uint64_t Len2 = GetStringLengthH(SI->getFalseValue(), PHIs);
270 if (Len2 == 0) return 0;
271 if (Len1 == ~0ULL) return Len2;
272 if (Len2 == ~0ULL) return Len1;
273 if (Len1 != Len2) return 0;
277 // If the value is not a GEP instruction nor a constant expression with a
278 // GEP instruction, then return unknown.
280 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(V)) {
282 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
283 if (CE->getOpcode() != Instruction::GetElementPtr)
290 // Make sure the GEP has exactly three arguments.
291 if (GEP->getNumOperands() != 3)
294 // Check to make sure that the first operand of the GEP is an integer and
295 // has value 0 so that we are sure we're indexing into the initializer.
296 if (ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(1))) {
302 // If the second index isn't a ConstantInt, then this is a variable index
303 // into the array. If this occurs, we can't say anything meaningful about
305 uint64_t StartIdx = 0;
306 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(2)))
307 StartIdx = CI->getZExtValue();
311 // The GEP instruction, constant or instruction, must reference a global
312 // variable that is a constant and is initialized. The referenced constant
313 // initializer is the array that we'll use for optimization.
314 GlobalVariable* GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
315 if (!GV || !GV->isConstant() || !GV->hasInitializer())
317 Constant *GlobalInit = GV->getInitializer();
319 // Handle the ConstantAggregateZero case, which is a degenerate case. The
320 // initializer is constant zero so the length of the string must be zero.
321 if (isa<ConstantAggregateZero>(GlobalInit))
322 return 1; // Len = 0 offset by 1.
324 // Must be a Constant Array
325 ConstantArray *Array = dyn_cast<ConstantArray>(GlobalInit);
326 if (!Array || Array->getType()->getElementType() != Type::Int8Ty)
329 // Get the number of elements in the array
330 uint64_t NumElts = Array->getType()->getNumElements();
332 // Traverse the constant array from StartIdx (derived above) which is
333 // the place the GEP refers to in the array.
334 for (unsigned i = StartIdx; i != NumElts; ++i) {
335 Constant *Elt = Array->getOperand(i);
336 ConstantInt *CI = dyn_cast<ConstantInt>(Elt);
337 if (!CI) // This array isn't suitable, non-int initializer.
340 return i-StartIdx+1; // We found end of string, success!
343 return 0; // The array isn't null terminated, conservatively return 'unknown'.
346 /// GetStringLength - If we can compute the length of the string pointed to by
347 /// the specified pointer, return 'len+1'. If we can't, return 0.
348 static uint64_t GetStringLength(Value *V) {
349 if (!isa<PointerType>(V->getType())) return 0;
351 SmallPtrSet<PHINode*, 32> PHIs;
352 uint64_t Len = GetStringLengthH(V, PHIs);
353 // If Len is ~0ULL, we had an infinite phi cycle: this is dead code, so return
354 // an empty string as a length.
355 return Len == ~0ULL ? 1 : Len;
358 /// IsOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
359 /// value is equal or not-equal to zero.
360 static bool IsOnlyUsedInZeroEqualityComparison(Value *V) {
361 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
363 if (ICmpInst *IC = dyn_cast<ICmpInst>(*UI))
364 if (IC->isEquality())
365 if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
366 if (C->isNullValue())
368 // Unknown instruction.
374 //===----------------------------------------------------------------------===//
375 // Miscellaneous LibCall Optimizations
376 //===----------------------------------------------------------------------===//
379 //===---------------------------------------===//
380 // 'exit' Optimizations
382 /// ExitOpt - int main() { exit(4); } --> int main() { return 4; }
383 struct VISIBILITY_HIDDEN ExitOpt : public LibCallOptimization {
384 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
385 // Verify we have a reasonable prototype for exit.
386 if (Callee->arg_size() == 0 || !CI->use_empty())
389 // Verify the caller is main, and that the result type of main matches the
390 // argument type of exit.
391 if (!Caller->isName("main") || !Caller->hasExternalLinkage() ||
392 Caller->getReturnType() != CI->getOperand(1)->getType())
395 TerminatorInst *OldTI = CI->getParent()->getTerminator();
397 // Create the return after the call.
398 ReturnInst *RI = B.CreateRet(CI->getOperand(1));
400 // Drop all successor phi node entries.
401 for (unsigned i = 0, e = OldTI->getNumSuccessors(); i != e; ++i)
402 OldTI->getSuccessor(i)->removePredecessor(CI->getParent());
404 // Erase all instructions from after our return instruction until the end of
406 BasicBlock::iterator FirstDead = RI; ++FirstDead;
407 CI->getParent()->getInstList().erase(FirstDead, CI->getParent()->end());
412 //===----------------------------------------------------------------------===//
413 // String and Memory LibCall Optimizations
414 //===----------------------------------------------------------------------===//
416 //===---------------------------------------===//
417 // 'strcat' Optimizations
419 struct VISIBILITY_HIDDEN StrCatOpt : public LibCallOptimization {
420 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
421 // Verify the "strcat" function prototype.
422 const FunctionType *FT = Callee->getFunctionType();
423 if (FT->getNumParams() != 2 ||
424 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
425 FT->getParamType(0) != FT->getReturnType() ||
426 FT->getParamType(1) != FT->getReturnType())
429 // Extract some information from the instruction
430 Value *Dst = CI->getOperand(1);
431 Value *Src = CI->getOperand(2);
433 // See if we can get the length of the input string.
434 uint64_t Len = GetStringLength(Src);
435 if (Len == 0) return 0;
436 --Len; // Unbias length.
438 // Handle the simple, do-nothing case: strcat(x, "") -> x
442 // We need to find the end of the destination string. That's where the
443 // memory is to be moved to. We just generate a call to strlen.
444 Value *DstLen = EmitStrLen(Dst, B);
446 // Now that we have the destination's length, we must index into the
447 // destination's pointer to get the actual memcpy destination (end of
448 // the string .. we're concatenating).
449 Dst = B.CreateGEP(Dst, DstLen, "endptr");
451 // We have enough information to now generate the memcpy call to do the
452 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
453 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len+1), 1, B);
458 //===---------------------------------------===//
459 // 'strchr' Optimizations
461 struct VISIBILITY_HIDDEN StrChrOpt : public LibCallOptimization {
462 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
463 // Verify the "strchr" function prototype.
464 const FunctionType *FT = Callee->getFunctionType();
465 if (FT->getNumParams() != 2 ||
466 FT->getReturnType() != PointerType::getUnqual(Type::Int8Ty) ||
467 FT->getParamType(0) != FT->getReturnType())
470 Value *SrcStr = CI->getOperand(1);
472 // If the second operand is non-constant, see if we can compute the length
473 // of the input string and turn this into memchr.
474 ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getOperand(2));
476 uint64_t Len = GetStringLength(SrcStr);
477 if (Len == 0 || FT->getParamType(1) != Type::Int32Ty) // memchr needs i32.
480 return EmitMemChr(SrcStr, CI->getOperand(2), // include nul.
481 ConstantInt::get(TD->getIntPtrType(), Len), B);
484 // Otherwise, the character is a constant, see if the first argument is
485 // a string literal. If so, we can constant fold.
487 if (!GetConstantStringInfo(SrcStr, Str))
490 // strchr can find the nul character.
492 char CharValue = CharC->getSExtValue();
494 // Compute the offset.
497 if (i == Str.size()) // Didn't find the char. strchr returns null.
498 return Constant::getNullValue(CI->getType());
499 // Did we find our match?
500 if (Str[i] == CharValue)
505 // strchr(s+n,c) -> gep(s+n+i,c)
506 Value *Idx = ConstantInt::get(Type::Int64Ty, i);
507 return B.CreateGEP(SrcStr, Idx, "strchr");
511 //===---------------------------------------===//
512 // 'strcmp' Optimizations
514 struct VISIBILITY_HIDDEN StrCmpOpt : public LibCallOptimization {
515 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
516 // Verify the "strcmp" function prototype.
517 const FunctionType *FT = Callee->getFunctionType();
518 if (FT->getNumParams() != 2 || FT->getReturnType() != Type::Int32Ty ||
519 FT->getParamType(0) != FT->getParamType(1) ||
520 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
523 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
524 if (Str1P == Str2P) // strcmp(x,x) -> 0
525 return ConstantInt::get(CI->getType(), 0);
527 std::string Str1, Str2;
528 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
529 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
531 if (HasStr1 && Str1.empty()) // strcmp("", x) -> *x
532 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
534 if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
535 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
537 // strcmp(x, y) -> cnst (if both x and y are constant strings)
538 if (HasStr1 && HasStr2)
539 return ConstantInt::get(CI->getType(), strcmp(Str1.c_str(),Str2.c_str()));
544 //===---------------------------------------===//
545 // 'strncmp' Optimizations
547 struct VISIBILITY_HIDDEN StrNCmpOpt : public LibCallOptimization {
548 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
549 // Verify the "strncmp" function prototype.
550 const FunctionType *FT = Callee->getFunctionType();
551 if (FT->getNumParams() != 3 || FT->getReturnType() != Type::Int32Ty ||
552 FT->getParamType(0) != FT->getParamType(1) ||
553 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
554 !isa<IntegerType>(FT->getParamType(2)))
557 Value *Str1P = CI->getOperand(1), *Str2P = CI->getOperand(2);
558 if (Str1P == Str2P) // strncmp(x,x,n) -> 0
559 return ConstantInt::get(CI->getType(), 0);
561 // Get the length argument if it is constant.
563 if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getOperand(3)))
564 Length = LengthArg->getZExtValue();
568 if (Length == 0) // strncmp(x,y,0) -> 0
569 return ConstantInt::get(CI->getType(), 0);
571 std::string Str1, Str2;
572 bool HasStr1 = GetConstantStringInfo(Str1P, Str1);
573 bool HasStr2 = GetConstantStringInfo(Str2P, Str2);
575 if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> *x
576 return B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType());
578 if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
579 return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
581 // strncmp(x, y) -> cnst (if both x and y are constant strings)
582 if (HasStr1 && HasStr2)
583 return ConstantInt::get(CI->getType(),
584 strncmp(Str1.c_str(), Str2.c_str(), Length));
590 //===---------------------------------------===//
591 // 'strcpy' Optimizations
593 struct VISIBILITY_HIDDEN StrCpyOpt : public LibCallOptimization {
594 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
595 // Verify the "strcpy" function prototype.
596 const FunctionType *FT = Callee->getFunctionType();
597 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
598 FT->getParamType(0) != FT->getParamType(1) ||
599 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty))
602 Value *Dst = CI->getOperand(1), *Src = CI->getOperand(2);
603 if (Dst == Src) // strcpy(x,x) -> x
606 // See if we can get the length of the input string.
607 uint64_t Len = GetStringLength(Src);
608 if (Len == 0) return 0;
610 // We have enough information to now generate the memcpy call to do the
611 // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
612 EmitMemCpy(Dst, Src, ConstantInt::get(TD->getIntPtrType(), Len), 1, B);
619 //===---------------------------------------===//
620 // 'strlen' Optimizations
622 struct VISIBILITY_HIDDEN StrLenOpt : public LibCallOptimization {
623 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
624 const FunctionType *FT = Callee->getFunctionType();
625 if (FT->getNumParams() != 1 ||
626 FT->getParamType(0) != PointerType::getUnqual(Type::Int8Ty) ||
627 !isa<IntegerType>(FT->getReturnType()))
630 Value *Src = CI->getOperand(1);
632 // Constant folding: strlen("xyz") -> 3
633 if (uint64_t Len = GetStringLength(Src))
634 return ConstantInt::get(CI->getType(), Len-1);
636 // Handle strlen(p) != 0.
637 if (!IsOnlyUsedInZeroEqualityComparison(CI)) return 0;
639 // strlen(x) != 0 --> *x != 0
640 // strlen(x) == 0 --> *x == 0
641 return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
645 //===---------------------------------------===//
646 // 'memcmp' Optimizations
648 struct VISIBILITY_HIDDEN MemCmpOpt : public LibCallOptimization {
649 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
650 const FunctionType *FT = Callee->getFunctionType();
651 if (FT->getNumParams() != 3 || !isa<PointerType>(FT->getParamType(0)) ||
652 !isa<PointerType>(FT->getParamType(1)) ||
653 FT->getReturnType() != Type::Int32Ty)
656 Value *LHS = CI->getOperand(1), *RHS = CI->getOperand(2);
658 if (LHS == RHS) // memcmp(s,s,x) -> 0
659 return Constant::getNullValue(CI->getType());
661 // Make sure we have a constant length.
662 ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getOperand(3));
664 uint64_t Len = LenC->getZExtValue();
666 if (Len == 0) // memcmp(s1,s2,0) -> 0
667 return Constant::getNullValue(CI->getType());
669 if (Len == 1) { // memcmp(S1,S2,1) -> *LHS - *RHS
670 Value *LHSV = B.CreateLoad(CastToCStr(LHS, B), "lhsv");
671 Value *RHSV = B.CreateLoad(CastToCStr(RHS, B), "rhsv");
672 return B.CreateZExt(B.CreateSub(LHSV, RHSV, "chardiff"), CI->getType());
675 // memcmp(S1,S2,2) != 0 -> (*(short*)LHS ^ *(short*)RHS) != 0
676 // memcmp(S1,S2,4) != 0 -> (*(int*)LHS ^ *(int*)RHS) != 0
677 if ((Len == 2 || Len == 4) && IsOnlyUsedInZeroEqualityComparison(CI)) {
678 const Type *PTy = PointerType::getUnqual(Len == 2 ?
679 Type::Int16Ty : Type::Int32Ty);
680 LHS = B.CreateBitCast(LHS, PTy, "tmp");
681 RHS = B.CreateBitCast(RHS, PTy, "tmp");
682 LoadInst *LHSV = B.CreateLoad(LHS, "lhsv");
683 LoadInst *RHSV = B.CreateLoad(RHS, "rhsv");
684 LHSV->setAlignment(1); RHSV->setAlignment(1); // Unaligned loads.
685 return B.CreateZExt(B.CreateXor(LHSV, RHSV, "shortdiff"), CI->getType());
692 //===---------------------------------------===//
693 // 'memcpy' Optimizations
695 struct VISIBILITY_HIDDEN MemCpyOpt : public LibCallOptimization {
696 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
697 const FunctionType *FT = Callee->getFunctionType();
698 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
699 !isa<PointerType>(FT->getParamType(0)) ||
700 !isa<PointerType>(FT->getParamType(1)) ||
701 FT->getParamType(2) != TD->getIntPtrType())
704 // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
705 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), CI->getOperand(3), 1, B);
706 return CI->getOperand(1);
710 //===---------------------------------------===//
711 // 'memmove' Optimizations
713 struct VISIBILITY_HIDDEN MemMoveOpt : public LibCallOptimization {
714 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
715 const FunctionType *FT = Callee->getFunctionType();
716 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
717 !isa<PointerType>(FT->getParamType(0)) ||
718 !isa<PointerType>(FT->getParamType(1)) ||
719 FT->getParamType(2) != TD->getIntPtrType())
722 // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
723 Module *M = Caller->getParent();
724 Intrinsic::ID IID = Intrinsic::memmove;
726 Tys[0] = TD->getIntPtrType();
727 Value *MemMove = Intrinsic::getDeclaration(M, IID, Tys, 1);
728 Value *Dst = CastToCStr(CI->getOperand(1), B);
729 Value *Src = CastToCStr(CI->getOperand(2), B);
730 Value *Size = CI->getOperand(3);
731 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
732 B.CreateCall4(MemMove, Dst, Src, Size, Align);
733 return CI->getOperand(1);
737 //===---------------------------------------===//
738 // 'memset' Optimizations
740 struct VISIBILITY_HIDDEN MemSetOpt : public LibCallOptimization {
741 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
742 const FunctionType *FT = Callee->getFunctionType();
743 if (FT->getNumParams() != 3 || FT->getReturnType() != FT->getParamType(0) ||
744 !isa<PointerType>(FT->getParamType(0)) ||
745 FT->getParamType(1) != TD->getIntPtrType() ||
746 FT->getParamType(2) != TD->getIntPtrType())
749 // memset(p, v, n) -> llvm.memset(p, v, n, 1)
750 Module *M = Caller->getParent();
751 Intrinsic::ID IID = Intrinsic::memset;
753 Tys[0] = TD->getIntPtrType();
754 Value *MemSet = Intrinsic::getDeclaration(M, IID, Tys, 1);
755 Value *Dst = CastToCStr(CI->getOperand(1), B);
756 Value *Val = B.CreateTrunc(CI->getOperand(2), Type::Int8Ty);
757 Value *Size = CI->getOperand(3);
758 Value *Align = ConstantInt::get(Type::Int32Ty, 1);
759 B.CreateCall4(MemSet, Dst, Val, Size, Align);
760 return CI->getOperand(1);
764 //===----------------------------------------------------------------------===//
765 // Math Library Optimizations
766 //===----------------------------------------------------------------------===//
768 //===---------------------------------------===//
769 // 'pow*' Optimizations
771 struct VISIBILITY_HIDDEN PowOpt : public LibCallOptimization {
772 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
773 const FunctionType *FT = Callee->getFunctionType();
774 // Just make sure this has 2 arguments of the same FP type, which match the
776 if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
777 FT->getParamType(0) != FT->getParamType(1) ||
778 !FT->getParamType(0)->isFloatingPoint())
781 Value *Op1 = CI->getOperand(1), *Op2 = CI->getOperand(2);
782 if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
783 if (Op1C->isExactlyValue(1.0)) // pow(1.0, x) -> 1.0
785 if (Op1C->isExactlyValue(2.0)) // pow(2.0, x) -> exp2(x)
786 return EmitUnaryFloatFnCall(Op2, "exp2", B);
789 ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
790 if (Op2C == 0) return 0;
792 if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
793 return ConstantFP::get(CI->getType(), 1.0);
795 if (Op2C->isExactlyValue(0.5)) {
796 // FIXME: This is not safe for -0.0 and -inf. This can only be done when
797 // 'unsafe' math optimizations are allowed.
798 // x pow(x, 0.5) sqrt(x)
799 // ---------------------------------------------
803 // pow(x, 0.5) -> sqrt(x)
804 return B.CreateCall(get_sqrt(), Op1, "sqrt");
808 if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
810 if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
811 return B.CreateMul(Op1, Op1, "pow2");
812 if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
813 return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
818 //===---------------------------------------===//
819 // 'exp2' Optimizations
821 struct VISIBILITY_HIDDEN Exp2Opt : public LibCallOptimization {
822 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
823 const FunctionType *FT = Callee->getFunctionType();
824 // Just make sure this has 1 argument of FP type, which matches the
826 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
827 !FT->getParamType(0)->isFloatingPoint())
830 Value *Op = CI->getOperand(1);
831 // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
832 // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
834 if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
835 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
836 LdExpArg = B.CreateSExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
837 } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
838 if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
839 LdExpArg = B.CreateZExt(OpC->getOperand(0), Type::Int32Ty, "tmp");
844 if (Op->getType() == Type::FloatTy)
846 else if (Op->getType() == Type::DoubleTy)
851 Constant *One = ConstantFP::get(APFloat(1.0f));
852 if (Op->getType() != Type::FloatTy)
853 One = ConstantExpr::getFPExtend(One, Op->getType());
855 Module *M = Caller->getParent();
856 Value *Callee = M->getOrInsertFunction(Name, Op->getType(),
857 Op->getType(), Type::Int32Ty,NULL);
858 return B.CreateCall2(Callee, One, LdExpArg);
865 //===---------------------------------------===//
866 // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
868 struct VISIBILITY_HIDDEN UnaryDoubleFPOpt : public LibCallOptimization {
869 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
870 const FunctionType *FT = Callee->getFunctionType();
871 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::DoubleTy ||
872 FT->getParamType(0) != Type::DoubleTy)
875 // If this is something like 'floor((double)floatval)', convert to floorf.
876 FPExtInst *Cast = dyn_cast<FPExtInst>(CI->getOperand(1));
877 if (Cast == 0 || Cast->getOperand(0)->getType() != Type::FloatTy)
880 // floor((double)floatval) -> (double)floorf(floatval)
881 Value *V = Cast->getOperand(0);
882 V = EmitUnaryFloatFnCall(V, Callee->getNameStart(), B);
883 return B.CreateFPExt(V, Type::DoubleTy);
887 //===----------------------------------------------------------------------===//
888 // Integer Optimizations
889 //===----------------------------------------------------------------------===//
891 //===---------------------------------------===//
892 // 'ffs*' Optimizations
894 struct VISIBILITY_HIDDEN FFSOpt : public LibCallOptimization {
895 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
896 const FunctionType *FT = Callee->getFunctionType();
897 // Just make sure this has 2 arguments of the same FP type, which match the
899 if (FT->getNumParams() != 1 || FT->getReturnType() != Type::Int32Ty ||
900 !isa<IntegerType>(FT->getParamType(0)))
903 Value *Op = CI->getOperand(1);
906 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
907 if (CI->getValue() == 0) // ffs(0) -> 0.
908 return Constant::getNullValue(CI->getType());
909 return ConstantInt::get(Type::Int32Ty, // ffs(c) -> cttz(c)+1
910 CI->getValue().countTrailingZeros()+1);
913 // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
914 const Type *ArgType = Op->getType();
915 Value *F = Intrinsic::getDeclaration(Callee->getParent(),
916 Intrinsic::cttz, &ArgType, 1);
917 Value *V = B.CreateCall(F, Op, "cttz");
918 V = B.CreateAdd(V, ConstantInt::get(Type::Int32Ty, 1), "tmp");
919 V = B.CreateIntCast(V, Type::Int32Ty, false, "tmp");
921 Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType), "tmp");
922 return B.CreateSelect(Cond, V, ConstantInt::get(Type::Int32Ty, 0));
926 //===---------------------------------------===//
927 // 'isdigit' Optimizations
929 struct VISIBILITY_HIDDEN IsDigitOpt : public LibCallOptimization {
930 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
931 const FunctionType *FT = Callee->getFunctionType();
932 // We require integer(i32)
933 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
934 FT->getParamType(0) != Type::Int32Ty)
937 // isdigit(c) -> (c-'0') <u 10
938 Value *Op = CI->getOperand(1);
939 Op = B.CreateSub(Op, ConstantInt::get(Type::Int32Ty, '0'), "isdigittmp");
940 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 10), "isdigit");
941 return B.CreateZExt(Op, CI->getType());
945 //===---------------------------------------===//
946 // 'isascii' Optimizations
948 struct VISIBILITY_HIDDEN IsAsciiOpt : public LibCallOptimization {
949 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
950 const FunctionType *FT = Callee->getFunctionType();
951 // We require integer(i32)
952 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
953 FT->getParamType(0) != Type::Int32Ty)
956 // isascii(c) -> c <u 128
957 Value *Op = CI->getOperand(1);
958 Op = B.CreateICmpULT(Op, ConstantInt::get(Type::Int32Ty, 128), "isascii");
959 return B.CreateZExt(Op, CI->getType());
963 //===---------------------------------------===//
964 // 'abs', 'labs', 'llabs' Optimizations
966 struct VISIBILITY_HIDDEN AbsOpt : public LibCallOptimization {
967 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
968 const FunctionType *FT = Callee->getFunctionType();
969 // We require integer(integer) where the types agree.
970 if (FT->getNumParams() != 1 || !isa<IntegerType>(FT->getReturnType()) ||
971 FT->getParamType(0) != FT->getReturnType())
974 // abs(x) -> x >s -1 ? x : -x
975 Value *Op = CI->getOperand(1);
976 Value *Pos = B.CreateICmpSGT(Op,ConstantInt::getAllOnesValue(Op->getType()),
978 Value *Neg = B.CreateNeg(Op, "neg");
979 return B.CreateSelect(Pos, Op, Neg);
984 //===---------------------------------------===//
985 // 'toascii' Optimizations
987 struct VISIBILITY_HIDDEN ToAsciiOpt : public LibCallOptimization {
988 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
989 const FunctionType *FT = Callee->getFunctionType();
990 // We require i32(i32)
991 if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
992 FT->getParamType(0) != Type::Int32Ty)
995 // isascii(c) -> c & 0x7f
996 return B.CreateAnd(CI->getOperand(1), ConstantInt::get(CI->getType(),0x7F));
1000 //===----------------------------------------------------------------------===//
1001 // Formatting and IO Optimizations
1002 //===----------------------------------------------------------------------===//
1004 //===---------------------------------------===//
1005 // 'printf' Optimizations
1007 struct VISIBILITY_HIDDEN PrintFOpt : public LibCallOptimization {
1008 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1009 // Require one fixed pointer argument and an integer/void result.
1010 const FunctionType *FT = Callee->getFunctionType();
1011 if (FT->getNumParams() < 1 || !isa<PointerType>(FT->getParamType(0)) ||
1012 !(isa<IntegerType>(FT->getReturnType()) ||
1013 FT->getReturnType() == Type::VoidTy))
1016 // Check for a fixed format string.
1017 std::string FormatStr;
1018 if (!GetConstantStringInfo(CI->getOperand(1), FormatStr))
1021 // Empty format string -> noop.
1022 if (FormatStr.empty()) // Tolerate printf's declared void.
1023 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 0);
1025 // printf("x") -> putchar('x'), even for '%'.
1026 if (FormatStr.size() == 1) {
1027 EmitPutChar(ConstantInt::get(Type::Int32Ty, FormatStr[0]), B);
1028 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1031 // printf("foo\n") --> puts("foo")
1032 if (FormatStr[FormatStr.size()-1] == '\n' &&
1033 FormatStr.find('%') == std::string::npos) { // no format characters.
1034 // Create a string literal with no \n on it. We expect the constant merge
1035 // pass to be run after this pass, to merge duplicate strings.
1036 FormatStr.erase(FormatStr.end()-1);
1037 Constant *C = ConstantArray::get(FormatStr, true);
1038 C = new GlobalVariable(C->getType(), true,GlobalVariable::InternalLinkage,
1039 C, "str", Callee->getParent());
1041 return CI->use_empty() ? (Value*)CI :
1042 ConstantInt::get(CI->getType(), FormatStr.size()+1);
1045 // Optimize specific format strings.
1046 // printf("%c", chr) --> putchar(*(i8*)dst)
1047 if (FormatStr == "%c" && CI->getNumOperands() > 2 &&
1048 isa<IntegerType>(CI->getOperand(2)->getType())) {
1049 EmitPutChar(CI->getOperand(2), B);
1050 return CI->use_empty() ? (Value*)CI : ConstantInt::get(CI->getType(), 1);
1053 // printf("%s\n", str) --> puts(str)
1054 if (FormatStr == "%s\n" && CI->getNumOperands() > 2 &&
1055 isa<PointerType>(CI->getOperand(2)->getType()) &&
1057 EmitPutS(CI->getOperand(2), B);
1064 //===---------------------------------------===//
1065 // 'sprintf' Optimizations
1067 struct VISIBILITY_HIDDEN SPrintFOpt : public LibCallOptimization {
1068 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1069 // Require two fixed pointer arguments and an integer result.
1070 const FunctionType *FT = Callee->getFunctionType();
1071 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1072 !isa<PointerType>(FT->getParamType(1)) ||
1073 !isa<IntegerType>(FT->getReturnType()))
1076 // Check for a fixed format string.
1077 std::string FormatStr;
1078 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1081 // If we just have a format string (nothing else crazy) transform it.
1082 if (CI->getNumOperands() == 3) {
1083 // Make sure there's no % in the constant array. We could try to handle
1084 // %% -> % in the future if we cared.
1085 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1086 if (FormatStr[i] == '%')
1087 return 0; // we found a format specifier, bail out.
1089 // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
1090 EmitMemCpy(CI->getOperand(1), CI->getOperand(2), // Copy the nul byte.
1091 ConstantInt::get(TD->getIntPtrType(), FormatStr.size()+1),1,B);
1092 return ConstantInt::get(CI->getType(), FormatStr.size());
1095 // The remaining optimizations require the format string to be "%s" or "%c"
1096 // and have an extra operand.
1097 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1100 // Decode the second character of the format string.
1101 if (FormatStr[1] == 'c') {
1102 // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
1103 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1104 Value *V = B.CreateTrunc(CI->getOperand(3), Type::Int8Ty, "char");
1105 Value *Ptr = CastToCStr(CI->getOperand(1), B);
1106 B.CreateStore(V, Ptr);
1107 Ptr = B.CreateGEP(Ptr, ConstantInt::get(Type::Int32Ty, 1), "nul");
1108 B.CreateStore(Constant::getNullValue(Type::Int8Ty), Ptr);
1110 return ConstantInt::get(CI->getType(), 1);
1113 if (FormatStr[1] == 's') {
1114 // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
1115 if (!isa<PointerType>(CI->getOperand(3)->getType())) return 0;
1117 Value *Len = EmitStrLen(CI->getOperand(3), B);
1118 Value *IncLen = B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1),
1120 EmitMemCpy(CI->getOperand(1), CI->getOperand(3), IncLen, 1, B);
1122 // The sprintf result is the unincremented number of bytes in the string.
1123 return B.CreateIntCast(Len, CI->getType(), false);
1129 //===---------------------------------------===//
1130 // 'fwrite' Optimizations
1132 struct VISIBILITY_HIDDEN FWriteOpt : public LibCallOptimization {
1133 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1134 // Require a pointer, an integer, an integer, a pointer, returning integer.
1135 const FunctionType *FT = Callee->getFunctionType();
1136 if (FT->getNumParams() != 4 || !isa<PointerType>(FT->getParamType(0)) ||
1137 !isa<IntegerType>(FT->getParamType(1)) ||
1138 !isa<IntegerType>(FT->getParamType(2)) ||
1139 !isa<PointerType>(FT->getParamType(3)) ||
1140 !isa<IntegerType>(FT->getReturnType()))
1143 // Get the element size and count.
1144 ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getOperand(2));
1145 ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getOperand(3));
1146 if (!SizeC || !CountC) return 0;
1147 uint64_t Bytes = SizeC->getZExtValue()*CountC->getZExtValue();
1149 // If this is writing zero records, remove the call (it's a noop).
1151 return ConstantInt::get(CI->getType(), 0);
1153 // If this is writing one byte, turn it into fputc.
1154 if (Bytes == 1) { // fwrite(S,1,1,F) -> fputc(S[0],F)
1155 Value *Char = B.CreateLoad(CastToCStr(CI->getOperand(1), B), "char");
1156 EmitFPutC(Char, CI->getOperand(4), B);
1157 return ConstantInt::get(CI->getType(), 1);
1164 //===---------------------------------------===//
1165 // 'fputs' Optimizations
1167 struct VISIBILITY_HIDDEN FPutsOpt : public LibCallOptimization {
1168 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1169 // Require two pointers. Also, we can't optimize if return value is used.
1170 const FunctionType *FT = Callee->getFunctionType();
1171 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1172 !isa<PointerType>(FT->getParamType(1)) ||
1176 // fputs(s,F) --> fwrite(s,1,strlen(s),F)
1177 uint64_t Len = GetStringLength(CI->getOperand(1));
1179 EmitFWrite(CI->getOperand(1), ConstantInt::get(TD->getIntPtrType(), Len-1),
1180 CI->getOperand(2), B);
1181 return CI; // Known to have no uses (see above).
1185 //===---------------------------------------===//
1186 // 'fprintf' Optimizations
1188 struct VISIBILITY_HIDDEN FPrintFOpt : public LibCallOptimization {
1189 virtual Value *CallOptimizer(Function *Callee, CallInst *CI, IRBuilder<> &B) {
1190 // Require two fixed paramters as pointers and integer result.
1191 const FunctionType *FT = Callee->getFunctionType();
1192 if (FT->getNumParams() != 2 || !isa<PointerType>(FT->getParamType(0)) ||
1193 !isa<PointerType>(FT->getParamType(1)) ||
1194 !isa<IntegerType>(FT->getReturnType()))
1197 // All the optimizations depend on the format string.
1198 std::string FormatStr;
1199 if (!GetConstantStringInfo(CI->getOperand(2), FormatStr))
1202 // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
1203 if (CI->getNumOperands() == 3) {
1204 for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
1205 if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
1206 return 0; // We found a format specifier.
1208 EmitFWrite(CI->getOperand(2), ConstantInt::get(TD->getIntPtrType(),
1210 CI->getOperand(1), B);
1211 return ConstantInt::get(CI->getType(), FormatStr.size());
1214 // The remaining optimizations require the format string to be "%s" or "%c"
1215 // and have an extra operand.
1216 if (FormatStr.size() != 2 || FormatStr[0] != '%' || CI->getNumOperands() <4)
1219 // Decode the second character of the format string.
1220 if (FormatStr[1] == 'c') {
1221 // fprintf(F, "%c", chr) --> *(i8*)dst = chr
1222 if (!isa<IntegerType>(CI->getOperand(3)->getType())) return 0;
1223 EmitFPutC(CI->getOperand(3), CI->getOperand(1), B);
1224 return ConstantInt::get(CI->getType(), 1);
1227 if (FormatStr[1] == 's') {
1228 // fprintf(F, "%s", str) -> fputs(str, F)
1229 if (!isa<PointerType>(CI->getOperand(3)->getType()) || !CI->use_empty())
1231 EmitFPutS(CI->getOperand(3), CI->getOperand(1), B);
1238 } // end anonymous namespace.
1240 //===----------------------------------------------------------------------===//
1241 // SimplifyLibCalls Pass Implementation
1242 //===----------------------------------------------------------------------===//
1245 /// This pass optimizes well known library functions from libc and libm.
1247 class VISIBILITY_HIDDEN SimplifyLibCalls : public FunctionPass {
1248 StringMap<LibCallOptimization*> Optimizations;
1249 // Miscellaneous LibCall Optimizations
1251 // String and Memory LibCall Optimizations
1252 StrCatOpt StrCat; StrChrOpt StrChr; StrCmpOpt StrCmp; StrNCmpOpt StrNCmp;
1253 StrCpyOpt StrCpy; StrLenOpt StrLen; MemCmpOpt MemCmp; MemCpyOpt MemCpy;
1254 MemMoveOpt MemMove; MemSetOpt MemSet;
1255 // Math Library Optimizations
1256 PowOpt Pow; Exp2Opt Exp2; UnaryDoubleFPOpt UnaryDoubleFP;
1257 // Integer Optimizations
1258 FFSOpt FFS; AbsOpt Abs; IsDigitOpt IsDigit; IsAsciiOpt IsAscii;
1260 // Formatting and IO Optimizations
1261 SPrintFOpt SPrintF; PrintFOpt PrintF;
1262 FWriteOpt FWrite; FPutsOpt FPuts; FPrintFOpt FPrintF;
1264 static char ID; // Pass identification
1265 SimplifyLibCalls() : FunctionPass(&ID) {}
1267 void InitOptimizations();
1268 bool runOnFunction(Function &F);
1270 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
1271 AU.addRequired<TargetData>();
1274 char SimplifyLibCalls::ID = 0;
1275 } // end anonymous namespace.
1277 static RegisterPass<SimplifyLibCalls>
1278 X("simplify-libcalls", "Simplify well-known library calls");
1280 // Public interface to the Simplify LibCalls pass.
1281 FunctionPass *llvm::createSimplifyLibCallsPass() {
1282 return new SimplifyLibCalls();
1285 /// Optimizations - Populate the Optimizations map with all the optimizations
1287 void SimplifyLibCalls::InitOptimizations() {
1288 // Miscellaneous LibCall Optimizations
1289 Optimizations["exit"] = &Exit;
1291 // String and Memory LibCall Optimizations
1292 Optimizations["strcat"] = &StrCat;
1293 Optimizations["strchr"] = &StrChr;
1294 Optimizations["strcmp"] = &StrCmp;
1295 Optimizations["strncmp"] = &StrNCmp;
1296 Optimizations["strcpy"] = &StrCpy;
1297 Optimizations["strlen"] = &StrLen;
1298 Optimizations["memcmp"] = &MemCmp;
1299 Optimizations["memcpy"] = &MemCpy;
1300 Optimizations["memmove"] = &MemMove;
1301 Optimizations["memset"] = &MemSet;
1303 // Math Library Optimizations
1304 Optimizations["powf"] = &Pow;
1305 Optimizations["pow"] = &Pow;
1306 Optimizations["powl"] = &Pow;
1307 Optimizations["llvm.pow.f32"] = &Pow;
1308 Optimizations["llvm.pow.f64"] = &Pow;
1309 Optimizations["llvm.pow.f80"] = &Pow;
1310 Optimizations["llvm.pow.f128"] = &Pow;
1311 Optimizations["llvm.pow.ppcf128"] = &Pow;
1312 Optimizations["exp2l"] = &Exp2;
1313 Optimizations["exp2"] = &Exp2;
1314 Optimizations["exp2f"] = &Exp2;
1315 Optimizations["llvm.exp2.ppcf128"] = &Exp2;
1316 Optimizations["llvm.exp2.f128"] = &Exp2;
1317 Optimizations["llvm.exp2.f80"] = &Exp2;
1318 Optimizations["llvm.exp2.f64"] = &Exp2;
1319 Optimizations["llvm.exp2.f32"] = &Exp2;
1322 Optimizations["floor"] = &UnaryDoubleFP;
1325 Optimizations["ceil"] = &UnaryDoubleFP;
1328 Optimizations["round"] = &UnaryDoubleFP;
1331 Optimizations["rint"] = &UnaryDoubleFP;
1333 #ifdef HAVE_NEARBYINTF
1334 Optimizations["nearbyint"] = &UnaryDoubleFP;
1337 // Integer Optimizations
1338 Optimizations["ffs"] = &FFS;
1339 Optimizations["ffsl"] = &FFS;
1340 Optimizations["ffsll"] = &FFS;
1341 Optimizations["abs"] = &Abs;
1342 Optimizations["labs"] = &Abs;
1343 Optimizations["llabs"] = &Abs;
1344 Optimizations["isdigit"] = &IsDigit;
1345 Optimizations["isascii"] = &IsAscii;
1346 Optimizations["toascii"] = &ToAscii;
1348 // Formatting and IO Optimizations
1349 Optimizations["sprintf"] = &SPrintF;
1350 Optimizations["printf"] = &PrintF;
1351 Optimizations["fwrite"] = &FWrite;
1352 Optimizations["fputs"] = &FPuts;
1353 Optimizations["fprintf"] = &FPrintF;
1357 /// runOnFunction - Top level algorithm.
1359 bool SimplifyLibCalls::runOnFunction(Function &F) {
1360 if (Optimizations.empty())
1361 InitOptimizations();
1363 const TargetData &TD = getAnalysis<TargetData>();
1365 IRBuilder<> Builder;
1367 bool Changed = false;
1368 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1369 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
1370 // Ignore non-calls.
1371 CallInst *CI = dyn_cast<CallInst>(I++);
1374 // Ignore indirect calls and calls to non-external functions.
1375 Function *Callee = CI->getCalledFunction();
1376 if (Callee == 0 || !Callee->isDeclaration() ||
1377 !(Callee->hasExternalLinkage() || Callee->hasDLLImportLinkage()))
1380 // Ignore unknown calls.
1381 const char *CalleeName = Callee->getNameStart();
1382 StringMap<LibCallOptimization*>::iterator OMI =
1383 Optimizations.find(CalleeName, CalleeName+Callee->getNameLen());
1384 if (OMI == Optimizations.end()) continue;
1386 // Set the builder to the instruction after the call.
1387 Builder.SetInsertPoint(BB, I);
1389 // Try to optimize this call.
1390 Value *Result = OMI->second->OptimizeCall(CI, TD, Builder);
1391 if (Result == 0) continue;
1393 DEBUG(DOUT << "SimplifyLibCalls simplified: " << *CI;
1394 DOUT << " into: " << *Result << "\n");
1396 // Something changed!
1400 // Inspect the instruction after the call (which was potentially just
1404 if (CI != Result && !CI->use_empty()) {
1405 CI->replaceAllUsesWith(Result);
1406 if (!Result->hasName())
1407 Result->takeName(CI);
1409 CI->eraseFromParent();
1417 // Additional cases that we need to add to this file:
1420 // * cbrt(expN(X)) -> expN(x/3)
1421 // * cbrt(sqrt(x)) -> pow(x,1/6)
1422 // * cbrt(sqrt(x)) -> pow(x,1/9)
1425 // * cos(-x) -> cos(x)
1428 // * exp(log(x)) -> x
1431 // * log(exp(x)) -> x
1432 // * log(x**y) -> y*log(x)
1433 // * log(exp(y)) -> y*log(e)
1434 // * log(exp2(y)) -> y*log(2)
1435 // * log(exp10(y)) -> y*log(10)
1436 // * log(sqrt(x)) -> 0.5*log(x)
1437 // * log(pow(x,y)) -> y*log(x)
1439 // lround, lroundf, lroundl:
1440 // * lround(cnst) -> cnst'
1443 // * memcmp(x,y,l) -> cnst
1444 // (if all arguments are constant and strlen(x) <= l and strlen(y) <= l)
1447 // * pow(exp(x),y) -> exp(x*y)
1448 // * pow(sqrt(x),y) -> pow(x,y*0.5)
1449 // * pow(pow(x,y),z)-> pow(x,y*z)
1452 // * puts("") -> putchar("\n")
1454 // round, roundf, roundl:
1455 // * round(cnst) -> cnst'
1458 // * signbit(cnst) -> cnst'
1459 // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
1461 // sqrt, sqrtf, sqrtl:
1462 // * sqrt(expN(x)) -> expN(x*0.5)
1463 // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
1464 // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
1467 // * stpcpy(str, "literal") ->
1468 // llvm.memcpy(str,"literal",strlen("literal")+1,1)
1470 // * strrchr(s,c) -> reverse_offset_of_in(c,s)
1471 // (if c is a constant integer and s is a constant string)
1472 // * strrchr(s1,0) -> strchr(s1,0)
1475 // * strncat(x,y,0) -> x
1476 // * strncat(x,y,0) -> x (if strlen(y) = 0)
1477 // * strncat(x,y,l) -> strcat(x,y) (if y and l are constants an l > strlen(y))
1480 // * strncpy(d,s,0) -> d
1481 // * strncpy(d,s,l) -> memcpy(d,s,l,1)
1482 // (if s and l are constants)
1485 // * strpbrk(s,a) -> offset_in_for(s,a)
1486 // (if s and a are both constant strings)
1487 // * strpbrk(s,"") -> 0
1488 // * strpbrk(s,a) -> strchr(s,a[0]) (if a is constant string of length 1)
1491 // * strspn(s,a) -> const_int (if both args are constant)
1492 // * strspn("",a) -> 0
1493 // * strspn(s,"") -> 0
1494 // * strcspn(s,a) -> const_int (if both args are constant)
1495 // * strcspn("",a) -> 0
1496 // * strcspn(s,"") -> strlen(a)
1499 // * strstr(x,x) -> x
1500 // * strstr(s1,s2) -> offset_of_s2_in(s1)
1501 // (if s1 and s2 are constant strings)
1504 // * tan(atan(x)) -> x
1506 // trunc, truncf, truncl:
1507 // * trunc(cnst) -> cnst'