SimplifyLibCalls.cpp 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377
  1. //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is a utility pass used for testing the InstructionSimplify analysis.
  11. // The analysis is applied to every instruction, and if it simplifies then the
  12. // instruction is replaced by the simplification. If you are looking for a pass
  13. // that performs serious instruction folding, use the instcombine pass instead.
  14. //
  15. //===----------------------------------------------------------------------===//
  16. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  17. #include "llvm/ADT/SmallString.h"
  18. #include "llvm/ADT/StringMap.h"
  19. #include "llvm/ADT/Triple.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/DiagnosticInfo.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/IRBuilder.h"
  25. #include "llvm/IR/IntrinsicInst.h"
  26. #include "llvm/IR/Intrinsics.h"
  27. #include "llvm/IR/LLVMContext.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/IR/PatternMatch.h"
  30. #include "llvm/Support/Allocator.h"
  31. #include "llvm/Support/CommandLine.h"
  32. #include "llvm/Analysis/TargetLibraryInfo.h"
  33. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  34. using namespace llvm;
  35. using namespace PatternMatch;
  36. #if 0 // HLSL Change Starts - option pending
  37. static cl::opt<bool>
  38. ColdErrorCalls("error-reporting-is-cold", cl::init(true), cl::Hidden,
  39. cl::desc("Treat error-reporting calls as cold"));
  40. static cl::opt<bool>
  41. EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
  42. cl::init(false),
  43. cl::desc("Enable unsafe double to float "
  44. "shrinking for math lib calls"));
  45. #else
  46. static const bool ColdErrorCalls = true;
  47. static const bool EnableUnsafeFPShrink = false;
  48. #endif // HLSL Change Ends
  49. //===----------------------------------------------------------------------===//
  50. // Helper Functions
  51. //===----------------------------------------------------------------------===//
  52. static bool ignoreCallingConv(LibFunc::Func Func) {
  53. switch (Func) {
  54. case LibFunc::abs:
  55. case LibFunc::labs:
  56. case LibFunc::llabs:
  57. case LibFunc::strlen:
  58. return true;
  59. default:
  60. return false;
  61. }
  62. llvm_unreachable("All cases should be covered in the switch.");
  63. }
  64. /// isOnlyUsedInZeroEqualityComparison - Return true if it only matters that the
  65. /// value is equal or not-equal to zero.
  66. static bool isOnlyUsedInZeroEqualityComparison(Value *V) {
  67. for (User *U : V->users()) {
  68. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  69. if (IC->isEquality())
  70. if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  71. if (C->isNullValue())
  72. continue;
  73. // Unknown instruction.
  74. return false;
  75. }
  76. return true;
  77. }
  78. /// isOnlyUsedInEqualityComparison - Return true if it is only used in equality
  79. /// comparisons with With.
  80. static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
  81. for (User *U : V->users()) {
  82. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  83. if (IC->isEquality() && IC->getOperand(1) == With)
  84. continue;
  85. // Unknown instruction.
  86. return false;
  87. }
  88. return true;
  89. }
  90. static bool callHasFloatingPointArgument(const CallInst *CI) {
  91. for (CallInst::const_op_iterator it = CI->op_begin(), e = CI->op_end();
  92. it != e; ++it) {
  93. if ((*it)->getType()->isFloatingPointTy())
  94. return true;
  95. }
  96. return false;
  97. }
  98. /// \brief Check whether the overloaded unary floating point function
  99. /// corresponing to \a Ty is available.
  100. static bool hasUnaryFloatFn(const TargetLibraryInfo *TLI, Type *Ty,
  101. LibFunc::Func DoubleFn, LibFunc::Func FloatFn,
  102. LibFunc::Func LongDoubleFn) {
  103. switch (Ty->getTypeID()) {
  104. case Type::FloatTyID:
  105. return TLI->has(FloatFn);
  106. case Type::DoubleTyID:
  107. return TLI->has(DoubleFn);
  108. default:
  109. return TLI->has(LongDoubleFn);
  110. }
  111. }
  112. /// \brief Returns whether \p F matches the signature expected for the
  113. /// string/memory copying library function \p Func.
  114. /// Acceptable functions are st[rp][n]?cpy, memove, memcpy, and memset.
  115. /// Their fortified (_chk) counterparts are also accepted.
  116. static bool checkStringCopyLibFuncSignature(Function *F, LibFunc::Func Func) {
  117. const DataLayout &DL = F->getParent()->getDataLayout();
  118. FunctionType *FT = F->getFunctionType();
  119. LLVMContext &Context = F->getContext();
  120. Type *PCharTy = Type::getInt8PtrTy(Context);
  121. Type *SizeTTy = DL.getIntPtrType(Context);
  122. unsigned NumParams = FT->getNumParams();
  123. // All string libfuncs return the same type as the first parameter.
  124. if (FT->getReturnType() != FT->getParamType(0))
  125. return false;
  126. switch (Func) {
  127. default:
  128. llvm_unreachable("Can't check signature for non-string-copy libfunc.");
  129. case LibFunc::stpncpy_chk:
  130. case LibFunc::strncpy_chk:
  131. --NumParams; // fallthrough
  132. case LibFunc::stpncpy:
  133. case LibFunc::strncpy: {
  134. if (NumParams != 3 || FT->getParamType(0) != FT->getParamType(1) ||
  135. FT->getParamType(0) != PCharTy || !FT->getParamType(2)->isIntegerTy())
  136. return false;
  137. break;
  138. }
  139. case LibFunc::strcpy_chk:
  140. case LibFunc::stpcpy_chk:
  141. --NumParams; // fallthrough
  142. case LibFunc::stpcpy:
  143. case LibFunc::strcpy: {
  144. if (NumParams != 2 || FT->getParamType(0) != FT->getParamType(1) ||
  145. FT->getParamType(0) != PCharTy)
  146. return false;
  147. break;
  148. }
  149. case LibFunc::memmove_chk:
  150. case LibFunc::memcpy_chk:
  151. --NumParams; // fallthrough
  152. case LibFunc::memmove:
  153. case LibFunc::memcpy: {
  154. if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
  155. !FT->getParamType(1)->isPointerTy() || FT->getParamType(2) != SizeTTy)
  156. return false;
  157. break;
  158. }
  159. case LibFunc::memset_chk:
  160. --NumParams; // fallthrough
  161. case LibFunc::memset: {
  162. if (NumParams != 3 || !FT->getParamType(0)->isPointerTy() ||
  163. !FT->getParamType(1)->isIntegerTy() || FT->getParamType(2) != SizeTTy)
  164. return false;
  165. break;
  166. }
  167. }
  168. // If this is a fortified libcall, the last parameter is a size_t.
  169. if (NumParams == FT->getNumParams() - 1)
  170. return FT->getParamType(FT->getNumParams() - 1) == SizeTTy;
  171. return true;
  172. }
  173. //===----------------------------------------------------------------------===//
  174. // String and Memory Library Call Optimizations
  175. //===----------------------------------------------------------------------===//
  176. Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
  177. Function *Callee = CI->getCalledFunction();
  178. // Verify the "strcat" function prototype.
  179. FunctionType *FT = Callee->getFunctionType();
  180. if (FT->getNumParams() != 2||
  181. FT->getReturnType() != B.getInt8PtrTy() ||
  182. FT->getParamType(0) != FT->getReturnType() ||
  183. FT->getParamType(1) != FT->getReturnType())
  184. return nullptr;
  185. // Extract some information from the instruction
  186. Value *Dst = CI->getArgOperand(0);
  187. Value *Src = CI->getArgOperand(1);
  188. // See if we can get the length of the input string.
  189. uint64_t Len = GetStringLength(Src);
  190. if (Len == 0)
  191. return nullptr;
  192. --Len; // Unbias length.
  193. // Handle the simple, do-nothing case: strcat(x, "") -> x
  194. if (Len == 0)
  195. return Dst;
  196. return emitStrLenMemCpy(Src, Dst, Len, B);
  197. }
  198. Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
  199. IRBuilder<> &B) {
  200. // We need to find the end of the destination string. That's where the
  201. // memory is to be moved to. We just generate a call to strlen.
  202. Value *DstLen = EmitStrLen(Dst, B, DL, TLI);
  203. if (!DstLen)
  204. return nullptr;
  205. // Now that we have the destination's length, we must index into the
  206. // destination's pointer to get the actual memcpy destination (end of
  207. // the string .. we're concatenating).
  208. Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
  209. // We have enough information to now generate the memcpy call to do the
  210. // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
  211. B.CreateMemCpy(CpyDst, Src,
  212. ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1),
  213. 1);
  214. return Dst;
  215. }
  216. Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
  217. Function *Callee = CI->getCalledFunction();
  218. // Verify the "strncat" function prototype.
  219. FunctionType *FT = Callee->getFunctionType();
  220. if (FT->getNumParams() != 3 || FT->getReturnType() != B.getInt8PtrTy() ||
  221. FT->getParamType(0) != FT->getReturnType() ||
  222. FT->getParamType(1) != FT->getReturnType() ||
  223. !FT->getParamType(2)->isIntegerTy())
  224. return nullptr;
  225. // Extract some information from the instruction
  226. Value *Dst = CI->getArgOperand(0);
  227. Value *Src = CI->getArgOperand(1);
  228. uint64_t Len;
  229. // We don't do anything if length is not constant
  230. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
  231. Len = LengthArg->getZExtValue();
  232. else
  233. return nullptr;
  234. // See if we can get the length of the input string.
  235. uint64_t SrcLen = GetStringLength(Src);
  236. if (SrcLen == 0)
  237. return nullptr;
  238. --SrcLen; // Unbias length.
  239. // Handle the simple, do-nothing cases:
  240. // strncat(x, "", c) -> x
  241. // strncat(x, c, 0) -> x
  242. if (SrcLen == 0 || Len == 0)
  243. return Dst;
  244. // We don't optimize this case
  245. if (Len < SrcLen)
  246. return nullptr;
  247. // strncat(x, s, c) -> strcat(x, s)
  248. // s is constant so the strcat can be optimized further
  249. return emitStrLenMemCpy(Src, Dst, SrcLen, B);
  250. }
  251. Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
  252. Function *Callee = CI->getCalledFunction();
  253. // Verify the "strchr" function prototype.
  254. FunctionType *FT = Callee->getFunctionType();
  255. if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
  256. FT->getParamType(0) != FT->getReturnType() ||
  257. !FT->getParamType(1)->isIntegerTy(32))
  258. return nullptr;
  259. Value *SrcStr = CI->getArgOperand(0);
  260. // If the second operand is non-constant, see if we can compute the length
  261. // of the input string and turn this into memchr.
  262. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  263. if (!CharC) {
  264. uint64_t Len = GetStringLength(SrcStr);
  265. if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
  266. return nullptr;
  267. return EmitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
  268. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
  269. B, DL, TLI);
  270. }
  271. // Otherwise, the character is a constant, see if the first argument is
  272. // a string literal. If so, we can constant fold.
  273. StringRef Str;
  274. if (!getConstantStringInfo(SrcStr, Str)) {
  275. if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
  276. return B.CreateGEP(B.getInt8Ty(), SrcStr, EmitStrLen(SrcStr, B, DL, TLI), "strchr");
  277. return nullptr;
  278. }
  279. // Compute the offset, make sure to handle the case when we're searching for
  280. // zero (a weird way to spell strlen).
  281. size_t I = (0xFF & CharC->getSExtValue()) == 0
  282. ? Str.size()
  283. : Str.find(CharC->getSExtValue());
  284. if (I == StringRef::npos) // Didn't find the char. strchr returns null.
  285. return Constant::getNullValue(CI->getType());
  286. // strchr(s+n,c) -> gep(s+n+i,c)
  287. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
  288. }
  289. Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
  290. Function *Callee = CI->getCalledFunction();
  291. // Verify the "strrchr" function prototype.
  292. FunctionType *FT = Callee->getFunctionType();
  293. if (FT->getNumParams() != 2 || FT->getReturnType() != B.getInt8PtrTy() ||
  294. FT->getParamType(0) != FT->getReturnType() ||
  295. !FT->getParamType(1)->isIntegerTy(32))
  296. return nullptr;
  297. Value *SrcStr = CI->getArgOperand(0);
  298. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  299. // Cannot fold anything if we're not looking for a constant.
  300. if (!CharC)
  301. return nullptr;
  302. StringRef Str;
  303. if (!getConstantStringInfo(SrcStr, Str)) {
  304. // strrchr(s, 0) -> strchr(s, 0)
  305. if (CharC->isZero())
  306. return EmitStrChr(SrcStr, '\0', B, TLI);
  307. return nullptr;
  308. }
  309. // Compute the offset.
  310. size_t I = (0xFF & CharC->getSExtValue()) == 0
  311. ? Str.size()
  312. : Str.rfind(CharC->getSExtValue());
  313. if (I == StringRef::npos) // Didn't find the char. Return null.
  314. return Constant::getNullValue(CI->getType());
  315. // strrchr(s+n,c) -> gep(s+n+i,c)
  316. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
  317. }
  318. Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
  319. Function *Callee = CI->getCalledFunction();
  320. // Verify the "strcmp" function prototype.
  321. FunctionType *FT = Callee->getFunctionType();
  322. if (FT->getNumParams() != 2 || !FT->getReturnType()->isIntegerTy(32) ||
  323. FT->getParamType(0) != FT->getParamType(1) ||
  324. FT->getParamType(0) != B.getInt8PtrTy())
  325. return nullptr;
  326. Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
  327. if (Str1P == Str2P) // strcmp(x,x) -> 0
  328. return ConstantInt::get(CI->getType(), 0);
  329. StringRef Str1, Str2;
  330. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  331. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  332. // strcmp(x, y) -> cnst (if both x and y are constant strings)
  333. if (HasStr1 && HasStr2)
  334. return ConstantInt::get(CI->getType(), Str1.compare(Str2));
  335. if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
  336. return B.CreateNeg(
  337. B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
  338. if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
  339. return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
  340. // strcmp(P, "x") -> memcmp(P, "x", 2)
  341. uint64_t Len1 = GetStringLength(Str1P);
  342. uint64_t Len2 = GetStringLength(Str2P);
  343. if (Len1 && Len2) {
  344. return EmitMemCmp(Str1P, Str2P,
  345. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  346. std::min(Len1, Len2)),
  347. B, DL, TLI);
  348. }
  349. return nullptr;
  350. }
  351. Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
  352. Function *Callee = CI->getCalledFunction();
  353. // Verify the "strncmp" function prototype.
  354. FunctionType *FT = Callee->getFunctionType();
  355. if (FT->getNumParams() != 3 || !FT->getReturnType()->isIntegerTy(32) ||
  356. FT->getParamType(0) != FT->getParamType(1) ||
  357. FT->getParamType(0) != B.getInt8PtrTy() ||
  358. !FT->getParamType(2)->isIntegerTy())
  359. return nullptr;
  360. Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
  361. if (Str1P == Str2P) // strncmp(x,x,n) -> 0
  362. return ConstantInt::get(CI->getType(), 0);
  363. // Get the length argument if it is constant.
  364. uint64_t Length;
  365. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
  366. Length = LengthArg->getZExtValue();
  367. else
  368. return nullptr;
  369. if (Length == 0) // strncmp(x,y,0) -> 0
  370. return ConstantInt::get(CI->getType(), 0);
  371. if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
  372. return EmitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
  373. StringRef Str1, Str2;
  374. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  375. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  376. // strncmp(x, y) -> cnst (if both x and y are constant strings)
  377. if (HasStr1 && HasStr2) {
  378. StringRef SubStr1 = Str1.substr(0, Length);
  379. StringRef SubStr2 = Str2.substr(0, Length);
  380. return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
  381. }
  382. if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
  383. return B.CreateNeg(
  384. B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
  385. if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
  386. return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
  387. return nullptr;
  388. }
  389. Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
  390. Function *Callee = CI->getCalledFunction();
  391. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strcpy))
  392. return nullptr;
  393. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  394. if (Dst == Src) // strcpy(x,x) -> x
  395. return Src;
  396. // See if we can get the length of the input string.
  397. uint64_t Len = GetStringLength(Src);
  398. if (Len == 0)
  399. return nullptr;
  400. // We have enough information to now generate the memcpy call to do the
  401. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  402. B.CreateMemCpy(Dst, Src,
  403. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len), 1);
  404. return Dst;
  405. }
  406. Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
  407. Function *Callee = CI->getCalledFunction();
  408. // Verify the "stpcpy" function prototype.
  409. FunctionType *FT = Callee->getFunctionType();
  410. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::stpcpy))
  411. return nullptr;
  412. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  413. if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
  414. Value *StrLen = EmitStrLen(Src, B, DL, TLI);
  415. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  416. }
  417. // See if we can get the length of the input string.
  418. uint64_t Len = GetStringLength(Src);
  419. if (Len == 0)
  420. return nullptr;
  421. Type *PT = FT->getParamType(0);
  422. Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
  423. Value *DstEnd =
  424. B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
  425. // We have enough information to now generate the memcpy call to do the
  426. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  427. B.CreateMemCpy(Dst, Src, LenV, 1);
  428. return DstEnd;
  429. }
  430. Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
  431. Function *Callee = CI->getCalledFunction();
  432. FunctionType *FT = Callee->getFunctionType();
  433. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::strncpy))
  434. return nullptr;
  435. Value *Dst = CI->getArgOperand(0);
  436. Value *Src = CI->getArgOperand(1);
  437. Value *LenOp = CI->getArgOperand(2);
  438. // See if we can get the length of the input string.
  439. uint64_t SrcLen = GetStringLength(Src);
  440. if (SrcLen == 0)
  441. return nullptr;
  442. --SrcLen;
  443. if (SrcLen == 0) {
  444. // strncpy(x, "", y) -> memset(x, '\0', y, 1)
  445. B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
  446. return Dst;
  447. }
  448. uint64_t Len;
  449. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
  450. Len = LengthArg->getZExtValue();
  451. else
  452. return nullptr;
  453. if (Len == 0)
  454. return Dst; // strncpy(x, y, 0) -> x
  455. // Let strncpy handle the zero padding
  456. if (Len > SrcLen + 1)
  457. return nullptr;
  458. Type *PT = FT->getParamType(0);
  459. // strncpy(x, s, c) -> memcpy(x, s, c, 1) [s and c are constant]
  460. B.CreateMemCpy(Dst, Src, ConstantInt::get(DL.getIntPtrType(PT), Len), 1);
  461. return Dst;
  462. }
  463. Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
  464. Function *Callee = CI->getCalledFunction();
  465. FunctionType *FT = Callee->getFunctionType();
  466. if (FT->getNumParams() != 1 || FT->getParamType(0) != B.getInt8PtrTy() ||
  467. !FT->getReturnType()->isIntegerTy())
  468. return nullptr;
  469. Value *Src = CI->getArgOperand(0);
  470. // Constant folding: strlen("xyz") -> 3
  471. if (uint64_t Len = GetStringLength(Src))
  472. return ConstantInt::get(CI->getType(), Len - 1);
  473. // strlen(x?"foo":"bars") --> x ? 3 : 4
  474. if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  475. uint64_t LenTrue = GetStringLength(SI->getTrueValue());
  476. uint64_t LenFalse = GetStringLength(SI->getFalseValue());
  477. if (LenTrue && LenFalse) {
  478. Function *Caller = CI->getParent()->getParent();
  479. emitOptimizationRemark(CI->getContext(), "simplify-libcalls", *Caller,
  480. SI->getDebugLoc(),
  481. "folded strlen(select) to select of constants");
  482. return B.CreateSelect(SI->getCondition(),
  483. ConstantInt::get(CI->getType(), LenTrue - 1),
  484. ConstantInt::get(CI->getType(), LenFalse - 1));
  485. }
  486. }
  487. // strlen(x) != 0 --> *x != 0
  488. // strlen(x) == 0 --> *x == 0
  489. if (isOnlyUsedInZeroEqualityComparison(CI))
  490. return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
  491. return nullptr;
  492. }
  493. Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
  494. Function *Callee = CI->getCalledFunction();
  495. FunctionType *FT = Callee->getFunctionType();
  496. if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
  497. FT->getParamType(1) != FT->getParamType(0) ||
  498. FT->getReturnType() != FT->getParamType(0))
  499. return nullptr;
  500. StringRef S1, S2;
  501. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  502. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  503. // strpbrk(s, "") -> nullptr
  504. // strpbrk("", s) -> nullptr
  505. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  506. return Constant::getNullValue(CI->getType());
  507. // Constant folding.
  508. if (HasS1 && HasS2) {
  509. size_t I = S1.find_first_of(S2);
  510. if (I == StringRef::npos) // No match.
  511. return Constant::getNullValue(CI->getType());
  512. return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I), "strpbrk");
  513. }
  514. // strpbrk(s, "a") -> strchr(s, 'a')
  515. if (HasS2 && S2.size() == 1)
  516. return EmitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
  517. return nullptr;
  518. }
  519. Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
  520. Function *Callee = CI->getCalledFunction();
  521. FunctionType *FT = Callee->getFunctionType();
  522. if ((FT->getNumParams() != 2 && FT->getNumParams() != 3) ||
  523. !FT->getParamType(0)->isPointerTy() ||
  524. !FT->getParamType(1)->isPointerTy())
  525. return nullptr;
  526. Value *EndPtr = CI->getArgOperand(1);
  527. if (isa<ConstantPointerNull>(EndPtr)) {
  528. // With a null EndPtr, this function won't capture the main argument.
  529. // It would be readonly too, except that it still may write to errno.
  530. CI->addAttribute(1, Attribute::NoCapture);
  531. }
  532. return nullptr;
  533. }
  534. Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
  535. Function *Callee = CI->getCalledFunction();
  536. FunctionType *FT = Callee->getFunctionType();
  537. if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
  538. FT->getParamType(1) != FT->getParamType(0) ||
  539. !FT->getReturnType()->isIntegerTy())
  540. return nullptr;
  541. StringRef S1, S2;
  542. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  543. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  544. // strspn(s, "") -> 0
  545. // strspn("", s) -> 0
  546. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  547. return Constant::getNullValue(CI->getType());
  548. // Constant folding.
  549. if (HasS1 && HasS2) {
  550. size_t Pos = S1.find_first_not_of(S2);
  551. if (Pos == StringRef::npos)
  552. Pos = S1.size();
  553. return ConstantInt::get(CI->getType(), Pos);
  554. }
  555. return nullptr;
  556. }
  557. Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
  558. Function *Callee = CI->getCalledFunction();
  559. FunctionType *FT = Callee->getFunctionType();
  560. if (FT->getNumParams() != 2 || FT->getParamType(0) != B.getInt8PtrTy() ||
  561. FT->getParamType(1) != FT->getParamType(0) ||
  562. !FT->getReturnType()->isIntegerTy())
  563. return nullptr;
  564. StringRef S1, S2;
  565. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  566. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  567. // strcspn("", s) -> 0
  568. if (HasS1 && S1.empty())
  569. return Constant::getNullValue(CI->getType());
  570. // Constant folding.
  571. if (HasS1 && HasS2) {
  572. size_t Pos = S1.find_first_of(S2);
  573. if (Pos == StringRef::npos)
  574. Pos = S1.size();
  575. return ConstantInt::get(CI->getType(), Pos);
  576. }
  577. // strcspn(s, "") -> strlen(s)
  578. if (HasS2 && S2.empty())
  579. return EmitStrLen(CI->getArgOperand(0), B, DL, TLI);
  580. return nullptr;
  581. }
  582. Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
  583. Function *Callee = CI->getCalledFunction();
  584. FunctionType *FT = Callee->getFunctionType();
  585. if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
  586. !FT->getParamType(1)->isPointerTy() ||
  587. !FT->getReturnType()->isPointerTy())
  588. return nullptr;
  589. // fold strstr(x, x) -> x.
  590. if (CI->getArgOperand(0) == CI->getArgOperand(1))
  591. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  592. // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
  593. if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
  594. Value *StrLen = EmitStrLen(CI->getArgOperand(1), B, DL, TLI);
  595. if (!StrLen)
  596. return nullptr;
  597. Value *StrNCmp = EmitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
  598. StrLen, B, DL, TLI);
  599. if (!StrNCmp)
  600. return nullptr;
  601. for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
  602. ICmpInst *Old = cast<ICmpInst>(*UI++);
  603. Value *Cmp =
  604. B.CreateICmp(Old->getPredicate(), StrNCmp,
  605. ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
  606. replaceAllUsesWith(Old, Cmp);
  607. }
  608. return CI;
  609. }
  610. // See if either input string is a constant string.
  611. StringRef SearchStr, ToFindStr;
  612. bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
  613. bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
  614. // fold strstr(x, "") -> x.
  615. if (HasStr2 && ToFindStr.empty())
  616. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  617. // If both strings are known, constant fold it.
  618. if (HasStr1 && HasStr2) {
  619. size_t Offset = SearchStr.find(ToFindStr);
  620. if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
  621. return Constant::getNullValue(CI->getType());
  622. // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
  623. Value *Result = CastToCStr(CI->getArgOperand(0), B);
  624. Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
  625. return B.CreateBitCast(Result, CI->getType());
  626. }
  627. // fold strstr(x, "y") -> strchr(x, 'y').
  628. if (HasStr2 && ToFindStr.size() == 1) {
  629. Value *StrChr = EmitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
  630. return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
  631. }
  632. return nullptr;
  633. }
  634. Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
  635. Function *Callee = CI->getCalledFunction();
  636. FunctionType *FT = Callee->getFunctionType();
  637. if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
  638. !FT->getParamType(1)->isIntegerTy(32) ||
  639. !FT->getParamType(2)->isIntegerTy() ||
  640. !FT->getReturnType()->isPointerTy())
  641. return nullptr;
  642. Value *SrcStr = CI->getArgOperand(0);
  643. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  644. ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  645. // memchr(x, y, 0) -> null
  646. if (LenC && LenC->isNullValue())
  647. return Constant::getNullValue(CI->getType());
  648. // From now on we need at least constant length and string.
  649. StringRef Str;
  650. if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
  651. return nullptr;
  652. // Truncate the string to LenC. If Str is smaller than LenC we will still only
  653. // scan the string, as reading past the end of it is undefined and we can just
  654. // return null if we don't find the char.
  655. Str = Str.substr(0, LenC->getZExtValue());
  656. // If the char is variable but the input str and length are not we can turn
  657. // this memchr call into a simple bit field test. Of course this only works
  658. // when the return value is only checked against null.
  659. //
  660. // It would be really nice to reuse switch lowering here but we can't change
  661. // the CFG at this point.
  662. //
  663. // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
  664. // after bounds check.
  665. if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
  666. unsigned char Max =
  667. *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
  668. reinterpret_cast<const unsigned char *>(Str.end()));
  669. // Make sure the bit field we're about to create fits in a register on the
  670. // target.
  671. // FIXME: On a 64 bit architecture this prevents us from using the
  672. // interesting range of alpha ascii chars. We could do better by emitting
  673. // two bitfields or shifting the range by 64 if no lower chars are used.
  674. if (!DL.fitsInLegalInteger(Max + 1))
  675. return nullptr;
  676. // For the bit field use a power-of-2 type with at least 8 bits to avoid
  677. // creating unnecessary illegal types.
  678. unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
  679. // Now build the bit field.
  680. APInt Bitfield(Width, 0);
  681. for (char C : Str)
  682. Bitfield.setBit((unsigned char)C);
  683. Value *BitfieldC = B.getInt(Bitfield);
  684. // First check that the bit field access is within bounds.
  685. Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
  686. Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
  687. "memchr.bounds");
  688. // Create code that checks if the given bit is set in the field.
  689. Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
  690. Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
  691. // Finally merge both checks and cast to pointer type. The inttoptr
  692. // implicitly zexts the i1 to intptr type.
  693. return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
  694. }
  695. // Check if all arguments are constants. If so, we can constant fold.
  696. if (!CharC)
  697. return nullptr;
  698. // Compute the offset.
  699. size_t I = Str.find(CharC->getSExtValue() & 0xFF);
  700. if (I == StringRef::npos) // Didn't find the char. memchr returns null.
  701. return Constant::getNullValue(CI->getType());
  702. // memchr(s+n,c,l) -> gep(s+n+i,c)
  703. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
  704. }
  705. Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
  706. Function *Callee = CI->getCalledFunction();
  707. FunctionType *FT = Callee->getFunctionType();
  708. if (FT->getNumParams() != 3 || !FT->getParamType(0)->isPointerTy() ||
  709. !FT->getParamType(1)->isPointerTy() ||
  710. !FT->getReturnType()->isIntegerTy(32))
  711. return nullptr;
  712. Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
  713. if (LHS == RHS) // memcmp(s,s,x) -> 0
  714. return Constant::getNullValue(CI->getType());
  715. // Make sure we have a constant length.
  716. ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  717. if (!LenC)
  718. return nullptr;
  719. uint64_t Len = LenC->getZExtValue();
  720. if (Len == 0) // memcmp(s1,s2,0) -> 0
  721. return Constant::getNullValue(CI->getType());
  722. // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
  723. if (Len == 1) {
  724. Value *LHSV = B.CreateZExt(B.CreateLoad(CastToCStr(LHS, B), "lhsc"),
  725. CI->getType(), "lhsv");
  726. Value *RHSV = B.CreateZExt(B.CreateLoad(CastToCStr(RHS, B), "rhsc"),
  727. CI->getType(), "rhsv");
  728. return B.CreateSub(LHSV, RHSV, "chardiff");
  729. }
  730. // Constant folding: memcmp(x, y, l) -> cnst (all arguments are constant)
  731. StringRef LHSStr, RHSStr;
  732. if (getConstantStringInfo(LHS, LHSStr) &&
  733. getConstantStringInfo(RHS, RHSStr)) {
  734. // Make sure we're not reading out-of-bounds memory.
  735. if (Len > LHSStr.size() || Len > RHSStr.size())
  736. return nullptr;
  737. // Fold the memcmp and normalize the result. This way we get consistent
  738. // results across multiple platforms.
  739. uint64_t Ret = 0;
  740. int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
  741. if (Cmp < 0)
  742. Ret = -1;
  743. else if (Cmp > 0)
  744. Ret = 1;
  745. return ConstantInt::get(CI->getType(), Ret);
  746. }
  747. return nullptr;
  748. }
  749. Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
  750. Function *Callee = CI->getCalledFunction();
  751. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy))
  752. return nullptr;
  753. // memcpy(x, y, n) -> llvm.memcpy(x, y, n, 1)
  754. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  755. CI->getArgOperand(2), 1);
  756. return CI->getArgOperand(0);
  757. }
  758. Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
  759. Function *Callee = CI->getCalledFunction();
  760. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove))
  761. return nullptr;
  762. // memmove(x, y, n) -> llvm.memmove(x, y, n, 1)
  763. B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
  764. CI->getArgOperand(2), 1);
  765. return CI->getArgOperand(0);
  766. }
  767. Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
  768. Function *Callee = CI->getCalledFunction();
  769. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset))
  770. return nullptr;
  771. // memset(p, v, n) -> llvm.memset(p, v, n, 1)
  772. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  773. B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
  774. return CI->getArgOperand(0);
  775. }
  776. //===----------------------------------------------------------------------===//
  777. // Math Library Optimizations
  778. //===----------------------------------------------------------------------===//
  779. /// Return a variant of Val with float type.
  780. /// Currently this works in two cases: If Val is an FPExtension of a float
  781. /// value to something bigger, simply return the operand.
  782. /// If Val is a ConstantFP but can be converted to a float ConstantFP without
  783. /// loss of precision do so.
  784. static Value *valueHasFloatPrecision(Value *Val) {
  785. if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
  786. Value *Op = Cast->getOperand(0);
  787. if (Op->getType()->isFloatTy())
  788. return Op;
  789. }
  790. if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
  791. APFloat F = Const->getValueAPF();
  792. bool losesInfo;
  793. (void)F.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven,
  794. &losesInfo);
  795. if (!losesInfo)
  796. return ConstantFP::get(Const->getContext(), F);
  797. }
  798. return nullptr;
  799. }
  800. //===----------------------------------------------------------------------===//
  801. // Double -> Float Shrinking Optimizations for Unary Functions like 'floor'
  802. Value *LibCallSimplifier::optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
  803. bool CheckRetType) {
  804. Function *Callee = CI->getCalledFunction();
  805. FunctionType *FT = Callee->getFunctionType();
  806. if (FT->getNumParams() != 1 || !FT->getReturnType()->isDoubleTy() ||
  807. !FT->getParamType(0)->isDoubleTy())
  808. return nullptr;
  809. if (CheckRetType) {
  810. // Check if all the uses for function like 'sin' are converted to float.
  811. for (User *U : CI->users()) {
  812. FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
  813. if (!Cast || !Cast->getType()->isFloatTy())
  814. return nullptr;
  815. }
  816. }
  817. // If this is something like 'floor((double)floatval)', convert to floorf.
  818. Value *V = valueHasFloatPrecision(CI->getArgOperand(0));
  819. if (V == nullptr)
  820. return nullptr;
  821. // floor((double)floatval) -> (double)floorf(floatval)
  822. if (Callee->isIntrinsic()) {
  823. Module *M = CI->getParent()->getParent()->getParent();
  824. Intrinsic::ID IID = Callee->getIntrinsicID();
  825. Function *F = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
  826. V = B.CreateCall(F, V);
  827. } else {
  828. // The call is a library call rather than an intrinsic.
  829. V = EmitUnaryFloatFnCall(V, Callee->getName(), B, Callee->getAttributes());
  830. }
  831. return B.CreateFPExt(V, B.getDoubleTy());
  832. }
  833. // Double -> Float Shrinking Optimizations for Binary Functions like 'fmin/fmax'
  834. Value *LibCallSimplifier::optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B) {
  835. Function *Callee = CI->getCalledFunction();
  836. FunctionType *FT = Callee->getFunctionType();
  837. // Just make sure this has 2 arguments of the same FP type, which match the
  838. // result type.
  839. if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
  840. FT->getParamType(0) != FT->getParamType(1) ||
  841. !FT->getParamType(0)->isFloatingPointTy())
  842. return nullptr;
  843. // If this is something like 'fmin((double)floatval1, (double)floatval2)',
  844. // or fmin(1.0, (double)floatval), then we convert it to fminf.
  845. Value *V1 = valueHasFloatPrecision(CI->getArgOperand(0));
  846. if (V1 == nullptr)
  847. return nullptr;
  848. Value *V2 = valueHasFloatPrecision(CI->getArgOperand(1));
  849. if (V2 == nullptr)
  850. return nullptr;
  851. // fmin((double)floatval1, (double)floatval2)
  852. // -> (double)fminf(floatval1, floatval2)
  853. // TODO: Handle intrinsics in the same way as in optimizeUnaryDoubleFP().
  854. Value *V = EmitBinaryFloatFnCall(V1, V2, Callee->getName(), B,
  855. Callee->getAttributes());
  856. return B.CreateFPExt(V, B.getDoubleTy());
  857. }
  858. Value *LibCallSimplifier::optimizeCos(CallInst *CI, IRBuilder<> &B) {
  859. Function *Callee = CI->getCalledFunction();
  860. Value *Ret = nullptr;
  861. if (UnsafeFPShrink && Callee->getName() == "cos" && TLI->has(LibFunc::cosf)) {
  862. Ret = optimizeUnaryDoubleFP(CI, B, true);
  863. }
  864. FunctionType *FT = Callee->getFunctionType();
  865. // Just make sure this has 1 argument of FP type, which matches the
  866. // result type.
  867. if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
  868. !FT->getParamType(0)->isFloatingPointTy())
  869. return Ret;
  870. // cos(-x) -> cos(x)
  871. Value *Op1 = CI->getArgOperand(0);
  872. if (BinaryOperator::isFNeg(Op1)) {
  873. BinaryOperator *BinExpr = cast<BinaryOperator>(Op1);
  874. return B.CreateCall(Callee, BinExpr->getOperand(1), "cos");
  875. }
  876. return Ret;
  877. }
  878. Value *LibCallSimplifier::optimizePow(CallInst *CI, IRBuilder<> &B) {
  879. Function *Callee = CI->getCalledFunction();
  880. Value *Ret = nullptr;
  881. if (UnsafeFPShrink && Callee->getName() == "pow" && TLI->has(LibFunc::powf)) {
  882. Ret = optimizeUnaryDoubleFP(CI, B, true);
  883. }
  884. FunctionType *FT = Callee->getFunctionType();
  885. // Just make sure this has 2 arguments of the same FP type, which match the
  886. // result type.
  887. if (FT->getNumParams() != 2 || FT->getReturnType() != FT->getParamType(0) ||
  888. FT->getParamType(0) != FT->getParamType(1) ||
  889. !FT->getParamType(0)->isFloatingPointTy())
  890. return Ret;
  891. Value *Op1 = CI->getArgOperand(0), *Op2 = CI->getArgOperand(1);
  892. if (ConstantFP *Op1C = dyn_cast<ConstantFP>(Op1)) {
  893. // pow(1.0, x) -> 1.0
  894. if (Op1C->isExactlyValue(1.0))
  895. return Op1C;
  896. // pow(2.0, x) -> exp2(x)
  897. if (Op1C->isExactlyValue(2.0) &&
  898. hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp2, LibFunc::exp2f,
  899. LibFunc::exp2l))
  900. return EmitUnaryFloatFnCall(Op2, "exp2", B, Callee->getAttributes());
  901. // pow(10.0, x) -> exp10(x)
  902. if (Op1C->isExactlyValue(10.0) &&
  903. hasUnaryFloatFn(TLI, Op1->getType(), LibFunc::exp10, LibFunc::exp10f,
  904. LibFunc::exp10l))
  905. return EmitUnaryFloatFnCall(Op2, TLI->getName(LibFunc::exp10), B,
  906. Callee->getAttributes());
  907. }
  908. ConstantFP *Op2C = dyn_cast<ConstantFP>(Op2);
  909. if (!Op2C)
  910. return Ret;
  911. if (Op2C->getValueAPF().isZero()) // pow(x, 0.0) -> 1.0
  912. return ConstantFP::get(CI->getType(), 1.0);
  913. if (Op2C->isExactlyValue(0.5) &&
  914. hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::sqrt, LibFunc::sqrtf,
  915. LibFunc::sqrtl) &&
  916. hasUnaryFloatFn(TLI, Op2->getType(), LibFunc::fabs, LibFunc::fabsf,
  917. LibFunc::fabsl)) {
  918. // Expand pow(x, 0.5) to (x == -infinity ? +infinity : fabs(sqrt(x))).
  919. // This is faster than calling pow, and still handles negative zero
  920. // and negative infinity correctly.
  921. // TODO: In fast-math mode, this could be just sqrt(x).
  922. // TODO: In finite-only mode, this could be just fabs(sqrt(x)).
  923. Value *Inf = ConstantFP::getInfinity(CI->getType());
  924. Value *NegInf = ConstantFP::getInfinity(CI->getType(), true);
  925. Value *Sqrt = EmitUnaryFloatFnCall(Op1, "sqrt", B, Callee->getAttributes());
  926. Value *FAbs =
  927. EmitUnaryFloatFnCall(Sqrt, "fabs", B, Callee->getAttributes());
  928. Value *FCmp = B.CreateFCmpOEQ(Op1, NegInf);
  929. Value *Sel = B.CreateSelect(FCmp, Inf, FAbs);
  930. return Sel;
  931. }
  932. if (Op2C->isExactlyValue(1.0)) // pow(x, 1.0) -> x
  933. return Op1;
  934. if (Op2C->isExactlyValue(2.0)) // pow(x, 2.0) -> x*x
  935. return B.CreateFMul(Op1, Op1, "pow2");
  936. if (Op2C->isExactlyValue(-1.0)) // pow(x, -1.0) -> 1.0/x
  937. return B.CreateFDiv(ConstantFP::get(CI->getType(), 1.0), Op1, "powrecip");
  938. return nullptr;
  939. }
  940. Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
  941. Function *Callee = CI->getCalledFunction();
  942. Function *Caller = CI->getParent()->getParent();
  943. Value *Ret = nullptr;
  944. if (UnsafeFPShrink && Callee->getName() == "exp2" &&
  945. TLI->has(LibFunc::exp2f)) {
  946. Ret = optimizeUnaryDoubleFP(CI, B, true);
  947. }
  948. FunctionType *FT = Callee->getFunctionType();
  949. // Just make sure this has 1 argument of FP type, which matches the
  950. // result type.
  951. if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
  952. !FT->getParamType(0)->isFloatingPointTy())
  953. return Ret;
  954. Value *Op = CI->getArgOperand(0);
  955. // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
  956. // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
  957. LibFunc::Func LdExp = LibFunc::ldexpl;
  958. if (Op->getType()->isFloatTy())
  959. LdExp = LibFunc::ldexpf;
  960. else if (Op->getType()->isDoubleTy())
  961. LdExp = LibFunc::ldexp;
  962. if (TLI->has(LdExp)) {
  963. Value *LdExpArg = nullptr;
  964. if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
  965. if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
  966. LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
  967. } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
  968. if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
  969. LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
  970. }
  971. if (LdExpArg) {
  972. Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
  973. if (!Op->getType()->isFloatTy())
  974. One = ConstantExpr::getFPExtend(One, Op->getType());
  975. Module *M = Caller->getParent();
  976. Value *Callee =
  977. M->getOrInsertFunction(TLI->getName(LdExp), Op->getType(),
  978. Op->getType(), B.getInt32Ty(), nullptr);
  979. CallInst *CI = B.CreateCall(Callee, {One, LdExpArg});
  980. if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
  981. CI->setCallingConv(F->getCallingConv());
  982. return CI;
  983. }
  984. }
  985. return Ret;
  986. }
  987. Value *LibCallSimplifier::optimizeFabs(CallInst *CI, IRBuilder<> &B) {
  988. Function *Callee = CI->getCalledFunction();
  989. Value *Ret = nullptr;
  990. if (Callee->getName() == "fabs" && TLI->has(LibFunc::fabsf)) {
  991. Ret = optimizeUnaryDoubleFP(CI, B, false);
  992. }
  993. FunctionType *FT = Callee->getFunctionType();
  994. // Make sure this has 1 argument of FP type which matches the result type.
  995. if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
  996. !FT->getParamType(0)->isFloatingPointTy())
  997. return Ret;
  998. Value *Op = CI->getArgOperand(0);
  999. if (Instruction *I = dyn_cast<Instruction>(Op)) {
  1000. // Fold fabs(x * x) -> x * x; any squared FP value must already be positive.
  1001. if (I->getOpcode() == Instruction::FMul)
  1002. if (I->getOperand(0) == I->getOperand(1))
  1003. return Op;
  1004. }
  1005. return Ret;
  1006. }
  1007. Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
  1008. Function *Callee = CI->getCalledFunction();
  1009. Value *Ret = nullptr;
  1010. if (TLI->has(LibFunc::sqrtf) && (Callee->getName() == "sqrt" ||
  1011. Callee->getIntrinsicID() == Intrinsic::sqrt))
  1012. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1013. // FIXME: For finer-grain optimization, we need intrinsics to have the same
  1014. // fast-math flag decorations that are applied to FP instructions. For now,
  1015. // we have to rely on the function-level unsafe-fp-math attribute to do this
  1016. // optimization because there's no other way to express that the sqrt can be
  1017. // reassociated.
  1018. Function *F = CI->getParent()->getParent();
  1019. if (F->hasFnAttribute("unsafe-fp-math")) {
  1020. // Check for unsafe-fp-math = true.
  1021. Attribute Attr = F->getFnAttribute("unsafe-fp-math");
  1022. if (Attr.getValueAsString() != "true")
  1023. return Ret;
  1024. }
  1025. Value *Op = CI->getArgOperand(0);
  1026. if (Instruction *I = dyn_cast<Instruction>(Op)) {
  1027. if (I->getOpcode() == Instruction::FMul && I->hasUnsafeAlgebra()) {
  1028. // We're looking for a repeated factor in a multiplication tree,
  1029. // so we can do this fold: sqrt(x * x) -> fabs(x);
  1030. // or this fold: sqrt(x * x * y) -> fabs(x) * sqrt(y).
  1031. Value *Op0 = I->getOperand(0);
  1032. Value *Op1 = I->getOperand(1);
  1033. Value *RepeatOp = nullptr;
  1034. Value *OtherOp = nullptr;
  1035. if (Op0 == Op1) {
  1036. // Simple match: the operands of the multiply are identical.
  1037. RepeatOp = Op0;
  1038. } else {
  1039. // Look for a more complicated pattern: one of the operands is itself
  1040. // a multiply, so search for a common factor in that multiply.
  1041. // Note: We don't bother looking any deeper than this first level or for
  1042. // variations of this pattern because instcombine's visitFMUL and/or the
  1043. // reassociation pass should give us this form.
  1044. Value *OtherMul0, *OtherMul1;
  1045. if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
  1046. // Pattern: sqrt((x * y) * z)
  1047. if (OtherMul0 == OtherMul1) {
  1048. // Matched: sqrt((x * x) * z)
  1049. RepeatOp = OtherMul0;
  1050. OtherOp = Op1;
  1051. }
  1052. }
  1053. }
  1054. if (RepeatOp) {
  1055. // Fast math flags for any created instructions should match the sqrt
  1056. // and multiply.
  1057. // FIXME: We're not checking the sqrt because it doesn't have
  1058. // fast-math-flags (see earlier comment).
  1059. IRBuilder<true, ConstantFolder,
  1060. IRBuilderDefaultInserter<true> >::FastMathFlagGuard Guard(B);
  1061. B.SetFastMathFlags(I->getFastMathFlags());
  1062. // If we found a repeated factor, hoist it out of the square root and
  1063. // replace it with the fabs of that factor.
  1064. Module *M = Callee->getParent();
  1065. Type *ArgType = Op->getType();
  1066. Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
  1067. Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
  1068. if (OtherOp) {
  1069. // If we found a non-repeated factor, we still need to get its square
  1070. // root. We then multiply that by the value that was simplified out
  1071. // of the square root calculation.
  1072. Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
  1073. Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
  1074. return B.CreateFMul(FabsCall, SqrtCall);
  1075. }
  1076. return FabsCall;
  1077. }
  1078. }
  1079. }
  1080. return Ret;
  1081. }
  1082. static bool isTrigLibCall(CallInst *CI);
  1083. static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
  1084. bool UseFloat, Value *&Sin, Value *&Cos,
  1085. Value *&SinCos);
  1086. Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
  1087. // Make sure the prototype is as expected, otherwise the rest of the
  1088. // function is probably invalid and likely to abort.
  1089. if (!isTrigLibCall(CI))
  1090. return nullptr;
  1091. Value *Arg = CI->getArgOperand(0);
  1092. SmallVector<CallInst *, 1> SinCalls;
  1093. SmallVector<CallInst *, 1> CosCalls;
  1094. SmallVector<CallInst *, 1> SinCosCalls;
  1095. bool IsFloat = Arg->getType()->isFloatTy();
  1096. // Look for all compatible sinpi, cospi and sincospi calls with the same
  1097. // argument. If there are enough (in some sense) we can make the
  1098. // substitution.
  1099. for (User *U : Arg->users())
  1100. classifyArgUse(U, CI->getParent(), IsFloat, SinCalls, CosCalls,
  1101. SinCosCalls);
  1102. // It's only worthwhile if both sinpi and cospi are actually used.
  1103. if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
  1104. return nullptr;
  1105. Value *Sin, *Cos, *SinCos;
  1106. insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
  1107. replaceTrigInsts(SinCalls, Sin);
  1108. replaceTrigInsts(CosCalls, Cos);
  1109. replaceTrigInsts(SinCosCalls, SinCos);
  1110. return nullptr;
  1111. }
  1112. static bool isTrigLibCall(CallInst *CI) {
  1113. Function *Callee = CI->getCalledFunction();
  1114. FunctionType *FT = Callee->getFunctionType();
  1115. // We can only hope to do anything useful if we can ignore things like errno
  1116. // and floating-point exceptions.
  1117. bool AttributesSafe =
  1118. CI->hasFnAttr(Attribute::NoUnwind) && CI->hasFnAttr(Attribute::ReadNone);
  1119. // Other than that we need float(float) or double(double)
  1120. return AttributesSafe && FT->getNumParams() == 1 &&
  1121. FT->getReturnType() == FT->getParamType(0) &&
  1122. (FT->getParamType(0)->isFloatTy() ||
  1123. FT->getParamType(0)->isDoubleTy());
  1124. }
  1125. void
  1126. LibCallSimplifier::classifyArgUse(Value *Val, BasicBlock *BB, bool IsFloat,
  1127. SmallVectorImpl<CallInst *> &SinCalls,
  1128. SmallVectorImpl<CallInst *> &CosCalls,
  1129. SmallVectorImpl<CallInst *> &SinCosCalls) {
  1130. CallInst *CI = dyn_cast<CallInst>(Val);
  1131. if (!CI)
  1132. return;
  1133. Function *Callee = CI->getCalledFunction();
  1134. StringRef FuncName = Callee->getName();
  1135. LibFunc::Func Func;
  1136. if (!TLI->getLibFunc(FuncName, Func) || !TLI->has(Func) || !isTrigLibCall(CI))
  1137. return;
  1138. if (IsFloat) {
  1139. if (Func == LibFunc::sinpif)
  1140. SinCalls.push_back(CI);
  1141. else if (Func == LibFunc::cospif)
  1142. CosCalls.push_back(CI);
  1143. else if (Func == LibFunc::sincospif_stret)
  1144. SinCosCalls.push_back(CI);
  1145. } else {
  1146. if (Func == LibFunc::sinpi)
  1147. SinCalls.push_back(CI);
  1148. else if (Func == LibFunc::cospi)
  1149. CosCalls.push_back(CI);
  1150. else if (Func == LibFunc::sincospi_stret)
  1151. SinCosCalls.push_back(CI);
  1152. }
  1153. }
  1154. void LibCallSimplifier::replaceTrigInsts(SmallVectorImpl<CallInst *> &Calls,
  1155. Value *Res) {
  1156. for (SmallVectorImpl<CallInst *>::iterator I = Calls.begin(), E = Calls.end();
  1157. I != E; ++I) {
  1158. replaceAllUsesWith(*I, Res);
  1159. }
  1160. }
  1161. void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
  1162. bool UseFloat, Value *&Sin, Value *&Cos, Value *&SinCos) {
  1163. Type *ArgTy = Arg->getType();
  1164. Type *ResTy;
  1165. StringRef Name;
  1166. Triple T(OrigCallee->getParent()->getTargetTriple());
  1167. if (UseFloat) {
  1168. Name = "__sincospif_stret";
  1169. assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
  1170. // x86_64 can't use {float, float} since that would be returned in both
  1171. // xmm0 and xmm1, which isn't what a real struct would do.
  1172. ResTy = T.getArch() == Triple::x86_64
  1173. ? static_cast<Type *>(VectorType::get(ArgTy, 2))
  1174. : static_cast<Type *>(StructType::get(ArgTy, ArgTy, nullptr));
  1175. } else {
  1176. Name = "__sincospi_stret";
  1177. ResTy = StructType::get(ArgTy, ArgTy, nullptr);
  1178. }
  1179. Module *M = OrigCallee->getParent();
  1180. Value *Callee = M->getOrInsertFunction(Name, OrigCallee->getAttributes(),
  1181. ResTy, ArgTy, nullptr);
  1182. if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
  1183. // If the argument is an instruction, it must dominate all uses so put our
  1184. // sincos call there.
  1185. BasicBlock::iterator Loc = ArgInst;
  1186. B.SetInsertPoint(ArgInst->getParent(), ++Loc);
  1187. } else {
  1188. // Otherwise (e.g. for a constant) the beginning of the function is as
  1189. // good a place as any.
  1190. BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
  1191. B.SetInsertPoint(&EntryBB, EntryBB.begin());
  1192. }
  1193. SinCos = B.CreateCall(Callee, Arg, "sincospi");
  1194. if (SinCos->getType()->isStructTy()) {
  1195. Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
  1196. Cos = B.CreateExtractValue(SinCos, 1, "cospi");
  1197. } else {
  1198. Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
  1199. "sinpi");
  1200. Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
  1201. "cospi");
  1202. }
  1203. }
  1204. //===----------------------------------------------------------------------===//
  1205. // Integer Library Call Optimizations
  1206. //===----------------------------------------------------------------------===//
  1207. Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
  1208. Function *Callee = CI->getCalledFunction();
  1209. FunctionType *FT = Callee->getFunctionType();
  1210. // Just make sure this has 2 arguments of the same FP type, which match the
  1211. // result type.
  1212. if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy(32) ||
  1213. !FT->getParamType(0)->isIntegerTy())
  1214. return nullptr;
  1215. Value *Op = CI->getArgOperand(0);
  1216. // Constant fold.
  1217. if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
  1218. if (CI->isZero()) // ffs(0) -> 0.
  1219. return B.getInt32(0);
  1220. // ffs(c) -> cttz(c)+1
  1221. return B.getInt32(CI->getValue().countTrailingZeros() + 1);
  1222. }
  1223. // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
  1224. Type *ArgType = Op->getType();
  1225. Value *F =
  1226. Intrinsic::getDeclaration(Callee->getParent(), Intrinsic::cttz, ArgType);
  1227. Value *V = B.CreateCall(F, {Op, B.getFalse()}, "cttz");
  1228. V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
  1229. V = B.CreateIntCast(V, B.getInt32Ty(), false);
  1230. Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
  1231. return B.CreateSelect(Cond, V, B.getInt32(0));
  1232. }
  1233. Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
  1234. Function *Callee = CI->getCalledFunction();
  1235. FunctionType *FT = Callee->getFunctionType();
  1236. // We require integer(integer) where the types agree.
  1237. if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
  1238. FT->getParamType(0) != FT->getReturnType())
  1239. return nullptr;
  1240. // abs(x) -> x >s -1 ? x : -x
  1241. Value *Op = CI->getArgOperand(0);
  1242. Value *Pos =
  1243. B.CreateICmpSGT(Op, Constant::getAllOnesValue(Op->getType()), "ispos");
  1244. Value *Neg = B.CreateNeg(Op, "neg");
  1245. return B.CreateSelect(Pos, Op, Neg);
  1246. }
  1247. Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
  1248. Function *Callee = CI->getCalledFunction();
  1249. FunctionType *FT = Callee->getFunctionType();
  1250. // We require integer(i32)
  1251. if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
  1252. !FT->getParamType(0)->isIntegerTy(32))
  1253. return nullptr;
  1254. // isdigit(c) -> (c-'0') <u 10
  1255. Value *Op = CI->getArgOperand(0);
  1256. Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
  1257. Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
  1258. return B.CreateZExt(Op, CI->getType());
  1259. }
  1260. Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
  1261. Function *Callee = CI->getCalledFunction();
  1262. FunctionType *FT = Callee->getFunctionType();
  1263. // We require integer(i32)
  1264. if (FT->getNumParams() != 1 || !FT->getReturnType()->isIntegerTy() ||
  1265. !FT->getParamType(0)->isIntegerTy(32))
  1266. return nullptr;
  1267. // isascii(c) -> c <u 128
  1268. Value *Op = CI->getArgOperand(0);
  1269. Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
  1270. return B.CreateZExt(Op, CI->getType());
  1271. }
  1272. Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
  1273. Function *Callee = CI->getCalledFunction();
  1274. FunctionType *FT = Callee->getFunctionType();
  1275. // We require i32(i32)
  1276. if (FT->getNumParams() != 1 || FT->getReturnType() != FT->getParamType(0) ||
  1277. !FT->getParamType(0)->isIntegerTy(32))
  1278. return nullptr;
  1279. // toascii(c) -> c & 0x7f
  1280. return B.CreateAnd(CI->getArgOperand(0),
  1281. ConstantInt::get(CI->getType(), 0x7F));
  1282. }
  1283. //===----------------------------------------------------------------------===//
  1284. // Formatting and IO Library Call Optimizations
  1285. //===----------------------------------------------------------------------===//
  1286. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
  1287. Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
  1288. int StreamArg) {
  1289. // Error reporting calls should be cold, mark them as such.
  1290. // This applies even to non-builtin calls: it is only a hint and applies to
  1291. // functions that the frontend might not understand as builtins.
  1292. // This heuristic was suggested in:
  1293. // Improving Static Branch Prediction in a Compiler
  1294. // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
  1295. // Proceedings of PACT'98, Oct. 1998, IEEE
  1296. Function *Callee = CI->getCalledFunction();
  1297. if (!CI->hasFnAttr(Attribute::Cold) &&
  1298. isReportingError(Callee, CI, StreamArg)) {
  1299. CI->addAttribute(AttributeSet::FunctionIndex, Attribute::Cold);
  1300. }
  1301. return nullptr;
  1302. }
  1303. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
  1304. if (!ColdErrorCalls)
  1305. return false;
  1306. if (!Callee || !Callee->isDeclaration())
  1307. return false;
  1308. if (StreamArg < 0)
  1309. return true;
  1310. // These functions might be considered cold, but only if their stream
  1311. // argument is stderr.
  1312. if (StreamArg >= (int)CI->getNumArgOperands())
  1313. return false;
  1314. LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
  1315. if (!LI)
  1316. return false;
  1317. GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
  1318. if (!GV || !GV->isDeclaration())
  1319. return false;
  1320. return GV->getName() == "stderr";
  1321. }
  1322. Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
  1323. // Check for a fixed format string.
  1324. StringRef FormatStr;
  1325. if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
  1326. return nullptr;
  1327. // Empty format string -> noop.
  1328. if (FormatStr.empty()) // Tolerate printf's declared void.
  1329. return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
  1330. // Do not do any of the following transformations if the printf return value
  1331. // is used, in general the printf return value is not compatible with either
  1332. // putchar() or puts().
  1333. if (!CI->use_empty())
  1334. return nullptr;
  1335. // printf("x") -> putchar('x'), even for '%'.
  1336. if (FormatStr.size() == 1) {
  1337. Value *Res = EmitPutChar(B.getInt32(FormatStr[0]), B, TLI);
  1338. if (CI->use_empty() || !Res)
  1339. return Res;
  1340. return B.CreateIntCast(Res, CI->getType(), true);
  1341. }
  1342. // printf("foo\n") --> puts("foo")
  1343. if (FormatStr[FormatStr.size() - 1] == '\n' &&
  1344. FormatStr.find('%') == StringRef::npos) { // No format characters.
  1345. // Create a string literal with no \n on it. We expect the constant merge
  1346. // pass to be run after this pass, to merge duplicate strings.
  1347. FormatStr = FormatStr.drop_back();
  1348. Value *GV = B.CreateGlobalString(FormatStr, "str");
  1349. Value *NewCI = EmitPutS(GV, B, TLI);
  1350. return (CI->use_empty() || !NewCI)
  1351. ? NewCI
  1352. : ConstantInt::get(CI->getType(), FormatStr.size() + 1);
  1353. }
  1354. // Optimize specific format strings.
  1355. // printf("%c", chr) --> putchar(chr)
  1356. if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
  1357. CI->getArgOperand(1)->getType()->isIntegerTy()) {
  1358. Value *Res = EmitPutChar(CI->getArgOperand(1), B, TLI);
  1359. if (CI->use_empty() || !Res)
  1360. return Res;
  1361. return B.CreateIntCast(Res, CI->getType(), true);
  1362. }
  1363. // printf("%s\n", str) --> puts(str)
  1364. if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
  1365. CI->getArgOperand(1)->getType()->isPointerTy()) {
  1366. return EmitPutS(CI->getArgOperand(1), B, TLI);
  1367. }
  1368. return nullptr;
  1369. }
  1370. Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
  1371. Function *Callee = CI->getCalledFunction();
  1372. // Require one fixed pointer argument and an integer/void result.
  1373. FunctionType *FT = Callee->getFunctionType();
  1374. if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
  1375. !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
  1376. return nullptr;
  1377. if (Value *V = optimizePrintFString(CI, B)) {
  1378. return V;
  1379. }
  1380. // printf(format, ...) -> iprintf(format, ...) if no floating point
  1381. // arguments.
  1382. if (TLI->has(LibFunc::iprintf) && !callHasFloatingPointArgument(CI)) {
  1383. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1384. Constant *IPrintFFn =
  1385. M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
  1386. CallInst *New = cast<CallInst>(CI->clone());
  1387. New->setCalledFunction(IPrintFFn);
  1388. B.Insert(New);
  1389. return New;
  1390. }
  1391. return nullptr;
  1392. }
  1393. Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
  1394. // Check for a fixed format string.
  1395. StringRef FormatStr;
  1396. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  1397. return nullptr;
  1398. // If we just have a format string (nothing else crazy) transform it.
  1399. if (CI->getNumArgOperands() == 2) {
  1400. // Make sure there's no % in the constant array. We could try to handle
  1401. // %% -> % in the future if we cared.
  1402. for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
  1403. if (FormatStr[i] == '%')
  1404. return nullptr; // we found a format specifier, bail out.
  1405. // sprintf(str, fmt) -> llvm.memcpy(str, fmt, strlen(fmt)+1, 1)
  1406. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  1407. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  1408. FormatStr.size() + 1),
  1409. 1); // Copy the null byte.
  1410. return ConstantInt::get(CI->getType(), FormatStr.size());
  1411. }
  1412. // The remaining optimizations require the format string to be "%s" or "%c"
  1413. // and have an extra operand.
  1414. if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
  1415. CI->getNumArgOperands() < 3)
  1416. return nullptr;
  1417. // Decode the second character of the format string.
  1418. if (FormatStr[1] == 'c') {
  1419. // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
  1420. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  1421. return nullptr;
  1422. Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
  1423. Value *Ptr = CastToCStr(CI->getArgOperand(0), B);
  1424. B.CreateStore(V, Ptr);
  1425. Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
  1426. B.CreateStore(B.getInt8(0), Ptr);
  1427. return ConstantInt::get(CI->getType(), 1);
  1428. }
  1429. if (FormatStr[1] == 's') {
  1430. // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
  1431. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  1432. return nullptr;
  1433. Value *Len = EmitStrLen(CI->getArgOperand(2), B, DL, TLI);
  1434. if (!Len)
  1435. return nullptr;
  1436. Value *IncLen =
  1437. B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
  1438. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(2), IncLen, 1);
  1439. // The sprintf result is the unincremented number of bytes in the string.
  1440. return B.CreateIntCast(Len, CI->getType(), false);
  1441. }
  1442. return nullptr;
  1443. }
  1444. Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
  1445. Function *Callee = CI->getCalledFunction();
  1446. // Require two fixed pointer arguments and an integer result.
  1447. FunctionType *FT = Callee->getFunctionType();
  1448. if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
  1449. !FT->getParamType(1)->isPointerTy() ||
  1450. !FT->getReturnType()->isIntegerTy())
  1451. return nullptr;
  1452. if (Value *V = optimizeSPrintFString(CI, B)) {
  1453. return V;
  1454. }
  1455. // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
  1456. // point arguments.
  1457. if (TLI->has(LibFunc::siprintf) && !callHasFloatingPointArgument(CI)) {
  1458. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1459. Constant *SIPrintFFn =
  1460. M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
  1461. CallInst *New = cast<CallInst>(CI->clone());
  1462. New->setCalledFunction(SIPrintFFn);
  1463. B.Insert(New);
  1464. return New;
  1465. }
  1466. return nullptr;
  1467. }
  1468. Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
  1469. optimizeErrorReporting(CI, B, 0);
  1470. // All the optimizations depend on the format string.
  1471. StringRef FormatStr;
  1472. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  1473. return nullptr;
  1474. // Do not do any of the following transformations if the fprintf return
  1475. // value is used, in general the fprintf return value is not compatible
  1476. // with fwrite(), fputc() or fputs().
  1477. if (!CI->use_empty())
  1478. return nullptr;
  1479. // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
  1480. if (CI->getNumArgOperands() == 2) {
  1481. for (unsigned i = 0, e = FormatStr.size(); i != e; ++i)
  1482. if (FormatStr[i] == '%') // Could handle %% -> % if we cared.
  1483. return nullptr; // We found a format specifier.
  1484. return EmitFWrite(
  1485. CI->getArgOperand(1),
  1486. ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
  1487. CI->getArgOperand(0), B, DL, TLI);
  1488. }
  1489. // The remaining optimizations require the format string to be "%s" or "%c"
  1490. // and have an extra operand.
  1491. if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
  1492. CI->getNumArgOperands() < 3)
  1493. return nullptr;
  1494. // Decode the second character of the format string.
  1495. if (FormatStr[1] == 'c') {
  1496. // fprintf(F, "%c", chr) --> fputc(chr, F)
  1497. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  1498. return nullptr;
  1499. return EmitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
  1500. }
  1501. if (FormatStr[1] == 's') {
  1502. // fprintf(F, "%s", str) --> fputs(str, F)
  1503. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  1504. return nullptr;
  1505. return EmitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
  1506. }
  1507. return nullptr;
  1508. }
  1509. Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
  1510. Function *Callee = CI->getCalledFunction();
  1511. // Require two fixed paramters as pointers and integer result.
  1512. FunctionType *FT = Callee->getFunctionType();
  1513. if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
  1514. !FT->getParamType(1)->isPointerTy() ||
  1515. !FT->getReturnType()->isIntegerTy())
  1516. return nullptr;
  1517. if (Value *V = optimizeFPrintFString(CI, B)) {
  1518. return V;
  1519. }
  1520. // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
  1521. // floating point arguments.
  1522. if (TLI->has(LibFunc::fiprintf) && !callHasFloatingPointArgument(CI)) {
  1523. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1524. Constant *FIPrintFFn =
  1525. M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
  1526. CallInst *New = cast<CallInst>(CI->clone());
  1527. New->setCalledFunction(FIPrintFFn);
  1528. B.Insert(New);
  1529. return New;
  1530. }
  1531. return nullptr;
  1532. }
  1533. Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
  1534. optimizeErrorReporting(CI, B, 3);
  1535. Function *Callee = CI->getCalledFunction();
  1536. // Require a pointer, an integer, an integer, a pointer, returning integer.
  1537. FunctionType *FT = Callee->getFunctionType();
  1538. if (FT->getNumParams() != 4 || !FT->getParamType(0)->isPointerTy() ||
  1539. !FT->getParamType(1)->isIntegerTy() ||
  1540. !FT->getParamType(2)->isIntegerTy() ||
  1541. !FT->getParamType(3)->isPointerTy() ||
  1542. !FT->getReturnType()->isIntegerTy())
  1543. return nullptr;
  1544. // Get the element size and count.
  1545. ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  1546. ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  1547. if (!SizeC || !CountC)
  1548. return nullptr;
  1549. uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
  1550. // If this is writing zero records, remove the call (it's a noop).
  1551. if (Bytes == 0)
  1552. return ConstantInt::get(CI->getType(), 0);
  1553. // If this is writing one byte, turn it into fputc.
  1554. // This optimisation is only valid, if the return value is unused.
  1555. if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
  1556. Value *Char = B.CreateLoad(CastToCStr(CI->getArgOperand(0), B), "char");
  1557. Value *NewCI = EmitFPutC(Char, CI->getArgOperand(3), B, TLI);
  1558. return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
  1559. }
  1560. return nullptr;
  1561. }
  1562. Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
  1563. optimizeErrorReporting(CI, B, 1);
  1564. Function *Callee = CI->getCalledFunction();
  1565. // Require two pointers. Also, we can't optimize if return value is used.
  1566. FunctionType *FT = Callee->getFunctionType();
  1567. if (FT->getNumParams() != 2 || !FT->getParamType(0)->isPointerTy() ||
  1568. !FT->getParamType(1)->isPointerTy() || !CI->use_empty())
  1569. return nullptr;
  1570. // fputs(s,F) --> fwrite(s,1,strlen(s),F)
  1571. uint64_t Len = GetStringLength(CI->getArgOperand(0));
  1572. if (!Len)
  1573. return nullptr;
  1574. // Known to have no uses (see above).
  1575. return EmitFWrite(
  1576. CI->getArgOperand(0),
  1577. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
  1578. CI->getArgOperand(1), B, DL, TLI);
  1579. }
  1580. Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
  1581. Function *Callee = CI->getCalledFunction();
  1582. // Require one fixed pointer argument and an integer/void result.
  1583. FunctionType *FT = Callee->getFunctionType();
  1584. if (FT->getNumParams() < 1 || !FT->getParamType(0)->isPointerTy() ||
  1585. !(FT->getReturnType()->isIntegerTy() || FT->getReturnType()->isVoidTy()))
  1586. return nullptr;
  1587. // Check for a constant string.
  1588. StringRef Str;
  1589. if (!getConstantStringInfo(CI->getArgOperand(0), Str))
  1590. return nullptr;
  1591. if (Str.empty() && CI->use_empty()) {
  1592. // puts("") -> putchar('\n')
  1593. Value *Res = EmitPutChar(B.getInt32('\n'), B, TLI);
  1594. if (CI->use_empty() || !Res)
  1595. return Res;
  1596. return B.CreateIntCast(Res, CI->getType(), true);
  1597. }
  1598. return nullptr;
  1599. }
  1600. bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
  1601. LibFunc::Func Func;
  1602. SmallString<20> FloatFuncName = FuncName;
  1603. FloatFuncName += 'f';
  1604. if (TLI->getLibFunc(FloatFuncName, Func))
  1605. return TLI->has(Func);
  1606. return false;
  1607. }
  1608. Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
  1609. IRBuilder<> &Builder) {
  1610. LibFunc::Func Func;
  1611. Function *Callee = CI->getCalledFunction();
  1612. StringRef FuncName = Callee->getName();
  1613. // Check for string/memory library functions.
  1614. if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
  1615. // Make sure we never change the calling convention.
  1616. assert((ignoreCallingConv(Func) ||
  1617. CI->getCallingConv() == llvm::CallingConv::C) &&
  1618. "Optimizing string/memory libcall would change the calling convention");
  1619. switch (Func) {
  1620. case LibFunc::strcat:
  1621. return optimizeStrCat(CI, Builder);
  1622. case LibFunc::strncat:
  1623. return optimizeStrNCat(CI, Builder);
  1624. case LibFunc::strchr:
  1625. return optimizeStrChr(CI, Builder);
  1626. case LibFunc::strrchr:
  1627. return optimizeStrRChr(CI, Builder);
  1628. case LibFunc::strcmp:
  1629. return optimizeStrCmp(CI, Builder);
  1630. case LibFunc::strncmp:
  1631. return optimizeStrNCmp(CI, Builder);
  1632. case LibFunc::strcpy:
  1633. return optimizeStrCpy(CI, Builder);
  1634. case LibFunc::stpcpy:
  1635. return optimizeStpCpy(CI, Builder);
  1636. case LibFunc::strncpy:
  1637. return optimizeStrNCpy(CI, Builder);
  1638. case LibFunc::strlen:
  1639. return optimizeStrLen(CI, Builder);
  1640. case LibFunc::strpbrk:
  1641. return optimizeStrPBrk(CI, Builder);
  1642. case LibFunc::strtol:
  1643. case LibFunc::strtod:
  1644. case LibFunc::strtof:
  1645. case LibFunc::strtoul:
  1646. case LibFunc::strtoll:
  1647. case LibFunc::strtold:
  1648. case LibFunc::strtoull:
  1649. return optimizeStrTo(CI, Builder);
  1650. case LibFunc::strspn:
  1651. return optimizeStrSpn(CI, Builder);
  1652. case LibFunc::strcspn:
  1653. return optimizeStrCSpn(CI, Builder);
  1654. case LibFunc::strstr:
  1655. return optimizeStrStr(CI, Builder);
  1656. case LibFunc::memchr:
  1657. return optimizeMemChr(CI, Builder);
  1658. case LibFunc::memcmp:
  1659. return optimizeMemCmp(CI, Builder);
  1660. case LibFunc::memcpy:
  1661. return optimizeMemCpy(CI, Builder);
  1662. case LibFunc::memmove:
  1663. return optimizeMemMove(CI, Builder);
  1664. case LibFunc::memset:
  1665. return optimizeMemSet(CI, Builder);
  1666. default:
  1667. break;
  1668. }
  1669. }
  1670. return nullptr;
  1671. }
  1672. Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
  1673. if (CI->isNoBuiltin())
  1674. return nullptr;
  1675. LibFunc::Func Func;
  1676. Function *Callee = CI->getCalledFunction();
  1677. StringRef FuncName = Callee->getName();
  1678. IRBuilder<> Builder(CI);
  1679. bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
  1680. // Command-line parameter overrides function attribute.
  1681. if (false) // HLSL Change - EnableUnsafeFPShrink.getNumOccurrences() > 0)
  1682. UnsafeFPShrink = EnableUnsafeFPShrink;
  1683. else if (Callee->hasFnAttribute("unsafe-fp-math")) {
  1684. // FIXME: This is the same problem as described in optimizeSqrt().
  1685. // If calls gain access to IR-level FMF, then use that instead of a
  1686. // function attribute.
  1687. // Check for unsafe-fp-math = true.
  1688. Attribute Attr = Callee->getFnAttribute("unsafe-fp-math");
  1689. if (Attr.getValueAsString() == "true")
  1690. UnsafeFPShrink = true;
  1691. }
  1692. // First, check for intrinsics.
  1693. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
  1694. if (!isCallingConvC)
  1695. return nullptr;
  1696. switch (II->getIntrinsicID()) {
  1697. case Intrinsic::pow:
  1698. return optimizePow(CI, Builder);
  1699. case Intrinsic::exp2:
  1700. return optimizeExp2(CI, Builder);
  1701. case Intrinsic::fabs:
  1702. return optimizeFabs(CI, Builder);
  1703. case Intrinsic::sqrt:
  1704. return optimizeSqrt(CI, Builder);
  1705. default:
  1706. return nullptr;
  1707. }
  1708. }
  1709. // Also try to simplify calls to fortified library functions.
  1710. if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
  1711. // Try to further simplify the result.
  1712. CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
  1713. if (SimplifiedCI && SimplifiedCI->getCalledFunction())
  1714. if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, Builder)) {
  1715. // If we were able to further simplify, remove the now redundant call.
  1716. SimplifiedCI->replaceAllUsesWith(V);
  1717. SimplifiedCI->eraseFromParent();
  1718. return V;
  1719. }
  1720. return SimplifiedFortifiedCI;
  1721. }
  1722. // Then check for known library functions.
  1723. if (TLI->getLibFunc(FuncName, Func) && TLI->has(Func)) {
  1724. // We never change the calling convention.
  1725. if (!ignoreCallingConv(Func) && !isCallingConvC)
  1726. return nullptr;
  1727. if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
  1728. return V;
  1729. switch (Func) {
  1730. case LibFunc::cosf:
  1731. case LibFunc::cos:
  1732. case LibFunc::cosl:
  1733. return optimizeCos(CI, Builder);
  1734. case LibFunc::sinpif:
  1735. case LibFunc::sinpi:
  1736. case LibFunc::cospif:
  1737. case LibFunc::cospi:
  1738. return optimizeSinCosPi(CI, Builder);
  1739. case LibFunc::powf:
  1740. case LibFunc::pow:
  1741. case LibFunc::powl:
  1742. return optimizePow(CI, Builder);
  1743. case LibFunc::exp2l:
  1744. case LibFunc::exp2:
  1745. case LibFunc::exp2f:
  1746. return optimizeExp2(CI, Builder);
  1747. case LibFunc::fabsf:
  1748. case LibFunc::fabs:
  1749. case LibFunc::fabsl:
  1750. return optimizeFabs(CI, Builder);
  1751. case LibFunc::sqrtf:
  1752. case LibFunc::sqrt:
  1753. case LibFunc::sqrtl:
  1754. return optimizeSqrt(CI, Builder);
  1755. case LibFunc::ffs:
  1756. case LibFunc::ffsl:
  1757. case LibFunc::ffsll:
  1758. return optimizeFFS(CI, Builder);
  1759. case LibFunc::abs:
  1760. case LibFunc::labs:
  1761. case LibFunc::llabs:
  1762. return optimizeAbs(CI, Builder);
  1763. case LibFunc::isdigit:
  1764. return optimizeIsDigit(CI, Builder);
  1765. case LibFunc::isascii:
  1766. return optimizeIsAscii(CI, Builder);
  1767. case LibFunc::toascii:
  1768. return optimizeToAscii(CI, Builder);
  1769. case LibFunc::printf:
  1770. return optimizePrintF(CI, Builder);
  1771. case LibFunc::sprintf:
  1772. return optimizeSPrintF(CI, Builder);
  1773. case LibFunc::fprintf:
  1774. return optimizeFPrintF(CI, Builder);
  1775. case LibFunc::fwrite:
  1776. return optimizeFWrite(CI, Builder);
  1777. case LibFunc::fputs:
  1778. return optimizeFPuts(CI, Builder);
  1779. case LibFunc::puts:
  1780. return optimizePuts(CI, Builder);
  1781. case LibFunc::perror:
  1782. return optimizeErrorReporting(CI, Builder);
  1783. case LibFunc::vfprintf:
  1784. case LibFunc::fiprintf:
  1785. return optimizeErrorReporting(CI, Builder, 0);
  1786. case LibFunc::fputc:
  1787. return optimizeErrorReporting(CI, Builder, 1);
  1788. case LibFunc::ceil:
  1789. case LibFunc::floor:
  1790. case LibFunc::rint:
  1791. case LibFunc::round:
  1792. case LibFunc::nearbyint:
  1793. case LibFunc::trunc:
  1794. if (hasFloatVersion(FuncName))
  1795. return optimizeUnaryDoubleFP(CI, Builder, false);
  1796. return nullptr;
  1797. case LibFunc::acos:
  1798. case LibFunc::acosh:
  1799. case LibFunc::asin:
  1800. case LibFunc::asinh:
  1801. case LibFunc::atan:
  1802. case LibFunc::atanh:
  1803. case LibFunc::cbrt:
  1804. case LibFunc::cosh:
  1805. case LibFunc::exp:
  1806. case LibFunc::exp10:
  1807. case LibFunc::expm1:
  1808. case LibFunc::log:
  1809. case LibFunc::log10:
  1810. case LibFunc::log1p:
  1811. case LibFunc::log2:
  1812. case LibFunc::logb:
  1813. case LibFunc::sin:
  1814. case LibFunc::sinh:
  1815. case LibFunc::tan:
  1816. case LibFunc::tanh:
  1817. if (UnsafeFPShrink && hasFloatVersion(FuncName))
  1818. return optimizeUnaryDoubleFP(CI, Builder, true);
  1819. return nullptr;
  1820. case LibFunc::copysign:
  1821. case LibFunc::fmin:
  1822. case LibFunc::fmax:
  1823. if (hasFloatVersion(FuncName))
  1824. return optimizeBinaryDoubleFP(CI, Builder);
  1825. return nullptr;
  1826. default:
  1827. return nullptr;
  1828. }
  1829. }
  1830. return nullptr;
  1831. }
  1832. LibCallSimplifier::LibCallSimplifier(
  1833. const DataLayout &DL, const TargetLibraryInfo *TLI,
  1834. function_ref<void(Instruction *, Value *)> Replacer)
  1835. : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), UnsafeFPShrink(false),
  1836. Replacer(Replacer) {}
  1837. void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
  1838. // Indirect through the replacer used in this instance.
  1839. Replacer(I, With);
  1840. }
  1841. /*static*/ void LibCallSimplifier::replaceAllUsesWithDefault(Instruction *I,
  1842. Value *With) {
  1843. I->replaceAllUsesWith(With);
  1844. I->eraseFromParent();
  1845. }
  1846. // TODO:
  1847. // Additional cases that we need to add to this file:
  1848. //
  1849. // cbrt:
  1850. // * cbrt(expN(X)) -> expN(x/3)
  1851. // * cbrt(sqrt(x)) -> pow(x,1/6)
  1852. // * cbrt(sqrt(x)) -> pow(x,1/9)
  1853. //
  1854. // exp, expf, expl:
  1855. // * exp(log(x)) -> x
  1856. //
  1857. // log, logf, logl:
  1858. // * log(exp(x)) -> x
  1859. // * log(x**y) -> y*log(x)
  1860. // * log(exp(y)) -> y*log(e)
  1861. // * log(exp2(y)) -> y*log(2)
  1862. // * log(exp10(y)) -> y*log(10)
  1863. // * log(sqrt(x)) -> 0.5*log(x)
  1864. // * log(pow(x,y)) -> y*log(x)
  1865. //
  1866. // lround, lroundf, lroundl:
  1867. // * lround(cnst) -> cnst'
  1868. //
  1869. // pow, powf, powl:
  1870. // * pow(exp(x),y) -> exp(x*y)
  1871. // * pow(sqrt(x),y) -> pow(x,y*0.5)
  1872. // * pow(pow(x,y),z)-> pow(x,y*z)
  1873. //
  1874. // round, roundf, roundl:
  1875. // * round(cnst) -> cnst'
  1876. //
  1877. // signbit:
  1878. // * signbit(cnst) -> cnst'
  1879. // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
  1880. //
  1881. // sqrt, sqrtf, sqrtl:
  1882. // * sqrt(expN(x)) -> expN(x*0.5)
  1883. // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
  1884. // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
  1885. //
  1886. // tan, tanf, tanl:
  1887. // * tan(atan(x)) -> x
  1888. //
  1889. // trunc, truncf, truncl:
  1890. // * trunc(cnst) -> cnst'
  1891. //
  1892. //
  1893. //===----------------------------------------------------------------------===//
  1894. // Fortified Library Call Optimizations
  1895. //===----------------------------------------------------------------------===//
  1896. bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
  1897. unsigned ObjSizeOp,
  1898. unsigned SizeOp,
  1899. bool isString) {
  1900. if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
  1901. return true;
  1902. if (ConstantInt *ObjSizeCI =
  1903. dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
  1904. if (ObjSizeCI->isAllOnesValue())
  1905. return true;
  1906. // If the object size wasn't -1 (unknown), bail out if we were asked to.
  1907. if (OnlyLowerUnknownSize)
  1908. return false;
  1909. if (isString) {
  1910. uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
  1911. // If the length is 0 we don't know how long it is and so we can't
  1912. // remove the check.
  1913. if (Len == 0)
  1914. return false;
  1915. return ObjSizeCI->getZExtValue() >= Len;
  1916. }
  1917. if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
  1918. return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
  1919. }
  1920. return false;
  1921. }
  1922. Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI, IRBuilder<> &B) {
  1923. Function *Callee = CI->getCalledFunction();
  1924. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memcpy_chk))
  1925. return nullptr;
  1926. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  1927. B.CreateMemCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  1928. CI->getArgOperand(2), 1);
  1929. return CI->getArgOperand(0);
  1930. }
  1931. return nullptr;
  1932. }
  1933. Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI, IRBuilder<> &B) {
  1934. Function *Callee = CI->getCalledFunction();
  1935. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memmove_chk))
  1936. return nullptr;
  1937. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  1938. B.CreateMemMove(CI->getArgOperand(0), CI->getArgOperand(1),
  1939. CI->getArgOperand(2), 1);
  1940. return CI->getArgOperand(0);
  1941. }
  1942. return nullptr;
  1943. }
  1944. Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI, IRBuilder<> &B) {
  1945. Function *Callee = CI->getCalledFunction();
  1946. if (!checkStringCopyLibFuncSignature(Callee, LibFunc::memset_chk))
  1947. return nullptr;
  1948. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  1949. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  1950. B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
  1951. return CI->getArgOperand(0);
  1952. }
  1953. return nullptr;
  1954. }
  1955. Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
  1956. IRBuilder<> &B,
  1957. LibFunc::Func Func) {
  1958. Function *Callee = CI->getCalledFunction();
  1959. StringRef Name = Callee->getName();
  1960. const DataLayout &DL = CI->getModule()->getDataLayout();
  1961. if (!checkStringCopyLibFuncSignature(Callee, Func))
  1962. return nullptr;
  1963. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
  1964. *ObjSize = CI->getArgOperand(2);
  1965. // __stpcpy_chk(x,x,...) -> x+strlen(x)
  1966. if (Func == LibFunc::stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
  1967. Value *StrLen = EmitStrLen(Src, B, DL, TLI);
  1968. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  1969. }
  1970. // If a) we don't have any length information, or b) we know this will
  1971. // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
  1972. // st[rp]cpy_chk call which may fail at runtime if the size is too long.
  1973. // TODO: It might be nice to get a maximum length out of the possible
  1974. // string lengths for varying.
  1975. if (isFortifiedCallFoldable(CI, 2, 1, true))
  1976. return EmitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
  1977. if (OnlyLowerUnknownSize)
  1978. return nullptr;
  1979. // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
  1980. uint64_t Len = GetStringLength(Src);
  1981. if (Len == 0)
  1982. return nullptr;
  1983. Type *SizeTTy = DL.getIntPtrType(CI->getContext());
  1984. Value *LenV = ConstantInt::get(SizeTTy, Len);
  1985. Value *Ret = EmitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
  1986. // If the function was an __stpcpy_chk, and we were able to fold it into
  1987. // a __memcpy_chk, we still need to return the correct end pointer.
  1988. if (Ret && Func == LibFunc::stpcpy_chk)
  1989. return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
  1990. return Ret;
  1991. }
  1992. Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
  1993. IRBuilder<> &B,
  1994. LibFunc::Func Func) {
  1995. Function *Callee = CI->getCalledFunction();
  1996. StringRef Name = Callee->getName();
  1997. if (!checkStringCopyLibFuncSignature(Callee, Func))
  1998. return nullptr;
  1999. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  2000. Value *Ret = EmitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  2001. CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
  2002. return Ret;
  2003. }
  2004. return nullptr;
  2005. }
  2006. Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
  2007. // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
  2008. // Some clang users checked for _chk libcall availability using:
  2009. // __has_builtin(__builtin___memcpy_chk)
  2010. // When compiling with -fno-builtin, this is always true.
  2011. // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
  2012. // end up with fortified libcalls, which isn't acceptable in a freestanding
  2013. // environment which only provides their non-fortified counterparts.
  2014. //
  2015. // Until we change clang and/or teach external users to check for availability
  2016. // differently, disregard the "nobuiltin" attribute and TLI::has.
  2017. //
  2018. // PR23093.
  2019. LibFunc::Func Func;
  2020. Function *Callee = CI->getCalledFunction();
  2021. StringRef FuncName = Callee->getName();
  2022. IRBuilder<> Builder(CI);
  2023. bool isCallingConvC = CI->getCallingConv() == llvm::CallingConv::C;
  2024. // First, check that this is a known library functions.
  2025. if (!TLI->getLibFunc(FuncName, Func))
  2026. return nullptr;
  2027. // We never change the calling convention.
  2028. if (!ignoreCallingConv(Func) && !isCallingConvC)
  2029. return nullptr;
  2030. switch (Func) {
  2031. case LibFunc::memcpy_chk:
  2032. return optimizeMemCpyChk(CI, Builder);
  2033. case LibFunc::memmove_chk:
  2034. return optimizeMemMoveChk(CI, Builder);
  2035. case LibFunc::memset_chk:
  2036. return optimizeMemSetChk(CI, Builder);
  2037. case LibFunc::stpcpy_chk:
  2038. case LibFunc::strcpy_chk:
  2039. return optimizeStrpCpyChk(CI, Builder, Func);
  2040. case LibFunc::stpncpy_chk:
  2041. case LibFunc::strncpy_chk:
  2042. return optimizeStrpNCpyChk(CI, Builder, Func);
  2043. default:
  2044. break;
  2045. }
  2046. return nullptr;
  2047. }
  2048. FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
  2049. const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
  2050. : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}