SimplifyLibCalls.cpp 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901
  1. //===------ SimplifyLibCalls.cpp - Library calls simplifier ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the library calls simplifier. It does not implement
  10. // any pass, but can't be used by other passes to do simplifications.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  14. #include "llvm/ADT/APSInt.h"
  15. #include "llvm/ADT/SmallString.h"
  16. #include "llvm/ADT/StringMap.h"
  17. #include "llvm/ADT/Triple.h"
  18. #include "llvm/Analysis/ConstantFolding.h"
  19. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  20. #include "llvm/Analysis/TargetLibraryInfo.h"
  21. #include "llvm/Transforms/Utils/Local.h"
  22. #include "llvm/Analysis/ValueTracking.h"
  23. #include "llvm/Analysis/CaptureTracking.h"
  24. #include "llvm/Analysis/Loads.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/Function.h"
  27. #include "llvm/IR/IRBuilder.h"
  28. #include "llvm/IR/IntrinsicInst.h"
  29. #include "llvm/IR/Intrinsics.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/PatternMatch.h"
  33. #include "llvm/Support/CommandLine.h"
  34. #include "llvm/Support/KnownBits.h"
  35. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  36. using namespace llvm;
  37. using namespace PatternMatch;
  38. static cl::opt<bool>
  39. EnableUnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
  40. cl::init(false),
  41. cl::desc("Enable unsafe double to float "
  42. "shrinking for math lib calls"));
  43. //===----------------------------------------------------------------------===//
  44. // Helper Functions
  45. //===----------------------------------------------------------------------===//
  46. static bool ignoreCallingConv(LibFunc Func) {
  47. return Func == LibFunc_abs || Func == LibFunc_labs ||
  48. Func == LibFunc_llabs || Func == LibFunc_strlen;
  49. }
  50. static bool isCallingConvCCompatible(CallInst *CI) {
  51. switch(CI->getCallingConv()) {
  52. default:
  53. return false;
  54. case llvm::CallingConv::C:
  55. return true;
  56. case llvm::CallingConv::ARM_APCS:
  57. case llvm::CallingConv::ARM_AAPCS:
  58. case llvm::CallingConv::ARM_AAPCS_VFP: {
  59. // The iOS ABI diverges from the standard in some cases, so for now don't
  60. // try to simplify those calls.
  61. if (Triple(CI->getModule()->getTargetTriple()).isiOS())
  62. return false;
  63. auto *FuncTy = CI->getFunctionType();
  64. if (!FuncTy->getReturnType()->isPointerTy() &&
  65. !FuncTy->getReturnType()->isIntegerTy() &&
  66. !FuncTy->getReturnType()->isVoidTy())
  67. return false;
  68. for (auto Param : FuncTy->params()) {
  69. if (!Param->isPointerTy() && !Param->isIntegerTy())
  70. return false;
  71. }
  72. return true;
  73. }
  74. }
  75. return false;
  76. }
  77. /// Return true if it is only used in equality comparisons with With.
  78. static bool isOnlyUsedInEqualityComparison(Value *V, Value *With) {
  79. for (User *U : V->users()) {
  80. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  81. if (IC->isEquality() && IC->getOperand(1) == With)
  82. continue;
  83. // Unknown instruction.
  84. return false;
  85. }
  86. return true;
  87. }
  88. static bool callHasFloatingPointArgument(const CallInst *CI) {
  89. return any_of(CI->operands(), [](const Use &OI) {
  90. return OI->getType()->isFloatingPointTy();
  91. });
  92. }
  93. static Value *convertStrToNumber(CallInst *CI, StringRef &Str, int64_t Base) {
  94. if (Base < 2 || Base > 36)
  95. // handle special zero base
  96. if (Base != 0)
  97. return nullptr;
  98. char *End;
  99. std::string nptr = Str.str();
  100. errno = 0;
  101. long long int Result = strtoll(nptr.c_str(), &End, Base);
  102. if (errno)
  103. return nullptr;
  104. // if we assume all possible target locales are ASCII supersets,
  105. // then if strtoll successfully parses a number on the host,
  106. // it will also successfully parse the same way on the target
  107. if (*End != '\0')
  108. return nullptr;
  109. if (!isIntN(CI->getType()->getPrimitiveSizeInBits(), Result))
  110. return nullptr;
  111. return ConstantInt::get(CI->getType(), Result);
  112. }
  113. static bool isLocallyOpenedFile(Value *File, CallInst *CI, IRBuilder<> &B,
  114. const TargetLibraryInfo *TLI) {
  115. CallInst *FOpen = dyn_cast<CallInst>(File);
  116. if (!FOpen)
  117. return false;
  118. Function *InnerCallee = FOpen->getCalledFunction();
  119. if (!InnerCallee)
  120. return false;
  121. LibFunc Func;
  122. if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
  123. Func != LibFunc_fopen)
  124. return false;
  125. inferLibFuncAttributes(*CI->getCalledFunction(), *TLI);
  126. if (PointerMayBeCaptured(File, true, true))
  127. return false;
  128. return true;
  129. }
  130. static bool isOnlyUsedInComparisonWithZero(Value *V) {
  131. for (User *U : V->users()) {
  132. if (ICmpInst *IC = dyn_cast<ICmpInst>(U))
  133. if (Constant *C = dyn_cast<Constant>(IC->getOperand(1)))
  134. if (C->isNullValue())
  135. continue;
  136. // Unknown instruction.
  137. return false;
  138. }
  139. return true;
  140. }
  141. static bool canTransformToMemCmp(CallInst *CI, Value *Str, uint64_t Len,
  142. const DataLayout &DL) {
  143. if (!isOnlyUsedInComparisonWithZero(CI))
  144. return false;
  145. if (!isDereferenceableAndAlignedPointer(Str, 1, APInt(64, Len), DL))
  146. return false;
  147. if (CI->getFunction()->hasFnAttribute(Attribute::SanitizeMemory))
  148. return false;
  149. return true;
  150. }
  151. //===----------------------------------------------------------------------===//
  152. // String and Memory Library Call Optimizations
  153. //===----------------------------------------------------------------------===//
  154. Value *LibCallSimplifier::optimizeStrCat(CallInst *CI, IRBuilder<> &B) {
  155. // Extract some information from the instruction
  156. Value *Dst = CI->getArgOperand(0);
  157. Value *Src = CI->getArgOperand(1);
  158. // See if we can get the length of the input string.
  159. uint64_t Len = GetStringLength(Src);
  160. if (Len == 0)
  161. return nullptr;
  162. --Len; // Unbias length.
  163. // Handle the simple, do-nothing case: strcat(x, "") -> x
  164. if (Len == 0)
  165. return Dst;
  166. return emitStrLenMemCpy(Src, Dst, Len, B);
  167. }
  168. Value *LibCallSimplifier::emitStrLenMemCpy(Value *Src, Value *Dst, uint64_t Len,
  169. IRBuilder<> &B) {
  170. // We need to find the end of the destination string. That's where the
  171. // memory is to be moved to. We just generate a call to strlen.
  172. Value *DstLen = emitStrLen(Dst, B, DL, TLI);
  173. if (!DstLen)
  174. return nullptr;
  175. // Now that we have the destination's length, we must index into the
  176. // destination's pointer to get the actual memcpy destination (end of
  177. // the string .. we're concatenating).
  178. Value *CpyDst = B.CreateGEP(B.getInt8Ty(), Dst, DstLen, "endptr");
  179. // We have enough information to now generate the memcpy call to do the
  180. // concatenation for us. Make a memcpy to copy the nul byte with align = 1.
  181. B.CreateMemCpy(CpyDst, 1, Src, 1,
  182. ConstantInt::get(DL.getIntPtrType(Src->getContext()), Len + 1));
  183. return Dst;
  184. }
  185. Value *LibCallSimplifier::optimizeStrNCat(CallInst *CI, IRBuilder<> &B) {
  186. // Extract some information from the instruction.
  187. Value *Dst = CI->getArgOperand(0);
  188. Value *Src = CI->getArgOperand(1);
  189. uint64_t Len;
  190. // We don't do anything if length is not constant.
  191. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
  192. Len = LengthArg->getZExtValue();
  193. else
  194. return nullptr;
  195. // See if we can get the length of the input string.
  196. uint64_t SrcLen = GetStringLength(Src);
  197. if (SrcLen == 0)
  198. return nullptr;
  199. --SrcLen; // Unbias length.
  200. // Handle the simple, do-nothing cases:
  201. // strncat(x, "", c) -> x
  202. // strncat(x, c, 0) -> x
  203. if (SrcLen == 0 || Len == 0)
  204. return Dst;
  205. // We don't optimize this case.
  206. if (Len < SrcLen)
  207. return nullptr;
  208. // strncat(x, s, c) -> strcat(x, s)
  209. // s is constant so the strcat can be optimized further.
  210. return emitStrLenMemCpy(Src, Dst, SrcLen, B);
  211. }
  212. Value *LibCallSimplifier::optimizeStrChr(CallInst *CI, IRBuilder<> &B) {
  213. Function *Callee = CI->getCalledFunction();
  214. FunctionType *FT = Callee->getFunctionType();
  215. Value *SrcStr = CI->getArgOperand(0);
  216. // If the second operand is non-constant, see if we can compute the length
  217. // of the input string and turn this into memchr.
  218. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  219. if (!CharC) {
  220. uint64_t Len = GetStringLength(SrcStr);
  221. if (Len == 0 || !FT->getParamType(1)->isIntegerTy(32)) // memchr needs i32.
  222. return nullptr;
  223. return emitMemChr(SrcStr, CI->getArgOperand(1), // include nul.
  224. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len),
  225. B, DL, TLI);
  226. }
  227. // Otherwise, the character is a constant, see if the first argument is
  228. // a string literal. If so, we can constant fold.
  229. StringRef Str;
  230. if (!getConstantStringInfo(SrcStr, Str)) {
  231. if (CharC->isZero()) // strchr(p, 0) -> p + strlen(p)
  232. return B.CreateGEP(B.getInt8Ty(), SrcStr, emitStrLen(SrcStr, B, DL, TLI),
  233. "strchr");
  234. return nullptr;
  235. }
  236. // Compute the offset, make sure to handle the case when we're searching for
  237. // zero (a weird way to spell strlen).
  238. size_t I = (0xFF & CharC->getSExtValue()) == 0
  239. ? Str.size()
  240. : Str.find(CharC->getSExtValue());
  241. if (I == StringRef::npos) // Didn't find the char. strchr returns null.
  242. return Constant::getNullValue(CI->getType());
  243. // strchr(s+n,c) -> gep(s+n+i,c)
  244. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strchr");
  245. }
  246. Value *LibCallSimplifier::optimizeStrRChr(CallInst *CI, IRBuilder<> &B) {
  247. Value *SrcStr = CI->getArgOperand(0);
  248. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  249. // Cannot fold anything if we're not looking for a constant.
  250. if (!CharC)
  251. return nullptr;
  252. StringRef Str;
  253. if (!getConstantStringInfo(SrcStr, Str)) {
  254. // strrchr(s, 0) -> strchr(s, 0)
  255. if (CharC->isZero())
  256. return emitStrChr(SrcStr, '\0', B, TLI);
  257. return nullptr;
  258. }
  259. // Compute the offset.
  260. size_t I = (0xFF & CharC->getSExtValue()) == 0
  261. ? Str.size()
  262. : Str.rfind(CharC->getSExtValue());
  263. if (I == StringRef::npos) // Didn't find the char. Return null.
  264. return Constant::getNullValue(CI->getType());
  265. // strrchr(s+n,c) -> gep(s+n+i,c)
  266. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "strrchr");
  267. }
  268. Value *LibCallSimplifier::optimizeStrCmp(CallInst *CI, IRBuilder<> &B) {
  269. Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
  270. if (Str1P == Str2P) // strcmp(x,x) -> 0
  271. return ConstantInt::get(CI->getType(), 0);
  272. StringRef Str1, Str2;
  273. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  274. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  275. // strcmp(x, y) -> cnst (if both x and y are constant strings)
  276. if (HasStr1 && HasStr2)
  277. return ConstantInt::get(CI->getType(), Str1.compare(Str2));
  278. if (HasStr1 && Str1.empty()) // strcmp("", x) -> -*x
  279. return B.CreateNeg(
  280. B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
  281. if (HasStr2 && Str2.empty()) // strcmp(x,"") -> *x
  282. return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
  283. // strcmp(P, "x") -> memcmp(P, "x", 2)
  284. uint64_t Len1 = GetStringLength(Str1P);
  285. uint64_t Len2 = GetStringLength(Str2P);
  286. if (Len1 && Len2) {
  287. return emitMemCmp(Str1P, Str2P,
  288. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  289. std::min(Len1, Len2)),
  290. B, DL, TLI);
  291. }
  292. // strcmp to memcmp
  293. if (!HasStr1 && HasStr2) {
  294. if (canTransformToMemCmp(CI, Str1P, Len2, DL))
  295. return emitMemCmp(
  296. Str1P, Str2P,
  297. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
  298. TLI);
  299. } else if (HasStr1 && !HasStr2) {
  300. if (canTransformToMemCmp(CI, Str2P, Len1, DL))
  301. return emitMemCmp(
  302. Str1P, Str2P,
  303. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
  304. TLI);
  305. }
  306. return nullptr;
  307. }
  308. Value *LibCallSimplifier::optimizeStrNCmp(CallInst *CI, IRBuilder<> &B) {
  309. Value *Str1P = CI->getArgOperand(0), *Str2P = CI->getArgOperand(1);
  310. if (Str1P == Str2P) // strncmp(x,x,n) -> 0
  311. return ConstantInt::get(CI->getType(), 0);
  312. // Get the length argument if it is constant.
  313. uint64_t Length;
  314. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(CI->getArgOperand(2)))
  315. Length = LengthArg->getZExtValue();
  316. else
  317. return nullptr;
  318. if (Length == 0) // strncmp(x,y,0) -> 0
  319. return ConstantInt::get(CI->getType(), 0);
  320. if (Length == 1) // strncmp(x,y,1) -> memcmp(x,y,1)
  321. return emitMemCmp(Str1P, Str2P, CI->getArgOperand(2), B, DL, TLI);
  322. StringRef Str1, Str2;
  323. bool HasStr1 = getConstantStringInfo(Str1P, Str1);
  324. bool HasStr2 = getConstantStringInfo(Str2P, Str2);
  325. // strncmp(x, y) -> cnst (if both x and y are constant strings)
  326. if (HasStr1 && HasStr2) {
  327. StringRef SubStr1 = Str1.substr(0, Length);
  328. StringRef SubStr2 = Str2.substr(0, Length);
  329. return ConstantInt::get(CI->getType(), SubStr1.compare(SubStr2));
  330. }
  331. if (HasStr1 && Str1.empty()) // strncmp("", x, n) -> -*x
  332. return B.CreateNeg(
  333. B.CreateZExt(B.CreateLoad(Str2P, "strcmpload"), CI->getType()));
  334. if (HasStr2 && Str2.empty()) // strncmp(x, "", n) -> *x
  335. return B.CreateZExt(B.CreateLoad(Str1P, "strcmpload"), CI->getType());
  336. uint64_t Len1 = GetStringLength(Str1P);
  337. uint64_t Len2 = GetStringLength(Str2P);
  338. // strncmp to memcmp
  339. if (!HasStr1 && HasStr2) {
  340. Len2 = std::min(Len2, Length);
  341. if (canTransformToMemCmp(CI, Str1P, Len2, DL))
  342. return emitMemCmp(
  343. Str1P, Str2P,
  344. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len2), B, DL,
  345. TLI);
  346. } else if (HasStr1 && !HasStr2) {
  347. Len1 = std::min(Len1, Length);
  348. if (canTransformToMemCmp(CI, Str2P, Len1, DL))
  349. return emitMemCmp(
  350. Str1P, Str2P,
  351. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len1), B, DL,
  352. TLI);
  353. }
  354. return nullptr;
  355. }
  356. Value *LibCallSimplifier::optimizeStrCpy(CallInst *CI, IRBuilder<> &B) {
  357. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  358. if (Dst == Src) // strcpy(x,x) -> x
  359. return Src;
  360. // See if we can get the length of the input string.
  361. uint64_t Len = GetStringLength(Src);
  362. if (Len == 0)
  363. return nullptr;
  364. // We have enough information to now generate the memcpy call to do the
  365. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  366. B.CreateMemCpy(Dst, 1, Src, 1,
  367. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len));
  368. return Dst;
  369. }
  370. Value *LibCallSimplifier::optimizeStpCpy(CallInst *CI, IRBuilder<> &B) {
  371. Function *Callee = CI->getCalledFunction();
  372. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1);
  373. if (Dst == Src) { // stpcpy(x,x) -> x+strlen(x)
  374. Value *StrLen = emitStrLen(Src, B, DL, TLI);
  375. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  376. }
  377. // See if we can get the length of the input string.
  378. uint64_t Len = GetStringLength(Src);
  379. if (Len == 0)
  380. return nullptr;
  381. Type *PT = Callee->getFunctionType()->getParamType(0);
  382. Value *LenV = ConstantInt::get(DL.getIntPtrType(PT), Len);
  383. Value *DstEnd = B.CreateGEP(B.getInt8Ty(), Dst,
  384. ConstantInt::get(DL.getIntPtrType(PT), Len - 1));
  385. // We have enough information to now generate the memcpy call to do the
  386. // copy for us. Make a memcpy to copy the nul byte with align = 1.
  387. B.CreateMemCpy(Dst, 1, Src, 1, LenV);
  388. return DstEnd;
  389. }
  390. Value *LibCallSimplifier::optimizeStrNCpy(CallInst *CI, IRBuilder<> &B) {
  391. Function *Callee = CI->getCalledFunction();
  392. Value *Dst = CI->getArgOperand(0);
  393. Value *Src = CI->getArgOperand(1);
  394. Value *LenOp = CI->getArgOperand(2);
  395. // See if we can get the length of the input string.
  396. uint64_t SrcLen = GetStringLength(Src);
  397. if (SrcLen == 0)
  398. return nullptr;
  399. --SrcLen;
  400. if (SrcLen == 0) {
  401. // strncpy(x, "", y) -> memset(align 1 x, '\0', y)
  402. B.CreateMemSet(Dst, B.getInt8('\0'), LenOp, 1);
  403. return Dst;
  404. }
  405. uint64_t Len;
  406. if (ConstantInt *LengthArg = dyn_cast<ConstantInt>(LenOp))
  407. Len = LengthArg->getZExtValue();
  408. else
  409. return nullptr;
  410. if (Len == 0)
  411. return Dst; // strncpy(x, y, 0) -> x
  412. // Let strncpy handle the zero padding
  413. if (Len > SrcLen + 1)
  414. return nullptr;
  415. Type *PT = Callee->getFunctionType()->getParamType(0);
  416. // strncpy(x, s, c) -> memcpy(align 1 x, align 1 s, c) [s and c are constant]
  417. B.CreateMemCpy(Dst, 1, Src, 1, ConstantInt::get(DL.getIntPtrType(PT), Len));
  418. return Dst;
  419. }
  420. Value *LibCallSimplifier::optimizeStringLength(CallInst *CI, IRBuilder<> &B,
  421. unsigned CharSize) {
  422. Value *Src = CI->getArgOperand(0);
  423. // Constant folding: strlen("xyz") -> 3
  424. if (uint64_t Len = GetStringLength(Src, CharSize))
  425. return ConstantInt::get(CI->getType(), Len - 1);
  426. // If s is a constant pointer pointing to a string literal, we can fold
  427. // strlen(s + x) to strlen(s) - x, when x is known to be in the range
  428. // [0, strlen(s)] or the string has a single null terminator '\0' at the end.
  429. // We only try to simplify strlen when the pointer s points to an array
  430. // of i8. Otherwise, we would need to scale the offset x before doing the
  431. // subtraction. This will make the optimization more complex, and it's not
  432. // very useful because calling strlen for a pointer of other types is
  433. // very uncommon.
  434. if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
  435. if (!isGEPBasedOnPointerToString(GEP, CharSize))
  436. return nullptr;
  437. ConstantDataArraySlice Slice;
  438. if (getConstantDataArrayInfo(GEP->getOperand(0), Slice, CharSize)) {
  439. uint64_t NullTermIdx;
  440. if (Slice.Array == nullptr) {
  441. NullTermIdx = 0;
  442. } else {
  443. NullTermIdx = ~((uint64_t)0);
  444. for (uint64_t I = 0, E = Slice.Length; I < E; ++I) {
  445. if (Slice.Array->getElementAsInteger(I + Slice.Offset) == 0) {
  446. NullTermIdx = I;
  447. break;
  448. }
  449. }
  450. // If the string does not have '\0', leave it to strlen to compute
  451. // its length.
  452. if (NullTermIdx == ~((uint64_t)0))
  453. return nullptr;
  454. }
  455. Value *Offset = GEP->getOperand(2);
  456. KnownBits Known = computeKnownBits(Offset, DL, 0, nullptr, CI, nullptr);
  457. Known.Zero.flipAllBits();
  458. uint64_t ArrSize =
  459. cast<ArrayType>(GEP->getSourceElementType())->getNumElements();
  460. // KnownZero's bits are flipped, so zeros in KnownZero now represent
  461. // bits known to be zeros in Offset, and ones in KnowZero represent
  462. // bits unknown in Offset. Therefore, Offset is known to be in range
  463. // [0, NullTermIdx] when the flipped KnownZero is non-negative and
  464. // unsigned-less-than NullTermIdx.
  465. //
  466. // If Offset is not provably in the range [0, NullTermIdx], we can still
  467. // optimize if we can prove that the program has undefined behavior when
  468. // Offset is outside that range. That is the case when GEP->getOperand(0)
  469. // is a pointer to an object whose memory extent is NullTermIdx+1.
  470. if ((Known.Zero.isNonNegative() && Known.Zero.ule(NullTermIdx)) ||
  471. (GEP->isInBounds() && isa<GlobalVariable>(GEP->getOperand(0)) &&
  472. NullTermIdx == ArrSize - 1)) {
  473. Offset = B.CreateSExtOrTrunc(Offset, CI->getType());
  474. return B.CreateSub(ConstantInt::get(CI->getType(), NullTermIdx),
  475. Offset);
  476. }
  477. }
  478. return nullptr;
  479. }
  480. // strlen(x?"foo":"bars") --> x ? 3 : 4
  481. if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  482. uint64_t LenTrue = GetStringLength(SI->getTrueValue(), CharSize);
  483. uint64_t LenFalse = GetStringLength(SI->getFalseValue(), CharSize);
  484. if (LenTrue && LenFalse) {
  485. ORE.emit([&]() {
  486. return OptimizationRemark("instcombine", "simplify-libcalls", CI)
  487. << "folded strlen(select) to select of constants";
  488. });
  489. return B.CreateSelect(SI->getCondition(),
  490. ConstantInt::get(CI->getType(), LenTrue - 1),
  491. ConstantInt::get(CI->getType(), LenFalse - 1));
  492. }
  493. }
  494. // strlen(x) != 0 --> *x != 0
  495. // strlen(x) == 0 --> *x == 0
  496. if (isOnlyUsedInZeroEqualityComparison(CI))
  497. return B.CreateZExt(B.CreateLoad(Src, "strlenfirst"), CI->getType());
  498. return nullptr;
  499. }
  500. Value *LibCallSimplifier::optimizeStrLen(CallInst *CI, IRBuilder<> &B) {
  501. return optimizeStringLength(CI, B, 8);
  502. }
  503. Value *LibCallSimplifier::optimizeWcslen(CallInst *CI, IRBuilder<> &B) {
  504. Module &M = *CI->getModule();
  505. unsigned WCharSize = TLI->getWCharSize(M) * 8;
  506. // We cannot perform this optimization without wchar_size metadata.
  507. if (WCharSize == 0)
  508. return nullptr;
  509. return optimizeStringLength(CI, B, WCharSize);
  510. }
  511. Value *LibCallSimplifier::optimizeStrPBrk(CallInst *CI, IRBuilder<> &B) {
  512. StringRef S1, S2;
  513. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  514. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  515. // strpbrk(s, "") -> nullptr
  516. // strpbrk("", s) -> nullptr
  517. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  518. return Constant::getNullValue(CI->getType());
  519. // Constant folding.
  520. if (HasS1 && HasS2) {
  521. size_t I = S1.find_first_of(S2);
  522. if (I == StringRef::npos) // No match.
  523. return Constant::getNullValue(CI->getType());
  524. return B.CreateGEP(B.getInt8Ty(), CI->getArgOperand(0), B.getInt64(I),
  525. "strpbrk");
  526. }
  527. // strpbrk(s, "a") -> strchr(s, 'a')
  528. if (HasS2 && S2.size() == 1)
  529. return emitStrChr(CI->getArgOperand(0), S2[0], B, TLI);
  530. return nullptr;
  531. }
  532. Value *LibCallSimplifier::optimizeStrTo(CallInst *CI, IRBuilder<> &B) {
  533. Value *EndPtr = CI->getArgOperand(1);
  534. if (isa<ConstantPointerNull>(EndPtr)) {
  535. // With a null EndPtr, this function won't capture the main argument.
  536. // It would be readonly too, except that it still may write to errno.
  537. CI->addParamAttr(0, Attribute::NoCapture);
  538. }
  539. return nullptr;
  540. }
  541. Value *LibCallSimplifier::optimizeStrSpn(CallInst *CI, IRBuilder<> &B) {
  542. StringRef S1, S2;
  543. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  544. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  545. // strspn(s, "") -> 0
  546. // strspn("", s) -> 0
  547. if ((HasS1 && S1.empty()) || (HasS2 && S2.empty()))
  548. return Constant::getNullValue(CI->getType());
  549. // Constant folding.
  550. if (HasS1 && HasS2) {
  551. size_t Pos = S1.find_first_not_of(S2);
  552. if (Pos == StringRef::npos)
  553. Pos = S1.size();
  554. return ConstantInt::get(CI->getType(), Pos);
  555. }
  556. return nullptr;
  557. }
  558. Value *LibCallSimplifier::optimizeStrCSpn(CallInst *CI, IRBuilder<> &B) {
  559. StringRef S1, S2;
  560. bool HasS1 = getConstantStringInfo(CI->getArgOperand(0), S1);
  561. bool HasS2 = getConstantStringInfo(CI->getArgOperand(1), S2);
  562. // strcspn("", s) -> 0
  563. if (HasS1 && S1.empty())
  564. return Constant::getNullValue(CI->getType());
  565. // Constant folding.
  566. if (HasS1 && HasS2) {
  567. size_t Pos = S1.find_first_of(S2);
  568. if (Pos == StringRef::npos)
  569. Pos = S1.size();
  570. return ConstantInt::get(CI->getType(), Pos);
  571. }
  572. // strcspn(s, "") -> strlen(s)
  573. if (HasS2 && S2.empty())
  574. return emitStrLen(CI->getArgOperand(0), B, DL, TLI);
  575. return nullptr;
  576. }
  577. Value *LibCallSimplifier::optimizeStrStr(CallInst *CI, IRBuilder<> &B) {
  578. // fold strstr(x, x) -> x.
  579. if (CI->getArgOperand(0) == CI->getArgOperand(1))
  580. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  581. // fold strstr(a, b) == a -> strncmp(a, b, strlen(b)) == 0
  582. if (isOnlyUsedInEqualityComparison(CI, CI->getArgOperand(0))) {
  583. Value *StrLen = emitStrLen(CI->getArgOperand(1), B, DL, TLI);
  584. if (!StrLen)
  585. return nullptr;
  586. Value *StrNCmp = emitStrNCmp(CI->getArgOperand(0), CI->getArgOperand(1),
  587. StrLen, B, DL, TLI);
  588. if (!StrNCmp)
  589. return nullptr;
  590. for (auto UI = CI->user_begin(), UE = CI->user_end(); UI != UE;) {
  591. ICmpInst *Old = cast<ICmpInst>(*UI++);
  592. Value *Cmp =
  593. B.CreateICmp(Old->getPredicate(), StrNCmp,
  594. ConstantInt::getNullValue(StrNCmp->getType()), "cmp");
  595. replaceAllUsesWith(Old, Cmp);
  596. }
  597. return CI;
  598. }
  599. // See if either input string is a constant string.
  600. StringRef SearchStr, ToFindStr;
  601. bool HasStr1 = getConstantStringInfo(CI->getArgOperand(0), SearchStr);
  602. bool HasStr2 = getConstantStringInfo(CI->getArgOperand(1), ToFindStr);
  603. // fold strstr(x, "") -> x.
  604. if (HasStr2 && ToFindStr.empty())
  605. return B.CreateBitCast(CI->getArgOperand(0), CI->getType());
  606. // If both strings are known, constant fold it.
  607. if (HasStr1 && HasStr2) {
  608. size_t Offset = SearchStr.find(ToFindStr);
  609. if (Offset == StringRef::npos) // strstr("foo", "bar") -> null
  610. return Constant::getNullValue(CI->getType());
  611. // strstr("abcd", "bc") -> gep((char*)"abcd", 1)
  612. Value *Result = castToCStr(CI->getArgOperand(0), B);
  613. Result = B.CreateConstInBoundsGEP1_64(Result, Offset, "strstr");
  614. return B.CreateBitCast(Result, CI->getType());
  615. }
  616. // fold strstr(x, "y") -> strchr(x, 'y').
  617. if (HasStr2 && ToFindStr.size() == 1) {
  618. Value *StrChr = emitStrChr(CI->getArgOperand(0), ToFindStr[0], B, TLI);
  619. return StrChr ? B.CreateBitCast(StrChr, CI->getType()) : nullptr;
  620. }
  621. return nullptr;
  622. }
  623. Value *LibCallSimplifier::optimizeMemChr(CallInst *CI, IRBuilder<> &B) {
  624. Value *SrcStr = CI->getArgOperand(0);
  625. ConstantInt *CharC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  626. ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  627. // memchr(x, y, 0) -> null
  628. if (LenC && LenC->isZero())
  629. return Constant::getNullValue(CI->getType());
  630. // From now on we need at least constant length and string.
  631. StringRef Str;
  632. if (!LenC || !getConstantStringInfo(SrcStr, Str, 0, /*TrimAtNul=*/false))
  633. return nullptr;
  634. // Truncate the string to LenC. If Str is smaller than LenC we will still only
  635. // scan the string, as reading past the end of it is undefined and we can just
  636. // return null if we don't find the char.
  637. Str = Str.substr(0, LenC->getZExtValue());
  638. // If the char is variable but the input str and length are not we can turn
  639. // this memchr call into a simple bit field test. Of course this only works
  640. // when the return value is only checked against null.
  641. //
  642. // It would be really nice to reuse switch lowering here but we can't change
  643. // the CFG at this point.
  644. //
  645. // memchr("\r\n", C, 2) != nullptr -> (C & ((1 << '\r') | (1 << '\n'))) != 0
  646. // after bounds check.
  647. if (!CharC && !Str.empty() && isOnlyUsedInZeroEqualityComparison(CI)) {
  648. unsigned char Max =
  649. *std::max_element(reinterpret_cast<const unsigned char *>(Str.begin()),
  650. reinterpret_cast<const unsigned char *>(Str.end()));
  651. // Make sure the bit field we're about to create fits in a register on the
  652. // target.
  653. // FIXME: On a 64 bit architecture this prevents us from using the
  654. // interesting range of alpha ascii chars. We could do better by emitting
  655. // two bitfields or shifting the range by 64 if no lower chars are used.
  656. if (!DL.fitsInLegalInteger(Max + 1))
  657. return nullptr;
  658. // For the bit field use a power-of-2 type with at least 8 bits to avoid
  659. // creating unnecessary illegal types.
  660. unsigned char Width = NextPowerOf2(std::max((unsigned char)7, Max));
  661. // Now build the bit field.
  662. APInt Bitfield(Width, 0);
  663. for (char C : Str)
  664. Bitfield.setBit((unsigned char)C);
  665. Value *BitfieldC = B.getInt(Bitfield);
  666. // Adjust width of "C" to the bitfield width, then mask off the high bits.
  667. Value *C = B.CreateZExtOrTrunc(CI->getArgOperand(1), BitfieldC->getType());
  668. C = B.CreateAnd(C, B.getIntN(Width, 0xFF));
  669. // First check that the bit field access is within bounds.
  670. Value *Bounds = B.CreateICmp(ICmpInst::ICMP_ULT, C, B.getIntN(Width, Width),
  671. "memchr.bounds");
  672. // Create code that checks if the given bit is set in the field.
  673. Value *Shl = B.CreateShl(B.getIntN(Width, 1ULL), C);
  674. Value *Bits = B.CreateIsNotNull(B.CreateAnd(Shl, BitfieldC), "memchr.bits");
  675. // Finally merge both checks and cast to pointer type. The inttoptr
  676. // implicitly zexts the i1 to intptr type.
  677. return B.CreateIntToPtr(B.CreateAnd(Bounds, Bits, "memchr"), CI->getType());
  678. }
  679. // Check if all arguments are constants. If so, we can constant fold.
  680. if (!CharC)
  681. return nullptr;
  682. // Compute the offset.
  683. size_t I = Str.find(CharC->getSExtValue() & 0xFF);
  684. if (I == StringRef::npos) // Didn't find the char. memchr returns null.
  685. return Constant::getNullValue(CI->getType());
  686. // memchr(s+n,c,l) -> gep(s+n+i,c)
  687. return B.CreateGEP(B.getInt8Ty(), SrcStr, B.getInt64(I), "memchr");
  688. }
  689. Value *LibCallSimplifier::optimizeMemCmp(CallInst *CI, IRBuilder<> &B) {
  690. Value *LHS = CI->getArgOperand(0), *RHS = CI->getArgOperand(1);
  691. if (LHS == RHS) // memcmp(s,s,x) -> 0
  692. return Constant::getNullValue(CI->getType());
  693. // Make sure we have a constant length.
  694. ConstantInt *LenC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  695. if (!LenC)
  696. return nullptr;
  697. uint64_t Len = LenC->getZExtValue();
  698. if (Len == 0) // memcmp(s1,s2,0) -> 0
  699. return Constant::getNullValue(CI->getType());
  700. // memcmp(S1,S2,1) -> *(unsigned char*)LHS - *(unsigned char*)RHS
  701. if (Len == 1) {
  702. Value *LHSV = B.CreateZExt(B.CreateLoad(castToCStr(LHS, B), "lhsc"),
  703. CI->getType(), "lhsv");
  704. Value *RHSV = B.CreateZExt(B.CreateLoad(castToCStr(RHS, B), "rhsc"),
  705. CI->getType(), "rhsv");
  706. return B.CreateSub(LHSV, RHSV, "chardiff");
  707. }
  708. // memcmp(S1,S2,N/8)==0 -> (*(intN_t*)S1 != *(intN_t*)S2)==0
  709. // TODO: The case where both inputs are constants does not need to be limited
  710. // to legal integers or equality comparison. See block below this.
  711. if (DL.isLegalInteger(Len * 8) && isOnlyUsedInZeroEqualityComparison(CI)) {
  712. IntegerType *IntType = IntegerType::get(CI->getContext(), Len * 8);
  713. unsigned PrefAlignment = DL.getPrefTypeAlignment(IntType);
  714. // First, see if we can fold either argument to a constant.
  715. Value *LHSV = nullptr;
  716. if (auto *LHSC = dyn_cast<Constant>(LHS)) {
  717. LHSC = ConstantExpr::getBitCast(LHSC, IntType->getPointerTo());
  718. LHSV = ConstantFoldLoadFromConstPtr(LHSC, IntType, DL);
  719. }
  720. Value *RHSV = nullptr;
  721. if (auto *RHSC = dyn_cast<Constant>(RHS)) {
  722. RHSC = ConstantExpr::getBitCast(RHSC, IntType->getPointerTo());
  723. RHSV = ConstantFoldLoadFromConstPtr(RHSC, IntType, DL);
  724. }
  725. // Don't generate unaligned loads. If either source is constant data,
  726. // alignment doesn't matter for that source because there is no load.
  727. if ((LHSV || getKnownAlignment(LHS, DL, CI) >= PrefAlignment) &&
  728. (RHSV || getKnownAlignment(RHS, DL, CI) >= PrefAlignment)) {
  729. if (!LHSV) {
  730. Type *LHSPtrTy =
  731. IntType->getPointerTo(LHS->getType()->getPointerAddressSpace());
  732. LHSV = B.CreateLoad(B.CreateBitCast(LHS, LHSPtrTy), "lhsv");
  733. }
  734. if (!RHSV) {
  735. Type *RHSPtrTy =
  736. IntType->getPointerTo(RHS->getType()->getPointerAddressSpace());
  737. RHSV = B.CreateLoad(B.CreateBitCast(RHS, RHSPtrTy), "rhsv");
  738. }
  739. return B.CreateZExt(B.CreateICmpNE(LHSV, RHSV), CI->getType(), "memcmp");
  740. }
  741. }
  742. // Constant folding: memcmp(x, y, Len) -> constant (all arguments are const).
  743. // TODO: This is limited to i8 arrays.
  744. StringRef LHSStr, RHSStr;
  745. if (getConstantStringInfo(LHS, LHSStr) &&
  746. getConstantStringInfo(RHS, RHSStr)) {
  747. // Make sure we're not reading out-of-bounds memory.
  748. if (Len > LHSStr.size() || Len > RHSStr.size())
  749. return nullptr;
  750. // Fold the memcmp and normalize the result. This way we get consistent
  751. // results across multiple platforms.
  752. uint64_t Ret = 0;
  753. int Cmp = memcmp(LHSStr.data(), RHSStr.data(), Len);
  754. if (Cmp < 0)
  755. Ret = -1;
  756. else if (Cmp > 0)
  757. Ret = 1;
  758. return ConstantInt::get(CI->getType(), Ret);
  759. }
  760. return nullptr;
  761. }
  762. Value *LibCallSimplifier::optimizeMemCpy(CallInst *CI, IRBuilder<> &B) {
  763. // memcpy(x, y, n) -> llvm.memcpy(align 1 x, align 1 y, n)
  764. B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
  765. CI->getArgOperand(2));
  766. return CI->getArgOperand(0);
  767. }
  768. Value *LibCallSimplifier::optimizeMemMove(CallInst *CI, IRBuilder<> &B) {
  769. // memmove(x, y, n) -> llvm.memmove(align 1 x, align 1 y, n)
  770. B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
  771. CI->getArgOperand(2));
  772. return CI->getArgOperand(0);
  773. }
  774. /// Fold memset[_chk](malloc(n), 0, n) --> calloc(1, n).
  775. Value *LibCallSimplifier::foldMallocMemset(CallInst *Memset, IRBuilder<> &B) {
  776. // This has to be a memset of zeros (bzero).
  777. auto *FillValue = dyn_cast<ConstantInt>(Memset->getArgOperand(1));
  778. if (!FillValue || FillValue->getZExtValue() != 0)
  779. return nullptr;
  780. // TODO: We should handle the case where the malloc has more than one use.
  781. // This is necessary to optimize common patterns such as when the result of
  782. // the malloc is checked against null or when a memset intrinsic is used in
  783. // place of a memset library call.
  784. auto *Malloc = dyn_cast<CallInst>(Memset->getArgOperand(0));
  785. if (!Malloc || !Malloc->hasOneUse())
  786. return nullptr;
  787. // Is the inner call really malloc()?
  788. Function *InnerCallee = Malloc->getCalledFunction();
  789. if (!InnerCallee)
  790. return nullptr;
  791. LibFunc Func;
  792. if (!TLI->getLibFunc(*InnerCallee, Func) || !TLI->has(Func) ||
  793. Func != LibFunc_malloc)
  794. return nullptr;
  795. // The memset must cover the same number of bytes that are malloc'd.
  796. if (Memset->getArgOperand(2) != Malloc->getArgOperand(0))
  797. return nullptr;
  798. // Replace the malloc with a calloc. We need the data layout to know what the
  799. // actual size of a 'size_t' parameter is.
  800. B.SetInsertPoint(Malloc->getParent(), ++Malloc->getIterator());
  801. const DataLayout &DL = Malloc->getModule()->getDataLayout();
  802. IntegerType *SizeType = DL.getIntPtrType(B.GetInsertBlock()->getContext());
  803. Value *Calloc = emitCalloc(ConstantInt::get(SizeType, 1),
  804. Malloc->getArgOperand(0), Malloc->getAttributes(),
  805. B, *TLI);
  806. if (!Calloc)
  807. return nullptr;
  808. Malloc->replaceAllUsesWith(Calloc);
  809. eraseFromParent(Malloc);
  810. return Calloc;
  811. }
  812. Value *LibCallSimplifier::optimizeMemSet(CallInst *CI, IRBuilder<> &B) {
  813. if (auto *Calloc = foldMallocMemset(CI, B))
  814. return Calloc;
  815. // memset(p, v, n) -> llvm.memset(align 1 p, v, n)
  816. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  817. B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
  818. return CI->getArgOperand(0);
  819. }
  820. Value *LibCallSimplifier::optimizeRealloc(CallInst *CI, IRBuilder<> &B) {
  821. if (isa<ConstantPointerNull>(CI->getArgOperand(0)))
  822. return emitMalloc(CI->getArgOperand(1), B, DL, TLI);
  823. return nullptr;
  824. }
  825. //===----------------------------------------------------------------------===//
  826. // Math Library Optimizations
  827. //===----------------------------------------------------------------------===//
  828. // Replace a libcall \p CI with a call to intrinsic \p IID
  829. static Value *replaceUnaryCall(CallInst *CI, IRBuilder<> &B, Intrinsic::ID IID) {
  830. // Propagate fast-math flags from the existing call to the new call.
  831. IRBuilder<>::FastMathFlagGuard Guard(B);
  832. B.setFastMathFlags(CI->getFastMathFlags());
  833. Module *M = CI->getModule();
  834. Value *V = CI->getArgOperand(0);
  835. Function *F = Intrinsic::getDeclaration(M, IID, CI->getType());
  836. CallInst *NewCall = B.CreateCall(F, V);
  837. NewCall->takeName(CI);
  838. return NewCall;
  839. }
  840. /// Return a variant of Val with float type.
  841. /// Currently this works in two cases: If Val is an FPExtension of a float
  842. /// value to something bigger, simply return the operand.
  843. /// If Val is a ConstantFP but can be converted to a float ConstantFP without
  844. /// loss of precision do so.
  845. static Value *valueHasFloatPrecision(Value *Val) {
  846. if (FPExtInst *Cast = dyn_cast<FPExtInst>(Val)) {
  847. Value *Op = Cast->getOperand(0);
  848. if (Op->getType()->isFloatTy())
  849. return Op;
  850. }
  851. if (ConstantFP *Const = dyn_cast<ConstantFP>(Val)) {
  852. APFloat F = Const->getValueAPF();
  853. bool losesInfo;
  854. (void)F.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven,
  855. &losesInfo);
  856. if (!losesInfo)
  857. return ConstantFP::get(Const->getContext(), F);
  858. }
  859. return nullptr;
  860. }
  861. /// Shrink double -> float functions.
  862. static Value *optimizeDoubleFP(CallInst *CI, IRBuilder<> &B,
  863. bool isBinary, bool isPrecise = false) {
  864. if (!CI->getType()->isDoubleTy())
  865. return nullptr;
  866. // If not all the uses of the function are converted to float, then bail out.
  867. // This matters if the precision of the result is more important than the
  868. // precision of the arguments.
  869. if (isPrecise)
  870. for (User *U : CI->users()) {
  871. FPTruncInst *Cast = dyn_cast<FPTruncInst>(U);
  872. if (!Cast || !Cast->getType()->isFloatTy())
  873. return nullptr;
  874. }
  875. // If this is something like 'g((double) float)', convert to 'gf(float)'.
  876. Value *V[2];
  877. V[0] = valueHasFloatPrecision(CI->getArgOperand(0));
  878. V[1] = isBinary ? valueHasFloatPrecision(CI->getArgOperand(1)) : nullptr;
  879. if (!V[0] || (isBinary && !V[1]))
  880. return nullptr;
  881. // If call isn't an intrinsic, check that it isn't within a function with the
  882. // same name as the float version of this call, otherwise the result is an
  883. // infinite loop. For example, from MinGW-w64:
  884. //
  885. // float expf(float val) { return (float) exp((double) val); }
  886. Function *CalleeFn = CI->getCalledFunction();
  887. StringRef CalleeNm = CalleeFn->getName();
  888. AttributeList CalleeAt = CalleeFn->getAttributes();
  889. if (CalleeFn && !CalleeFn->isIntrinsic()) {
  890. const Function *Fn = CI->getFunction();
  891. StringRef FnName = Fn->getName();
  892. if (FnName.back() == 'f' &&
  893. FnName.size() == (CalleeNm.size() + 1) &&
  894. FnName.startswith(CalleeNm))
  895. return nullptr;
  896. }
  897. // Propagate the math semantics from the current function to the new function.
  898. IRBuilder<>::FastMathFlagGuard Guard(B);
  899. B.setFastMathFlags(CI->getFastMathFlags());
  900. // g((double) float) -> (double) gf(float)
  901. Value *R;
  902. if (CalleeFn->isIntrinsic()) {
  903. Module *M = CI->getModule();
  904. Intrinsic::ID IID = CalleeFn->getIntrinsicID();
  905. Function *Fn = Intrinsic::getDeclaration(M, IID, B.getFloatTy());
  906. R = isBinary ? B.CreateCall(Fn, V) : B.CreateCall(Fn, V[0]);
  907. }
  908. else
  909. R = isBinary ? emitBinaryFloatFnCall(V[0], V[1], CalleeNm, B, CalleeAt)
  910. : emitUnaryFloatFnCall(V[0], CalleeNm, B, CalleeAt);
  911. return B.CreateFPExt(R, B.getDoubleTy());
  912. }
  913. /// Shrink double -> float for unary functions.
  914. static Value *optimizeUnaryDoubleFP(CallInst *CI, IRBuilder<> &B,
  915. bool isPrecise = false) {
  916. return optimizeDoubleFP(CI, B, false, isPrecise);
  917. }
  918. /// Shrink double -> float for binary functions.
  919. static Value *optimizeBinaryDoubleFP(CallInst *CI, IRBuilder<> &B,
  920. bool isPrecise = false) {
  921. return optimizeDoubleFP(CI, B, true, isPrecise);
  922. }
  923. // cabs(z) -> sqrt((creal(z)*creal(z)) + (cimag(z)*cimag(z)))
  924. Value *LibCallSimplifier::optimizeCAbs(CallInst *CI, IRBuilder<> &B) {
  925. if (!CI->isFast())
  926. return nullptr;
  927. // Propagate fast-math flags from the existing call to new instructions.
  928. IRBuilder<>::FastMathFlagGuard Guard(B);
  929. B.setFastMathFlags(CI->getFastMathFlags());
  930. Value *Real, *Imag;
  931. if (CI->getNumArgOperands() == 1) {
  932. Value *Op = CI->getArgOperand(0);
  933. assert(Op->getType()->isArrayTy() && "Unexpected signature for cabs!");
  934. Real = B.CreateExtractValue(Op, 0, "real");
  935. Imag = B.CreateExtractValue(Op, 1, "imag");
  936. } else {
  937. assert(CI->getNumArgOperands() == 2 && "Unexpected signature for cabs!");
  938. Real = CI->getArgOperand(0);
  939. Imag = CI->getArgOperand(1);
  940. }
  941. Value *RealReal = B.CreateFMul(Real, Real);
  942. Value *ImagImag = B.CreateFMul(Imag, Imag);
  943. Function *FSqrt = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::sqrt,
  944. CI->getType());
  945. return B.CreateCall(FSqrt, B.CreateFAdd(RealReal, ImagImag), "cabs");
  946. }
  947. static Value *optimizeTrigReflections(CallInst *Call, LibFunc Func,
  948. IRBuilder<> &B) {
  949. if (!isa<FPMathOperator>(Call))
  950. return nullptr;
  951. IRBuilder<>::FastMathFlagGuard Guard(B);
  952. B.setFastMathFlags(Call->getFastMathFlags());
  953. // TODO: Can this be shared to also handle LLVM intrinsics?
  954. Value *X;
  955. switch (Func) {
  956. case LibFunc_sin:
  957. case LibFunc_sinf:
  958. case LibFunc_sinl:
  959. case LibFunc_tan:
  960. case LibFunc_tanf:
  961. case LibFunc_tanl:
  962. // sin(-X) --> -sin(X)
  963. // tan(-X) --> -tan(X)
  964. if (match(Call->getArgOperand(0), m_OneUse(m_FNeg(m_Value(X)))))
  965. return B.CreateFNeg(B.CreateCall(Call->getCalledFunction(), X));
  966. break;
  967. case LibFunc_cos:
  968. case LibFunc_cosf:
  969. case LibFunc_cosl:
  970. // cos(-X) --> cos(X)
  971. if (match(Call->getArgOperand(0), m_FNeg(m_Value(X))))
  972. return B.CreateCall(Call->getCalledFunction(), X, "cos");
  973. break;
  974. default:
  975. break;
  976. }
  977. return nullptr;
  978. }
  979. static Value *getPow(Value *InnerChain[33], unsigned Exp, IRBuilder<> &B) {
  980. // Multiplications calculated using Addition Chains.
  981. // Refer: http://wwwhomes.uni-bielefeld.de/achim/addition_chain.html
  982. assert(Exp != 0 && "Incorrect exponent 0 not handled");
  983. if (InnerChain[Exp])
  984. return InnerChain[Exp];
  985. static const unsigned AddChain[33][2] = {
  986. {0, 0}, // Unused.
  987. {0, 0}, // Unused (base case = pow1).
  988. {1, 1}, // Unused (pre-computed).
  989. {1, 2}, {2, 2}, {2, 3}, {3, 3}, {2, 5}, {4, 4},
  990. {1, 8}, {5, 5}, {1, 10}, {6, 6}, {4, 9}, {7, 7},
  991. {3, 12}, {8, 8}, {8, 9}, {2, 16}, {1, 18}, {10, 10},
  992. {6, 15}, {11, 11}, {3, 20}, {12, 12}, {8, 17}, {13, 13},
  993. {3, 24}, {14, 14}, {4, 25}, {15, 15}, {3, 28}, {16, 16},
  994. };
  995. InnerChain[Exp] = B.CreateFMul(getPow(InnerChain, AddChain[Exp][0], B),
  996. getPow(InnerChain, AddChain[Exp][1], B));
  997. return InnerChain[Exp];
  998. }
  999. /// Use exp{,2}(x * y) for pow(exp{,2}(x), y);
  1000. /// exp2(n * x) for pow(2.0 ** n, x); exp10(x) for pow(10.0, x).
  1001. Value *LibCallSimplifier::replacePowWithExp(CallInst *Pow, IRBuilder<> &B) {
  1002. Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
  1003. AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
  1004. Module *Mod = Pow->getModule();
  1005. Type *Ty = Pow->getType();
  1006. bool Ignored;
  1007. // Evaluate special cases related to a nested function as the base.
  1008. // pow(exp(x), y) -> exp(x * y)
  1009. // pow(exp2(x), y) -> exp2(x * y)
  1010. // If exp{,2}() is used only once, it is better to fold two transcendental
  1011. // math functions into one. If used again, exp{,2}() would still have to be
  1012. // called with the original argument, then keep both original transcendental
  1013. // functions. However, this transformation is only safe with fully relaxed
  1014. // math semantics, since, besides rounding differences, it changes overflow
  1015. // and underflow behavior quite dramatically. For example:
  1016. // pow(exp(1000), 0.001) = pow(inf, 0.001) = inf
  1017. // Whereas:
  1018. // exp(1000 * 0.001) = exp(1)
  1019. // TODO: Loosen the requirement for fully relaxed math semantics.
  1020. // TODO: Handle exp10() when more targets have it available.
  1021. CallInst *BaseFn = dyn_cast<CallInst>(Base);
  1022. if (BaseFn && BaseFn->hasOneUse() && BaseFn->isFast() && Pow->isFast()) {
  1023. LibFunc LibFn;
  1024. Function *CalleeFn = BaseFn->getCalledFunction();
  1025. if (CalleeFn &&
  1026. TLI->getLibFunc(CalleeFn->getName(), LibFn) && TLI->has(LibFn)) {
  1027. StringRef ExpName;
  1028. Intrinsic::ID ID;
  1029. Value *ExpFn;
  1030. LibFunc LibFnFloat;
  1031. LibFunc LibFnDouble;
  1032. LibFunc LibFnLongDouble;
  1033. switch (LibFn) {
  1034. default:
  1035. return nullptr;
  1036. case LibFunc_expf: case LibFunc_exp: case LibFunc_expl:
  1037. ExpName = TLI->getName(LibFunc_exp);
  1038. ID = Intrinsic::exp;
  1039. LibFnFloat = LibFunc_expf;
  1040. LibFnDouble = LibFunc_exp;
  1041. LibFnLongDouble = LibFunc_expl;
  1042. break;
  1043. case LibFunc_exp2f: case LibFunc_exp2: case LibFunc_exp2l:
  1044. ExpName = TLI->getName(LibFunc_exp2);
  1045. ID = Intrinsic::exp2;
  1046. LibFnFloat = LibFunc_exp2f;
  1047. LibFnDouble = LibFunc_exp2;
  1048. LibFnLongDouble = LibFunc_exp2l;
  1049. break;
  1050. }
  1051. // Create new exp{,2}() with the product as its argument.
  1052. Value *FMul = B.CreateFMul(BaseFn->getArgOperand(0), Expo, "mul");
  1053. ExpFn = BaseFn->doesNotAccessMemory()
  1054. ? B.CreateCall(Intrinsic::getDeclaration(Mod, ID, Ty),
  1055. FMul, ExpName)
  1056. : emitUnaryFloatFnCall(FMul, TLI, LibFnDouble, LibFnFloat,
  1057. LibFnLongDouble, B,
  1058. BaseFn->getAttributes());
  1059. // Since the new exp{,2}() is different from the original one, dead code
  1060. // elimination cannot be trusted to remove it, since it may have side
  1061. // effects (e.g., errno). When the only consumer for the original
  1062. // exp{,2}() is pow(), then it has to be explicitly erased.
  1063. BaseFn->replaceAllUsesWith(ExpFn);
  1064. eraseFromParent(BaseFn);
  1065. return ExpFn;
  1066. }
  1067. }
  1068. // Evaluate special cases related to a constant base.
  1069. const APFloat *BaseF;
  1070. if (!match(Pow->getArgOperand(0), m_APFloat(BaseF)))
  1071. return nullptr;
  1072. // pow(2.0 ** n, x) -> exp2(n * x)
  1073. if (hasUnaryFloatFn(TLI, Ty, LibFunc_exp2, LibFunc_exp2f, LibFunc_exp2l)) {
  1074. APFloat BaseR = APFloat(1.0);
  1075. BaseR.convert(BaseF->getSemantics(), APFloat::rmTowardZero, &Ignored);
  1076. BaseR = BaseR / *BaseF;
  1077. bool IsInteger = BaseF->isInteger(),
  1078. IsReciprocal = BaseR.isInteger();
  1079. const APFloat *NF = IsReciprocal ? &BaseR : BaseF;
  1080. APSInt NI(64, false);
  1081. if ((IsInteger || IsReciprocal) &&
  1082. !NF->convertToInteger(NI, APFloat::rmTowardZero, &Ignored) &&
  1083. NI > 1 && NI.isPowerOf2()) {
  1084. double N = NI.logBase2() * (IsReciprocal ? -1.0 : 1.0);
  1085. Value *FMul = B.CreateFMul(Expo, ConstantFP::get(Ty, N), "mul");
  1086. if (Pow->doesNotAccessMemory())
  1087. return B.CreateCall(Intrinsic::getDeclaration(Mod, Intrinsic::exp2, Ty),
  1088. FMul, "exp2");
  1089. else
  1090. return emitUnaryFloatFnCall(FMul, TLI, LibFunc_exp2, LibFunc_exp2f,
  1091. LibFunc_exp2l, B, Attrs);
  1092. }
  1093. }
  1094. // pow(10.0, x) -> exp10(x)
  1095. // TODO: There is no exp10() intrinsic yet, but some day there shall be one.
  1096. if (match(Base, m_SpecificFP(10.0)) &&
  1097. hasUnaryFloatFn(TLI, Ty, LibFunc_exp10, LibFunc_exp10f, LibFunc_exp10l))
  1098. return emitUnaryFloatFnCall(Expo, TLI, LibFunc_exp10, LibFunc_exp10f,
  1099. LibFunc_exp10l, B, Attrs);
  1100. return nullptr;
  1101. }
  1102. static Value *getSqrtCall(Value *V, AttributeList Attrs, bool NoErrno,
  1103. Module *M, IRBuilder<> &B,
  1104. const TargetLibraryInfo *TLI) {
  1105. // If errno is never set, then use the intrinsic for sqrt().
  1106. if (NoErrno) {
  1107. Function *SqrtFn =
  1108. Intrinsic::getDeclaration(M, Intrinsic::sqrt, V->getType());
  1109. return B.CreateCall(SqrtFn, V, "sqrt");
  1110. }
  1111. // Otherwise, use the libcall for sqrt().
  1112. if (hasUnaryFloatFn(TLI, V->getType(), LibFunc_sqrt, LibFunc_sqrtf,
  1113. LibFunc_sqrtl))
  1114. // TODO: We also should check that the target can in fact lower the sqrt()
  1115. // libcall. We currently have no way to ask this question, so we ask if
  1116. // the target has a sqrt() libcall, which is not exactly the same.
  1117. return emitUnaryFloatFnCall(V, TLI, LibFunc_sqrt, LibFunc_sqrtf,
  1118. LibFunc_sqrtl, B, Attrs);
  1119. return nullptr;
  1120. }
  1121. /// Use square root in place of pow(x, +/-0.5).
  1122. Value *LibCallSimplifier::replacePowWithSqrt(CallInst *Pow, IRBuilder<> &B) {
  1123. Value *Sqrt, *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
  1124. AttributeList Attrs = Pow->getCalledFunction()->getAttributes();
  1125. Module *Mod = Pow->getModule();
  1126. Type *Ty = Pow->getType();
  1127. const APFloat *ExpoF;
  1128. if (!match(Expo, m_APFloat(ExpoF)) ||
  1129. (!ExpoF->isExactlyValue(0.5) && !ExpoF->isExactlyValue(-0.5)))
  1130. return nullptr;
  1131. Sqrt = getSqrtCall(Base, Attrs, Pow->doesNotAccessMemory(), Mod, B, TLI);
  1132. if (!Sqrt)
  1133. return nullptr;
  1134. // Handle signed zero base by expanding to fabs(sqrt(x)).
  1135. if (!Pow->hasNoSignedZeros()) {
  1136. Function *FAbsFn = Intrinsic::getDeclaration(Mod, Intrinsic::fabs, Ty);
  1137. Sqrt = B.CreateCall(FAbsFn, Sqrt, "abs");
  1138. }
  1139. // Handle non finite base by expanding to
  1140. // (x == -infinity ? +infinity : sqrt(x)).
  1141. if (!Pow->hasNoInfs()) {
  1142. Value *PosInf = ConstantFP::getInfinity(Ty),
  1143. *NegInf = ConstantFP::getInfinity(Ty, true);
  1144. Value *FCmp = B.CreateFCmpOEQ(Base, NegInf, "isinf");
  1145. Sqrt = B.CreateSelect(FCmp, PosInf, Sqrt);
  1146. }
  1147. // If the exponent is negative, then get the reciprocal.
  1148. if (ExpoF->isNegative())
  1149. Sqrt = B.CreateFDiv(ConstantFP::get(Ty, 1.0), Sqrt, "reciprocal");
  1150. return Sqrt;
  1151. }
  1152. Value *LibCallSimplifier::optimizePow(CallInst *Pow, IRBuilder<> &B) {
  1153. Value *Base = Pow->getArgOperand(0), *Expo = Pow->getArgOperand(1);
  1154. Function *Callee = Pow->getCalledFunction();
  1155. StringRef Name = Callee->getName();
  1156. Type *Ty = Pow->getType();
  1157. Value *Shrunk = nullptr;
  1158. bool Ignored;
  1159. // Bail out if simplifying libcalls to pow() is disabled.
  1160. if (!hasUnaryFloatFn(TLI, Ty, LibFunc_pow, LibFunc_powf, LibFunc_powl))
  1161. return nullptr;
  1162. // Propagate the math semantics from the call to any created instructions.
  1163. IRBuilder<>::FastMathFlagGuard Guard(B);
  1164. B.setFastMathFlags(Pow->getFastMathFlags());
  1165. // Shrink pow() to powf() if the arguments are single precision,
  1166. // unless the result is expected to be double precision.
  1167. if (UnsafeFPShrink &&
  1168. Name == TLI->getName(LibFunc_pow) && hasFloatVersion(Name))
  1169. Shrunk = optimizeBinaryDoubleFP(Pow, B, true);
  1170. // Evaluate special cases related to the base.
  1171. // pow(1.0, x) -> 1.0
  1172. if (match(Base, m_FPOne()))
  1173. return Base;
  1174. if (Value *Exp = replacePowWithExp(Pow, B))
  1175. return Exp;
  1176. // Evaluate special cases related to the exponent.
  1177. // pow(x, -1.0) -> 1.0 / x
  1178. if (match(Expo, m_SpecificFP(-1.0)))
  1179. return B.CreateFDiv(ConstantFP::get(Ty, 1.0), Base, "reciprocal");
  1180. // pow(x, 0.0) -> 1.0
  1181. if (match(Expo, m_SpecificFP(0.0)))
  1182. return ConstantFP::get(Ty, 1.0);
  1183. // pow(x, 1.0) -> x
  1184. if (match(Expo, m_FPOne()))
  1185. return Base;
  1186. // pow(x, 2.0) -> x * x
  1187. if (match(Expo, m_SpecificFP(2.0)))
  1188. return B.CreateFMul(Base, Base, "square");
  1189. if (Value *Sqrt = replacePowWithSqrt(Pow, B))
  1190. return Sqrt;
  1191. // pow(x, n) -> x * x * x * ...
  1192. const APFloat *ExpoF;
  1193. if (Pow->isFast() && match(Expo, m_APFloat(ExpoF))) {
  1194. // We limit to a max of 7 multiplications, thus the maximum exponent is 32.
  1195. // If the exponent is an integer+0.5 we generate a call to sqrt and an
  1196. // additional fmul.
  1197. // TODO: This whole transformation should be backend specific (e.g. some
  1198. // backends might prefer libcalls or the limit for the exponent might
  1199. // be different) and it should also consider optimizing for size.
  1200. APFloat LimF(ExpoF->getSemantics(), 33.0),
  1201. ExpoA(abs(*ExpoF));
  1202. if (ExpoA.compare(LimF) == APFloat::cmpLessThan) {
  1203. // This transformation applies to integer or integer+0.5 exponents only.
  1204. // For integer+0.5, we create a sqrt(Base) call.
  1205. Value *Sqrt = nullptr;
  1206. if (!ExpoA.isInteger()) {
  1207. APFloat Expo2 = ExpoA;
  1208. // To check if ExpoA is an integer + 0.5, we add it to itself. If there
  1209. // is no floating point exception and the result is an integer, then
  1210. // ExpoA == integer + 0.5
  1211. if (Expo2.add(ExpoA, APFloat::rmNearestTiesToEven) != APFloat::opOK)
  1212. return nullptr;
  1213. if (!Expo2.isInteger())
  1214. return nullptr;
  1215. Sqrt =
  1216. getSqrtCall(Base, Pow->getCalledFunction()->getAttributes(),
  1217. Pow->doesNotAccessMemory(), Pow->getModule(), B, TLI);
  1218. }
  1219. // We will memoize intermediate products of the Addition Chain.
  1220. Value *InnerChain[33] = {nullptr};
  1221. InnerChain[1] = Base;
  1222. InnerChain[2] = B.CreateFMul(Base, Base, "square");
  1223. // We cannot readily convert a non-double type (like float) to a double.
  1224. // So we first convert it to something which could be converted to double.
  1225. ExpoA.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &Ignored);
  1226. Value *FMul = getPow(InnerChain, ExpoA.convertToDouble(), B);
  1227. // Expand pow(x, y+0.5) to pow(x, y) * sqrt(x).
  1228. if (Sqrt)
  1229. FMul = B.CreateFMul(FMul, Sqrt);
  1230. // If the exponent is negative, then get the reciprocal.
  1231. if (ExpoF->isNegative())
  1232. FMul = B.CreateFDiv(ConstantFP::get(Ty, 1.0), FMul, "reciprocal");
  1233. return FMul;
  1234. }
  1235. }
  1236. return Shrunk;
  1237. }
  1238. Value *LibCallSimplifier::optimizeExp2(CallInst *CI, IRBuilder<> &B) {
  1239. Function *Callee = CI->getCalledFunction();
  1240. Value *Ret = nullptr;
  1241. StringRef Name = Callee->getName();
  1242. if (UnsafeFPShrink && Name == "exp2" && hasFloatVersion(Name))
  1243. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1244. Value *Op = CI->getArgOperand(0);
  1245. // Turn exp2(sitofp(x)) -> ldexp(1.0, sext(x)) if sizeof(x) <= 32
  1246. // Turn exp2(uitofp(x)) -> ldexp(1.0, zext(x)) if sizeof(x) < 32
  1247. LibFunc LdExp = LibFunc_ldexpl;
  1248. if (Op->getType()->isFloatTy())
  1249. LdExp = LibFunc_ldexpf;
  1250. else if (Op->getType()->isDoubleTy())
  1251. LdExp = LibFunc_ldexp;
  1252. if (TLI->has(LdExp)) {
  1253. Value *LdExpArg = nullptr;
  1254. if (SIToFPInst *OpC = dyn_cast<SIToFPInst>(Op)) {
  1255. if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() <= 32)
  1256. LdExpArg = B.CreateSExt(OpC->getOperand(0), B.getInt32Ty());
  1257. } else if (UIToFPInst *OpC = dyn_cast<UIToFPInst>(Op)) {
  1258. if (OpC->getOperand(0)->getType()->getPrimitiveSizeInBits() < 32)
  1259. LdExpArg = B.CreateZExt(OpC->getOperand(0), B.getInt32Ty());
  1260. }
  1261. if (LdExpArg) {
  1262. Constant *One = ConstantFP::get(CI->getContext(), APFloat(1.0f));
  1263. if (!Op->getType()->isFloatTy())
  1264. One = ConstantExpr::getFPExtend(One, Op->getType());
  1265. Module *M = CI->getModule();
  1266. FunctionCallee NewCallee = M->getOrInsertFunction(
  1267. TLI->getName(LdExp), Op->getType(), Op->getType(), B.getInt32Ty());
  1268. CallInst *CI = B.CreateCall(NewCallee, {One, LdExpArg});
  1269. if (const Function *F = dyn_cast<Function>(Callee->stripPointerCasts()))
  1270. CI->setCallingConv(F->getCallingConv());
  1271. return CI;
  1272. }
  1273. }
  1274. return Ret;
  1275. }
  1276. Value *LibCallSimplifier::optimizeFMinFMax(CallInst *CI, IRBuilder<> &B) {
  1277. Function *Callee = CI->getCalledFunction();
  1278. // If we can shrink the call to a float function rather than a double
  1279. // function, do that first.
  1280. StringRef Name = Callee->getName();
  1281. if ((Name == "fmin" || Name == "fmax") && hasFloatVersion(Name))
  1282. if (Value *Ret = optimizeBinaryDoubleFP(CI, B))
  1283. return Ret;
  1284. IRBuilder<>::FastMathFlagGuard Guard(B);
  1285. FastMathFlags FMF;
  1286. if (CI->isFast()) {
  1287. // If the call is 'fast', then anything we create here will also be 'fast'.
  1288. FMF.setFast();
  1289. } else {
  1290. // At a minimum, no-nans-fp-math must be true.
  1291. if (!CI->hasNoNaNs())
  1292. return nullptr;
  1293. // No-signed-zeros is implied by the definitions of fmax/fmin themselves:
  1294. // "Ideally, fmax would be sensitive to the sign of zero, for example
  1295. // fmax(-0. 0, +0. 0) would return +0; however, implementation in software
  1296. // might be impractical."
  1297. FMF.setNoSignedZeros();
  1298. FMF.setNoNaNs();
  1299. }
  1300. B.setFastMathFlags(FMF);
  1301. // We have a relaxed floating-point environment. We can ignore NaN-handling
  1302. // and transform to a compare and select. We do not have to consider errno or
  1303. // exceptions, because fmin/fmax do not have those.
  1304. Value *Op0 = CI->getArgOperand(0);
  1305. Value *Op1 = CI->getArgOperand(1);
  1306. Value *Cmp = Callee->getName().startswith("fmin") ?
  1307. B.CreateFCmpOLT(Op0, Op1) : B.CreateFCmpOGT(Op0, Op1);
  1308. return B.CreateSelect(Cmp, Op0, Op1);
  1309. }
  1310. Value *LibCallSimplifier::optimizeLog(CallInst *CI, IRBuilder<> &B) {
  1311. Function *Callee = CI->getCalledFunction();
  1312. Value *Ret = nullptr;
  1313. StringRef Name = Callee->getName();
  1314. if (UnsafeFPShrink && hasFloatVersion(Name))
  1315. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1316. if (!CI->isFast())
  1317. return Ret;
  1318. Value *Op1 = CI->getArgOperand(0);
  1319. auto *OpC = dyn_cast<CallInst>(Op1);
  1320. // The earlier call must also be 'fast' in order to do these transforms.
  1321. if (!OpC || !OpC->isFast())
  1322. return Ret;
  1323. // log(pow(x,y)) -> y*log(x)
  1324. // This is only applicable to log, log2, log10.
  1325. if (Name != "log" && Name != "log2" && Name != "log10")
  1326. return Ret;
  1327. IRBuilder<>::FastMathFlagGuard Guard(B);
  1328. FastMathFlags FMF;
  1329. FMF.setFast();
  1330. B.setFastMathFlags(FMF);
  1331. LibFunc Func;
  1332. Function *F = OpC->getCalledFunction();
  1333. if (F && ((TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
  1334. Func == LibFunc_pow) || F->getIntrinsicID() == Intrinsic::pow))
  1335. return B.CreateFMul(OpC->getArgOperand(1),
  1336. emitUnaryFloatFnCall(OpC->getOperand(0), Callee->getName(), B,
  1337. Callee->getAttributes()), "mul");
  1338. // log(exp2(y)) -> y*log(2)
  1339. if (F && Name == "log" && TLI->getLibFunc(F->getName(), Func) &&
  1340. TLI->has(Func) && Func == LibFunc_exp2)
  1341. return B.CreateFMul(
  1342. OpC->getArgOperand(0),
  1343. emitUnaryFloatFnCall(ConstantFP::get(CI->getType(), 2.0),
  1344. Callee->getName(), B, Callee->getAttributes()),
  1345. "logmul");
  1346. return Ret;
  1347. }
  1348. Value *LibCallSimplifier::optimizeSqrt(CallInst *CI, IRBuilder<> &B) {
  1349. Function *Callee = CI->getCalledFunction();
  1350. Value *Ret = nullptr;
  1351. // TODO: Once we have a way (other than checking for the existince of the
  1352. // libcall) to tell whether our target can lower @llvm.sqrt, relax the
  1353. // condition below.
  1354. if (TLI->has(LibFunc_sqrtf) && (Callee->getName() == "sqrt" ||
  1355. Callee->getIntrinsicID() == Intrinsic::sqrt))
  1356. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1357. if (!CI->isFast())
  1358. return Ret;
  1359. Instruction *I = dyn_cast<Instruction>(CI->getArgOperand(0));
  1360. if (!I || I->getOpcode() != Instruction::FMul || !I->isFast())
  1361. return Ret;
  1362. // We're looking for a repeated factor in a multiplication tree,
  1363. // so we can do this fold: sqrt(x * x) -> fabs(x);
  1364. // or this fold: sqrt((x * x) * y) -> fabs(x) * sqrt(y).
  1365. Value *Op0 = I->getOperand(0);
  1366. Value *Op1 = I->getOperand(1);
  1367. Value *RepeatOp = nullptr;
  1368. Value *OtherOp = nullptr;
  1369. if (Op0 == Op1) {
  1370. // Simple match: the operands of the multiply are identical.
  1371. RepeatOp = Op0;
  1372. } else {
  1373. // Look for a more complicated pattern: one of the operands is itself
  1374. // a multiply, so search for a common factor in that multiply.
  1375. // Note: We don't bother looking any deeper than this first level or for
  1376. // variations of this pattern because instcombine's visitFMUL and/or the
  1377. // reassociation pass should give us this form.
  1378. Value *OtherMul0, *OtherMul1;
  1379. if (match(Op0, m_FMul(m_Value(OtherMul0), m_Value(OtherMul1)))) {
  1380. // Pattern: sqrt((x * y) * z)
  1381. if (OtherMul0 == OtherMul1 && cast<Instruction>(Op0)->isFast()) {
  1382. // Matched: sqrt((x * x) * z)
  1383. RepeatOp = OtherMul0;
  1384. OtherOp = Op1;
  1385. }
  1386. }
  1387. }
  1388. if (!RepeatOp)
  1389. return Ret;
  1390. // Fast math flags for any created instructions should match the sqrt
  1391. // and multiply.
  1392. IRBuilder<>::FastMathFlagGuard Guard(B);
  1393. B.setFastMathFlags(I->getFastMathFlags());
  1394. // If we found a repeated factor, hoist it out of the square root and
  1395. // replace it with the fabs of that factor.
  1396. Module *M = Callee->getParent();
  1397. Type *ArgType = I->getType();
  1398. Value *Fabs = Intrinsic::getDeclaration(M, Intrinsic::fabs, ArgType);
  1399. Value *FabsCall = B.CreateCall(Fabs, RepeatOp, "fabs");
  1400. if (OtherOp) {
  1401. // If we found a non-repeated factor, we still need to get its square
  1402. // root. We then multiply that by the value that was simplified out
  1403. // of the square root calculation.
  1404. Value *Sqrt = Intrinsic::getDeclaration(M, Intrinsic::sqrt, ArgType);
  1405. Value *SqrtCall = B.CreateCall(Sqrt, OtherOp, "sqrt");
  1406. return B.CreateFMul(FabsCall, SqrtCall);
  1407. }
  1408. return FabsCall;
  1409. }
  1410. // TODO: Generalize to handle any trig function and its inverse.
  1411. Value *LibCallSimplifier::optimizeTan(CallInst *CI, IRBuilder<> &B) {
  1412. Function *Callee = CI->getCalledFunction();
  1413. Value *Ret = nullptr;
  1414. StringRef Name = Callee->getName();
  1415. if (UnsafeFPShrink && Name == "tan" && hasFloatVersion(Name))
  1416. Ret = optimizeUnaryDoubleFP(CI, B, true);
  1417. Value *Op1 = CI->getArgOperand(0);
  1418. auto *OpC = dyn_cast<CallInst>(Op1);
  1419. if (!OpC)
  1420. return Ret;
  1421. // Both calls must be 'fast' in order to remove them.
  1422. if (!CI->isFast() || !OpC->isFast())
  1423. return Ret;
  1424. // tan(atan(x)) -> x
  1425. // tanf(atanf(x)) -> x
  1426. // tanl(atanl(x)) -> x
  1427. LibFunc Func;
  1428. Function *F = OpC->getCalledFunction();
  1429. if (F && TLI->getLibFunc(F->getName(), Func) && TLI->has(Func) &&
  1430. ((Func == LibFunc_atan && Callee->getName() == "tan") ||
  1431. (Func == LibFunc_atanf && Callee->getName() == "tanf") ||
  1432. (Func == LibFunc_atanl && Callee->getName() == "tanl")))
  1433. Ret = OpC->getArgOperand(0);
  1434. return Ret;
  1435. }
  1436. static bool isTrigLibCall(CallInst *CI) {
  1437. // We can only hope to do anything useful if we can ignore things like errno
  1438. // and floating-point exceptions.
  1439. // We already checked the prototype.
  1440. return CI->hasFnAttr(Attribute::NoUnwind) &&
  1441. CI->hasFnAttr(Attribute::ReadNone);
  1442. }
  1443. static void insertSinCosCall(IRBuilder<> &B, Function *OrigCallee, Value *Arg,
  1444. bool UseFloat, Value *&Sin, Value *&Cos,
  1445. Value *&SinCos) {
  1446. Type *ArgTy = Arg->getType();
  1447. Type *ResTy;
  1448. StringRef Name;
  1449. Triple T(OrigCallee->getParent()->getTargetTriple());
  1450. if (UseFloat) {
  1451. Name = "__sincospif_stret";
  1452. assert(T.getArch() != Triple::x86 && "x86 messy and unsupported for now");
  1453. // x86_64 can't use {float, float} since that would be returned in both
  1454. // xmm0 and xmm1, which isn't what a real struct would do.
  1455. ResTy = T.getArch() == Triple::x86_64
  1456. ? static_cast<Type *>(VectorType::get(ArgTy, 2))
  1457. : static_cast<Type *>(StructType::get(ArgTy, ArgTy));
  1458. } else {
  1459. Name = "__sincospi_stret";
  1460. ResTy = StructType::get(ArgTy, ArgTy);
  1461. }
  1462. Module *M = OrigCallee->getParent();
  1463. FunctionCallee Callee =
  1464. M->getOrInsertFunction(Name, OrigCallee->getAttributes(), ResTy, ArgTy);
  1465. if (Instruction *ArgInst = dyn_cast<Instruction>(Arg)) {
  1466. // If the argument is an instruction, it must dominate all uses so put our
  1467. // sincos call there.
  1468. B.SetInsertPoint(ArgInst->getParent(), ++ArgInst->getIterator());
  1469. } else {
  1470. // Otherwise (e.g. for a constant) the beginning of the function is as
  1471. // good a place as any.
  1472. BasicBlock &EntryBB = B.GetInsertBlock()->getParent()->getEntryBlock();
  1473. B.SetInsertPoint(&EntryBB, EntryBB.begin());
  1474. }
  1475. SinCos = B.CreateCall(Callee, Arg, "sincospi");
  1476. if (SinCos->getType()->isStructTy()) {
  1477. Sin = B.CreateExtractValue(SinCos, 0, "sinpi");
  1478. Cos = B.CreateExtractValue(SinCos, 1, "cospi");
  1479. } else {
  1480. Sin = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 0),
  1481. "sinpi");
  1482. Cos = B.CreateExtractElement(SinCos, ConstantInt::get(B.getInt32Ty(), 1),
  1483. "cospi");
  1484. }
  1485. }
  1486. Value *LibCallSimplifier::optimizeSinCosPi(CallInst *CI, IRBuilder<> &B) {
  1487. // Make sure the prototype is as expected, otherwise the rest of the
  1488. // function is probably invalid and likely to abort.
  1489. if (!isTrigLibCall(CI))
  1490. return nullptr;
  1491. Value *Arg = CI->getArgOperand(0);
  1492. SmallVector<CallInst *, 1> SinCalls;
  1493. SmallVector<CallInst *, 1> CosCalls;
  1494. SmallVector<CallInst *, 1> SinCosCalls;
  1495. bool IsFloat = Arg->getType()->isFloatTy();
  1496. // Look for all compatible sinpi, cospi and sincospi calls with the same
  1497. // argument. If there are enough (in some sense) we can make the
  1498. // substitution.
  1499. Function *F = CI->getFunction();
  1500. for (User *U : Arg->users())
  1501. classifyArgUse(U, F, IsFloat, SinCalls, CosCalls, SinCosCalls);
  1502. // It's only worthwhile if both sinpi and cospi are actually used.
  1503. if (SinCosCalls.empty() && (SinCalls.empty() || CosCalls.empty()))
  1504. return nullptr;
  1505. Value *Sin, *Cos, *SinCos;
  1506. insertSinCosCall(B, CI->getCalledFunction(), Arg, IsFloat, Sin, Cos, SinCos);
  1507. auto replaceTrigInsts = [this](SmallVectorImpl<CallInst *> &Calls,
  1508. Value *Res) {
  1509. for (CallInst *C : Calls)
  1510. replaceAllUsesWith(C, Res);
  1511. };
  1512. replaceTrigInsts(SinCalls, Sin);
  1513. replaceTrigInsts(CosCalls, Cos);
  1514. replaceTrigInsts(SinCosCalls, SinCos);
  1515. return nullptr;
  1516. }
  1517. void LibCallSimplifier::classifyArgUse(
  1518. Value *Val, Function *F, bool IsFloat,
  1519. SmallVectorImpl<CallInst *> &SinCalls,
  1520. SmallVectorImpl<CallInst *> &CosCalls,
  1521. SmallVectorImpl<CallInst *> &SinCosCalls) {
  1522. CallInst *CI = dyn_cast<CallInst>(Val);
  1523. if (!CI)
  1524. return;
  1525. // Don't consider calls in other functions.
  1526. if (CI->getFunction() != F)
  1527. return;
  1528. Function *Callee = CI->getCalledFunction();
  1529. LibFunc Func;
  1530. if (!Callee || !TLI->getLibFunc(*Callee, Func) || !TLI->has(Func) ||
  1531. !isTrigLibCall(CI))
  1532. return;
  1533. if (IsFloat) {
  1534. if (Func == LibFunc_sinpif)
  1535. SinCalls.push_back(CI);
  1536. else if (Func == LibFunc_cospif)
  1537. CosCalls.push_back(CI);
  1538. else if (Func == LibFunc_sincospif_stret)
  1539. SinCosCalls.push_back(CI);
  1540. } else {
  1541. if (Func == LibFunc_sinpi)
  1542. SinCalls.push_back(CI);
  1543. else if (Func == LibFunc_cospi)
  1544. CosCalls.push_back(CI);
  1545. else if (Func == LibFunc_sincospi_stret)
  1546. SinCosCalls.push_back(CI);
  1547. }
  1548. }
  1549. //===----------------------------------------------------------------------===//
  1550. // Integer Library Call Optimizations
  1551. //===----------------------------------------------------------------------===//
  1552. Value *LibCallSimplifier::optimizeFFS(CallInst *CI, IRBuilder<> &B) {
  1553. // ffs(x) -> x != 0 ? (i32)llvm.cttz(x)+1 : 0
  1554. Value *Op = CI->getArgOperand(0);
  1555. Type *ArgType = Op->getType();
  1556. Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
  1557. Intrinsic::cttz, ArgType);
  1558. Value *V = B.CreateCall(F, {Op, B.getTrue()}, "cttz");
  1559. V = B.CreateAdd(V, ConstantInt::get(V->getType(), 1));
  1560. V = B.CreateIntCast(V, B.getInt32Ty(), false);
  1561. Value *Cond = B.CreateICmpNE(Op, Constant::getNullValue(ArgType));
  1562. return B.CreateSelect(Cond, V, B.getInt32(0));
  1563. }
  1564. Value *LibCallSimplifier::optimizeFls(CallInst *CI, IRBuilder<> &B) {
  1565. // fls(x) -> (i32)(sizeInBits(x) - llvm.ctlz(x, false))
  1566. Value *Op = CI->getArgOperand(0);
  1567. Type *ArgType = Op->getType();
  1568. Value *F = Intrinsic::getDeclaration(CI->getCalledFunction()->getParent(),
  1569. Intrinsic::ctlz, ArgType);
  1570. Value *V = B.CreateCall(F, {Op, B.getFalse()}, "ctlz");
  1571. V = B.CreateSub(ConstantInt::get(V->getType(), ArgType->getIntegerBitWidth()),
  1572. V);
  1573. return B.CreateIntCast(V, CI->getType(), false);
  1574. }
  1575. Value *LibCallSimplifier::optimizeAbs(CallInst *CI, IRBuilder<> &B) {
  1576. // abs(x) -> x <s 0 ? -x : x
  1577. // The negation has 'nsw' because abs of INT_MIN is undefined.
  1578. Value *X = CI->getArgOperand(0);
  1579. Value *IsNeg = B.CreateICmpSLT(X, Constant::getNullValue(X->getType()));
  1580. Value *NegX = B.CreateNSWNeg(X, "neg");
  1581. return B.CreateSelect(IsNeg, NegX, X);
  1582. }
  1583. Value *LibCallSimplifier::optimizeIsDigit(CallInst *CI, IRBuilder<> &B) {
  1584. // isdigit(c) -> (c-'0') <u 10
  1585. Value *Op = CI->getArgOperand(0);
  1586. Op = B.CreateSub(Op, B.getInt32('0'), "isdigittmp");
  1587. Op = B.CreateICmpULT(Op, B.getInt32(10), "isdigit");
  1588. return B.CreateZExt(Op, CI->getType());
  1589. }
  1590. Value *LibCallSimplifier::optimizeIsAscii(CallInst *CI, IRBuilder<> &B) {
  1591. // isascii(c) -> c <u 128
  1592. Value *Op = CI->getArgOperand(0);
  1593. Op = B.CreateICmpULT(Op, B.getInt32(128), "isascii");
  1594. return B.CreateZExt(Op, CI->getType());
  1595. }
  1596. Value *LibCallSimplifier::optimizeToAscii(CallInst *CI, IRBuilder<> &B) {
  1597. // toascii(c) -> c & 0x7f
  1598. return B.CreateAnd(CI->getArgOperand(0),
  1599. ConstantInt::get(CI->getType(), 0x7F));
  1600. }
  1601. Value *LibCallSimplifier::optimizeAtoi(CallInst *CI, IRBuilder<> &B) {
  1602. StringRef Str;
  1603. if (!getConstantStringInfo(CI->getArgOperand(0), Str))
  1604. return nullptr;
  1605. return convertStrToNumber(CI, Str, 10);
  1606. }
  1607. Value *LibCallSimplifier::optimizeStrtol(CallInst *CI, IRBuilder<> &B) {
  1608. StringRef Str;
  1609. if (!getConstantStringInfo(CI->getArgOperand(0), Str))
  1610. return nullptr;
  1611. if (!isa<ConstantPointerNull>(CI->getArgOperand(1)))
  1612. return nullptr;
  1613. if (ConstantInt *CInt = dyn_cast<ConstantInt>(CI->getArgOperand(2))) {
  1614. return convertStrToNumber(CI, Str, CInt->getSExtValue());
  1615. }
  1616. return nullptr;
  1617. }
  1618. //===----------------------------------------------------------------------===//
  1619. // Formatting and IO Library Call Optimizations
  1620. //===----------------------------------------------------------------------===//
  1621. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg);
  1622. Value *LibCallSimplifier::optimizeErrorReporting(CallInst *CI, IRBuilder<> &B,
  1623. int StreamArg) {
  1624. Function *Callee = CI->getCalledFunction();
  1625. // Error reporting calls should be cold, mark them as such.
  1626. // This applies even to non-builtin calls: it is only a hint and applies to
  1627. // functions that the frontend might not understand as builtins.
  1628. // This heuristic was suggested in:
  1629. // Improving Static Branch Prediction in a Compiler
  1630. // Brian L. Deitrich, Ben-Chung Cheng, Wen-mei W. Hwu
  1631. // Proceedings of PACT'98, Oct. 1998, IEEE
  1632. if (!CI->hasFnAttr(Attribute::Cold) &&
  1633. isReportingError(Callee, CI, StreamArg)) {
  1634. CI->addAttribute(AttributeList::FunctionIndex, Attribute::Cold);
  1635. }
  1636. return nullptr;
  1637. }
  1638. static bool isReportingError(Function *Callee, CallInst *CI, int StreamArg) {
  1639. if (!Callee || !Callee->isDeclaration())
  1640. return false;
  1641. if (StreamArg < 0)
  1642. return true;
  1643. // These functions might be considered cold, but only if their stream
  1644. // argument is stderr.
  1645. if (StreamArg >= (int)CI->getNumArgOperands())
  1646. return false;
  1647. LoadInst *LI = dyn_cast<LoadInst>(CI->getArgOperand(StreamArg));
  1648. if (!LI)
  1649. return false;
  1650. GlobalVariable *GV = dyn_cast<GlobalVariable>(LI->getPointerOperand());
  1651. if (!GV || !GV->isDeclaration())
  1652. return false;
  1653. return GV->getName() == "stderr";
  1654. }
  1655. Value *LibCallSimplifier::optimizePrintFString(CallInst *CI, IRBuilder<> &B) {
  1656. // Check for a fixed format string.
  1657. StringRef FormatStr;
  1658. if (!getConstantStringInfo(CI->getArgOperand(0), FormatStr))
  1659. return nullptr;
  1660. // Empty format string -> noop.
  1661. if (FormatStr.empty()) // Tolerate printf's declared void.
  1662. return CI->use_empty() ? (Value *)CI : ConstantInt::get(CI->getType(), 0);
  1663. // Do not do any of the following transformations if the printf return value
  1664. // is used, in general the printf return value is not compatible with either
  1665. // putchar() or puts().
  1666. if (!CI->use_empty())
  1667. return nullptr;
  1668. // printf("x") -> putchar('x'), even for "%" and "%%".
  1669. if (FormatStr.size() == 1 || FormatStr == "%%")
  1670. return emitPutChar(B.getInt32(FormatStr[0]), B, TLI);
  1671. // printf("%s", "a") --> putchar('a')
  1672. if (FormatStr == "%s" && CI->getNumArgOperands() > 1) {
  1673. StringRef ChrStr;
  1674. if (!getConstantStringInfo(CI->getOperand(1), ChrStr))
  1675. return nullptr;
  1676. if (ChrStr.size() != 1)
  1677. return nullptr;
  1678. return emitPutChar(B.getInt32(ChrStr[0]), B, TLI);
  1679. }
  1680. // printf("foo\n") --> puts("foo")
  1681. if (FormatStr[FormatStr.size() - 1] == '\n' &&
  1682. FormatStr.find('%') == StringRef::npos) { // No format characters.
  1683. // Create a string literal with no \n on it. We expect the constant merge
  1684. // pass to be run after this pass, to merge duplicate strings.
  1685. FormatStr = FormatStr.drop_back();
  1686. Value *GV = B.CreateGlobalString(FormatStr, "str");
  1687. return emitPutS(GV, B, TLI);
  1688. }
  1689. // Optimize specific format strings.
  1690. // printf("%c", chr) --> putchar(chr)
  1691. if (FormatStr == "%c" && CI->getNumArgOperands() > 1 &&
  1692. CI->getArgOperand(1)->getType()->isIntegerTy())
  1693. return emitPutChar(CI->getArgOperand(1), B, TLI);
  1694. // printf("%s\n", str) --> puts(str)
  1695. if (FormatStr == "%s\n" && CI->getNumArgOperands() > 1 &&
  1696. CI->getArgOperand(1)->getType()->isPointerTy())
  1697. return emitPutS(CI->getArgOperand(1), B, TLI);
  1698. return nullptr;
  1699. }
  1700. Value *LibCallSimplifier::optimizePrintF(CallInst *CI, IRBuilder<> &B) {
  1701. Function *Callee = CI->getCalledFunction();
  1702. FunctionType *FT = Callee->getFunctionType();
  1703. if (Value *V = optimizePrintFString(CI, B)) {
  1704. return V;
  1705. }
  1706. // printf(format, ...) -> iprintf(format, ...) if no floating point
  1707. // arguments.
  1708. if (TLI->has(LibFunc_iprintf) && !callHasFloatingPointArgument(CI)) {
  1709. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1710. FunctionCallee IPrintFFn =
  1711. M->getOrInsertFunction("iprintf", FT, Callee->getAttributes());
  1712. CallInst *New = cast<CallInst>(CI->clone());
  1713. New->setCalledFunction(IPrintFFn);
  1714. B.Insert(New);
  1715. return New;
  1716. }
  1717. return nullptr;
  1718. }
  1719. Value *LibCallSimplifier::optimizeSPrintFString(CallInst *CI, IRBuilder<> &B) {
  1720. // Check for a fixed format string.
  1721. StringRef FormatStr;
  1722. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  1723. return nullptr;
  1724. // If we just have a format string (nothing else crazy) transform it.
  1725. if (CI->getNumArgOperands() == 2) {
  1726. // Make sure there's no % in the constant array. We could try to handle
  1727. // %% -> % in the future if we cared.
  1728. if (FormatStr.find('%') != StringRef::npos)
  1729. return nullptr; // we found a format specifier, bail out.
  1730. // sprintf(str, fmt) -> llvm.memcpy(align 1 str, align 1 fmt, strlen(fmt)+1)
  1731. B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
  1732. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  1733. FormatStr.size() + 1)); // Copy the null byte.
  1734. return ConstantInt::get(CI->getType(), FormatStr.size());
  1735. }
  1736. // The remaining optimizations require the format string to be "%s" or "%c"
  1737. // and have an extra operand.
  1738. if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
  1739. CI->getNumArgOperands() < 3)
  1740. return nullptr;
  1741. // Decode the second character of the format string.
  1742. if (FormatStr[1] == 'c') {
  1743. // sprintf(dst, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
  1744. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  1745. return nullptr;
  1746. Value *V = B.CreateTrunc(CI->getArgOperand(2), B.getInt8Ty(), "char");
  1747. Value *Ptr = castToCStr(CI->getArgOperand(0), B);
  1748. B.CreateStore(V, Ptr);
  1749. Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
  1750. B.CreateStore(B.getInt8(0), Ptr);
  1751. return ConstantInt::get(CI->getType(), 1);
  1752. }
  1753. if (FormatStr[1] == 's') {
  1754. // sprintf(dest, "%s", str) -> llvm.memcpy(dest, str, strlen(str)+1, 1)
  1755. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  1756. return nullptr;
  1757. Value *Len = emitStrLen(CI->getArgOperand(2), B, DL, TLI);
  1758. if (!Len)
  1759. return nullptr;
  1760. Value *IncLen =
  1761. B.CreateAdd(Len, ConstantInt::get(Len->getType(), 1), "leninc");
  1762. B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(2), 1, IncLen);
  1763. // The sprintf result is the unincremented number of bytes in the string.
  1764. return B.CreateIntCast(Len, CI->getType(), false);
  1765. }
  1766. return nullptr;
  1767. }
  1768. Value *LibCallSimplifier::optimizeSPrintF(CallInst *CI, IRBuilder<> &B) {
  1769. Function *Callee = CI->getCalledFunction();
  1770. FunctionType *FT = Callee->getFunctionType();
  1771. if (Value *V = optimizeSPrintFString(CI, B)) {
  1772. return V;
  1773. }
  1774. // sprintf(str, format, ...) -> siprintf(str, format, ...) if no floating
  1775. // point arguments.
  1776. if (TLI->has(LibFunc_siprintf) && !callHasFloatingPointArgument(CI)) {
  1777. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1778. FunctionCallee SIPrintFFn =
  1779. M->getOrInsertFunction("siprintf", FT, Callee->getAttributes());
  1780. CallInst *New = cast<CallInst>(CI->clone());
  1781. New->setCalledFunction(SIPrintFFn);
  1782. B.Insert(New);
  1783. return New;
  1784. }
  1785. return nullptr;
  1786. }
  1787. Value *LibCallSimplifier::optimizeSnPrintFString(CallInst *CI, IRBuilder<> &B) {
  1788. // Check for a fixed format string.
  1789. StringRef FormatStr;
  1790. if (!getConstantStringInfo(CI->getArgOperand(2), FormatStr))
  1791. return nullptr;
  1792. // Check for size
  1793. ConstantInt *Size = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  1794. if (!Size)
  1795. return nullptr;
  1796. uint64_t N = Size->getZExtValue();
  1797. // If we just have a format string (nothing else crazy) transform it.
  1798. if (CI->getNumArgOperands() == 3) {
  1799. // Make sure there's no % in the constant array. We could try to handle
  1800. // %% -> % in the future if we cared.
  1801. if (FormatStr.find('%') != StringRef::npos)
  1802. return nullptr; // we found a format specifier, bail out.
  1803. if (N == 0)
  1804. return ConstantInt::get(CI->getType(), FormatStr.size());
  1805. else if (N < FormatStr.size() + 1)
  1806. return nullptr;
  1807. // sprintf(str, size, fmt) -> llvm.memcpy(align 1 str, align 1 fmt,
  1808. // strlen(fmt)+1)
  1809. B.CreateMemCpy(
  1810. CI->getArgOperand(0), 1, CI->getArgOperand(2), 1,
  1811. ConstantInt::get(DL.getIntPtrType(CI->getContext()),
  1812. FormatStr.size() + 1)); // Copy the null byte.
  1813. return ConstantInt::get(CI->getType(), FormatStr.size());
  1814. }
  1815. // The remaining optimizations require the format string to be "%s" or "%c"
  1816. // and have an extra operand.
  1817. if (FormatStr.size() == 2 && FormatStr[0] == '%' &&
  1818. CI->getNumArgOperands() == 4) {
  1819. // Decode the second character of the format string.
  1820. if (FormatStr[1] == 'c') {
  1821. if (N == 0)
  1822. return ConstantInt::get(CI->getType(), 1);
  1823. else if (N == 1)
  1824. return nullptr;
  1825. // snprintf(dst, size, "%c", chr) --> *(i8*)dst = chr; *((i8*)dst+1) = 0
  1826. if (!CI->getArgOperand(3)->getType()->isIntegerTy())
  1827. return nullptr;
  1828. Value *V = B.CreateTrunc(CI->getArgOperand(3), B.getInt8Ty(), "char");
  1829. Value *Ptr = castToCStr(CI->getArgOperand(0), B);
  1830. B.CreateStore(V, Ptr);
  1831. Ptr = B.CreateGEP(B.getInt8Ty(), Ptr, B.getInt32(1), "nul");
  1832. B.CreateStore(B.getInt8(0), Ptr);
  1833. return ConstantInt::get(CI->getType(), 1);
  1834. }
  1835. if (FormatStr[1] == 's') {
  1836. // snprintf(dest, size, "%s", str) to llvm.memcpy(dest, str, len+1, 1)
  1837. StringRef Str;
  1838. if (!getConstantStringInfo(CI->getArgOperand(3), Str))
  1839. return nullptr;
  1840. if (N == 0)
  1841. return ConstantInt::get(CI->getType(), Str.size());
  1842. else if (N < Str.size() + 1)
  1843. return nullptr;
  1844. B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(3), 1,
  1845. ConstantInt::get(CI->getType(), Str.size() + 1));
  1846. // The snprintf result is the unincremented number of bytes in the string.
  1847. return ConstantInt::get(CI->getType(), Str.size());
  1848. }
  1849. }
  1850. return nullptr;
  1851. }
  1852. Value *LibCallSimplifier::optimizeSnPrintF(CallInst *CI, IRBuilder<> &B) {
  1853. if (Value *V = optimizeSnPrintFString(CI, B)) {
  1854. return V;
  1855. }
  1856. return nullptr;
  1857. }
  1858. Value *LibCallSimplifier::optimizeFPrintFString(CallInst *CI, IRBuilder<> &B) {
  1859. optimizeErrorReporting(CI, B, 0);
  1860. // All the optimizations depend on the format string.
  1861. StringRef FormatStr;
  1862. if (!getConstantStringInfo(CI->getArgOperand(1), FormatStr))
  1863. return nullptr;
  1864. // Do not do any of the following transformations if the fprintf return
  1865. // value is used, in general the fprintf return value is not compatible
  1866. // with fwrite(), fputc() or fputs().
  1867. if (!CI->use_empty())
  1868. return nullptr;
  1869. // fprintf(F, "foo") --> fwrite("foo", 3, 1, F)
  1870. if (CI->getNumArgOperands() == 2) {
  1871. // Could handle %% -> % if we cared.
  1872. if (FormatStr.find('%') != StringRef::npos)
  1873. return nullptr; // We found a format specifier.
  1874. return emitFWrite(
  1875. CI->getArgOperand(1),
  1876. ConstantInt::get(DL.getIntPtrType(CI->getContext()), FormatStr.size()),
  1877. CI->getArgOperand(0), B, DL, TLI);
  1878. }
  1879. // The remaining optimizations require the format string to be "%s" or "%c"
  1880. // and have an extra operand.
  1881. if (FormatStr.size() != 2 || FormatStr[0] != '%' ||
  1882. CI->getNumArgOperands() < 3)
  1883. return nullptr;
  1884. // Decode the second character of the format string.
  1885. if (FormatStr[1] == 'c') {
  1886. // fprintf(F, "%c", chr) --> fputc(chr, F)
  1887. if (!CI->getArgOperand(2)->getType()->isIntegerTy())
  1888. return nullptr;
  1889. return emitFPutC(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
  1890. }
  1891. if (FormatStr[1] == 's') {
  1892. // fprintf(F, "%s", str) --> fputs(str, F)
  1893. if (!CI->getArgOperand(2)->getType()->isPointerTy())
  1894. return nullptr;
  1895. return emitFPutS(CI->getArgOperand(2), CI->getArgOperand(0), B, TLI);
  1896. }
  1897. return nullptr;
  1898. }
  1899. Value *LibCallSimplifier::optimizeFPrintF(CallInst *CI, IRBuilder<> &B) {
  1900. Function *Callee = CI->getCalledFunction();
  1901. FunctionType *FT = Callee->getFunctionType();
  1902. if (Value *V = optimizeFPrintFString(CI, B)) {
  1903. return V;
  1904. }
  1905. // fprintf(stream, format, ...) -> fiprintf(stream, format, ...) if no
  1906. // floating point arguments.
  1907. if (TLI->has(LibFunc_fiprintf) && !callHasFloatingPointArgument(CI)) {
  1908. Module *M = B.GetInsertBlock()->getParent()->getParent();
  1909. FunctionCallee FIPrintFFn =
  1910. M->getOrInsertFunction("fiprintf", FT, Callee->getAttributes());
  1911. CallInst *New = cast<CallInst>(CI->clone());
  1912. New->setCalledFunction(FIPrintFFn);
  1913. B.Insert(New);
  1914. return New;
  1915. }
  1916. return nullptr;
  1917. }
  1918. Value *LibCallSimplifier::optimizeFWrite(CallInst *CI, IRBuilder<> &B) {
  1919. optimizeErrorReporting(CI, B, 3);
  1920. // Get the element size and count.
  1921. ConstantInt *SizeC = dyn_cast<ConstantInt>(CI->getArgOperand(1));
  1922. ConstantInt *CountC = dyn_cast<ConstantInt>(CI->getArgOperand(2));
  1923. if (SizeC && CountC) {
  1924. uint64_t Bytes = SizeC->getZExtValue() * CountC->getZExtValue();
  1925. // If this is writing zero records, remove the call (it's a noop).
  1926. if (Bytes == 0)
  1927. return ConstantInt::get(CI->getType(), 0);
  1928. // If this is writing one byte, turn it into fputc.
  1929. // This optimisation is only valid, if the return value is unused.
  1930. if (Bytes == 1 && CI->use_empty()) { // fwrite(S,1,1,F) -> fputc(S[0],F)
  1931. Value *Char = B.CreateLoad(castToCStr(CI->getArgOperand(0), B), "char");
  1932. Value *NewCI = emitFPutC(Char, CI->getArgOperand(3), B, TLI);
  1933. return NewCI ? ConstantInt::get(CI->getType(), 1) : nullptr;
  1934. }
  1935. }
  1936. if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
  1937. return emitFWriteUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
  1938. CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
  1939. TLI);
  1940. return nullptr;
  1941. }
  1942. Value *LibCallSimplifier::optimizeFPuts(CallInst *CI, IRBuilder<> &B) {
  1943. optimizeErrorReporting(CI, B, 1);
  1944. // Don't rewrite fputs to fwrite when optimising for size because fwrite
  1945. // requires more arguments and thus extra MOVs are required.
  1946. if (CI->getFunction()->optForSize())
  1947. return nullptr;
  1948. // Check if has any use
  1949. if (!CI->use_empty()) {
  1950. if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
  1951. return emitFPutSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
  1952. TLI);
  1953. else
  1954. // We can't optimize if return value is used.
  1955. return nullptr;
  1956. }
  1957. // fputs(s,F) --> fwrite(s,1,strlen(s),F)
  1958. uint64_t Len = GetStringLength(CI->getArgOperand(0));
  1959. if (!Len)
  1960. return nullptr;
  1961. // Known to have no uses (see above).
  1962. return emitFWrite(
  1963. CI->getArgOperand(0),
  1964. ConstantInt::get(DL.getIntPtrType(CI->getContext()), Len - 1),
  1965. CI->getArgOperand(1), B, DL, TLI);
  1966. }
  1967. Value *LibCallSimplifier::optimizeFPutc(CallInst *CI, IRBuilder<> &B) {
  1968. optimizeErrorReporting(CI, B, 1);
  1969. if (isLocallyOpenedFile(CI->getArgOperand(1), CI, B, TLI))
  1970. return emitFPutCUnlocked(CI->getArgOperand(0), CI->getArgOperand(1), B,
  1971. TLI);
  1972. return nullptr;
  1973. }
  1974. Value *LibCallSimplifier::optimizeFGetc(CallInst *CI, IRBuilder<> &B) {
  1975. if (isLocallyOpenedFile(CI->getArgOperand(0), CI, B, TLI))
  1976. return emitFGetCUnlocked(CI->getArgOperand(0), B, TLI);
  1977. return nullptr;
  1978. }
  1979. Value *LibCallSimplifier::optimizeFGets(CallInst *CI, IRBuilder<> &B) {
  1980. if (isLocallyOpenedFile(CI->getArgOperand(2), CI, B, TLI))
  1981. return emitFGetSUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
  1982. CI->getArgOperand(2), B, TLI);
  1983. return nullptr;
  1984. }
  1985. Value *LibCallSimplifier::optimizeFRead(CallInst *CI, IRBuilder<> &B) {
  1986. if (isLocallyOpenedFile(CI->getArgOperand(3), CI, B, TLI))
  1987. return emitFReadUnlocked(CI->getArgOperand(0), CI->getArgOperand(1),
  1988. CI->getArgOperand(2), CI->getArgOperand(3), B, DL,
  1989. TLI);
  1990. return nullptr;
  1991. }
  1992. Value *LibCallSimplifier::optimizePuts(CallInst *CI, IRBuilder<> &B) {
  1993. // Check for a constant string.
  1994. StringRef Str;
  1995. if (!getConstantStringInfo(CI->getArgOperand(0), Str))
  1996. return nullptr;
  1997. if (Str.empty() && CI->use_empty()) {
  1998. // puts("") -> putchar('\n')
  1999. Value *Res = emitPutChar(B.getInt32('\n'), B, TLI);
  2000. if (CI->use_empty() || !Res)
  2001. return Res;
  2002. return B.CreateIntCast(Res, CI->getType(), true);
  2003. }
  2004. return nullptr;
  2005. }
  2006. bool LibCallSimplifier::hasFloatVersion(StringRef FuncName) {
  2007. LibFunc Func;
  2008. SmallString<20> FloatFuncName = FuncName;
  2009. FloatFuncName += 'f';
  2010. if (TLI->getLibFunc(FloatFuncName, Func))
  2011. return TLI->has(Func);
  2012. return false;
  2013. }
  2014. Value *LibCallSimplifier::optimizeStringMemoryLibCall(CallInst *CI,
  2015. IRBuilder<> &Builder) {
  2016. LibFunc Func;
  2017. Function *Callee = CI->getCalledFunction();
  2018. // Check for string/memory library functions.
  2019. if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
  2020. // Make sure we never change the calling convention.
  2021. assert((ignoreCallingConv(Func) ||
  2022. isCallingConvCCompatible(CI)) &&
  2023. "Optimizing string/memory libcall would change the calling convention");
  2024. switch (Func) {
  2025. case LibFunc_strcat:
  2026. return optimizeStrCat(CI, Builder);
  2027. case LibFunc_strncat:
  2028. return optimizeStrNCat(CI, Builder);
  2029. case LibFunc_strchr:
  2030. return optimizeStrChr(CI, Builder);
  2031. case LibFunc_strrchr:
  2032. return optimizeStrRChr(CI, Builder);
  2033. case LibFunc_strcmp:
  2034. return optimizeStrCmp(CI, Builder);
  2035. case LibFunc_strncmp:
  2036. return optimizeStrNCmp(CI, Builder);
  2037. case LibFunc_strcpy:
  2038. return optimizeStrCpy(CI, Builder);
  2039. case LibFunc_stpcpy:
  2040. return optimizeStpCpy(CI, Builder);
  2041. case LibFunc_strncpy:
  2042. return optimizeStrNCpy(CI, Builder);
  2043. case LibFunc_strlen:
  2044. return optimizeStrLen(CI, Builder);
  2045. case LibFunc_strpbrk:
  2046. return optimizeStrPBrk(CI, Builder);
  2047. case LibFunc_strtol:
  2048. case LibFunc_strtod:
  2049. case LibFunc_strtof:
  2050. case LibFunc_strtoul:
  2051. case LibFunc_strtoll:
  2052. case LibFunc_strtold:
  2053. case LibFunc_strtoull:
  2054. return optimizeStrTo(CI, Builder);
  2055. case LibFunc_strspn:
  2056. return optimizeStrSpn(CI, Builder);
  2057. case LibFunc_strcspn:
  2058. return optimizeStrCSpn(CI, Builder);
  2059. case LibFunc_strstr:
  2060. return optimizeStrStr(CI, Builder);
  2061. case LibFunc_memchr:
  2062. return optimizeMemChr(CI, Builder);
  2063. case LibFunc_memcmp:
  2064. return optimizeMemCmp(CI, Builder);
  2065. case LibFunc_memcpy:
  2066. return optimizeMemCpy(CI, Builder);
  2067. case LibFunc_memmove:
  2068. return optimizeMemMove(CI, Builder);
  2069. case LibFunc_memset:
  2070. return optimizeMemSet(CI, Builder);
  2071. case LibFunc_realloc:
  2072. return optimizeRealloc(CI, Builder);
  2073. case LibFunc_wcslen:
  2074. return optimizeWcslen(CI, Builder);
  2075. default:
  2076. break;
  2077. }
  2078. }
  2079. return nullptr;
  2080. }
  2081. Value *LibCallSimplifier::optimizeFloatingPointLibCall(CallInst *CI,
  2082. LibFunc Func,
  2083. IRBuilder<> &Builder) {
  2084. // Don't optimize calls that require strict floating point semantics.
  2085. if (CI->isStrictFP())
  2086. return nullptr;
  2087. if (Value *V = optimizeTrigReflections(CI, Func, Builder))
  2088. return V;
  2089. switch (Func) {
  2090. case LibFunc_sinpif:
  2091. case LibFunc_sinpi:
  2092. case LibFunc_cospif:
  2093. case LibFunc_cospi:
  2094. return optimizeSinCosPi(CI, Builder);
  2095. case LibFunc_powf:
  2096. case LibFunc_pow:
  2097. case LibFunc_powl:
  2098. return optimizePow(CI, Builder);
  2099. case LibFunc_exp2l:
  2100. case LibFunc_exp2:
  2101. case LibFunc_exp2f:
  2102. return optimizeExp2(CI, Builder);
  2103. case LibFunc_fabsf:
  2104. case LibFunc_fabs:
  2105. case LibFunc_fabsl:
  2106. return replaceUnaryCall(CI, Builder, Intrinsic::fabs);
  2107. case LibFunc_sqrtf:
  2108. case LibFunc_sqrt:
  2109. case LibFunc_sqrtl:
  2110. return optimizeSqrt(CI, Builder);
  2111. case LibFunc_log:
  2112. case LibFunc_log10:
  2113. case LibFunc_log1p:
  2114. case LibFunc_log2:
  2115. case LibFunc_logb:
  2116. return optimizeLog(CI, Builder);
  2117. case LibFunc_tan:
  2118. case LibFunc_tanf:
  2119. case LibFunc_tanl:
  2120. return optimizeTan(CI, Builder);
  2121. case LibFunc_ceil:
  2122. return replaceUnaryCall(CI, Builder, Intrinsic::ceil);
  2123. case LibFunc_floor:
  2124. return replaceUnaryCall(CI, Builder, Intrinsic::floor);
  2125. case LibFunc_round:
  2126. return replaceUnaryCall(CI, Builder, Intrinsic::round);
  2127. case LibFunc_nearbyint:
  2128. return replaceUnaryCall(CI, Builder, Intrinsic::nearbyint);
  2129. case LibFunc_rint:
  2130. return replaceUnaryCall(CI, Builder, Intrinsic::rint);
  2131. case LibFunc_trunc:
  2132. return replaceUnaryCall(CI, Builder, Intrinsic::trunc);
  2133. case LibFunc_acos:
  2134. case LibFunc_acosh:
  2135. case LibFunc_asin:
  2136. case LibFunc_asinh:
  2137. case LibFunc_atan:
  2138. case LibFunc_atanh:
  2139. case LibFunc_cbrt:
  2140. case LibFunc_cosh:
  2141. case LibFunc_exp:
  2142. case LibFunc_exp10:
  2143. case LibFunc_expm1:
  2144. case LibFunc_cos:
  2145. case LibFunc_sin:
  2146. case LibFunc_sinh:
  2147. case LibFunc_tanh:
  2148. if (UnsafeFPShrink && hasFloatVersion(CI->getCalledFunction()->getName()))
  2149. return optimizeUnaryDoubleFP(CI, Builder, true);
  2150. return nullptr;
  2151. case LibFunc_copysign:
  2152. if (hasFloatVersion(CI->getCalledFunction()->getName()))
  2153. return optimizeBinaryDoubleFP(CI, Builder);
  2154. return nullptr;
  2155. case LibFunc_fminf:
  2156. case LibFunc_fmin:
  2157. case LibFunc_fminl:
  2158. case LibFunc_fmaxf:
  2159. case LibFunc_fmax:
  2160. case LibFunc_fmaxl:
  2161. return optimizeFMinFMax(CI, Builder);
  2162. case LibFunc_cabs:
  2163. case LibFunc_cabsf:
  2164. case LibFunc_cabsl:
  2165. return optimizeCAbs(CI, Builder);
  2166. default:
  2167. return nullptr;
  2168. }
  2169. }
  2170. Value *LibCallSimplifier::optimizeCall(CallInst *CI) {
  2171. // TODO: Split out the code below that operates on FP calls so that
  2172. // we can all non-FP calls with the StrictFP attribute to be
  2173. // optimized.
  2174. if (CI->isNoBuiltin())
  2175. return nullptr;
  2176. LibFunc Func;
  2177. Function *Callee = CI->getCalledFunction();
  2178. SmallVector<OperandBundleDef, 2> OpBundles;
  2179. CI->getOperandBundlesAsDefs(OpBundles);
  2180. IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
  2181. bool isCallingConvC = isCallingConvCCompatible(CI);
  2182. // Command-line parameter overrides instruction attribute.
  2183. // This can't be moved to optimizeFloatingPointLibCall() because it may be
  2184. // used by the intrinsic optimizations.
  2185. if (EnableUnsafeFPShrink.getNumOccurrences() > 0)
  2186. UnsafeFPShrink = EnableUnsafeFPShrink;
  2187. else if (isa<FPMathOperator>(CI) && CI->isFast())
  2188. UnsafeFPShrink = true;
  2189. // First, check for intrinsics.
  2190. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
  2191. if (!isCallingConvC)
  2192. return nullptr;
  2193. // The FP intrinsics have corresponding constrained versions so we don't
  2194. // need to check for the StrictFP attribute here.
  2195. switch (II->getIntrinsicID()) {
  2196. case Intrinsic::pow:
  2197. return optimizePow(CI, Builder);
  2198. case Intrinsic::exp2:
  2199. return optimizeExp2(CI, Builder);
  2200. case Intrinsic::log:
  2201. return optimizeLog(CI, Builder);
  2202. case Intrinsic::sqrt:
  2203. return optimizeSqrt(CI, Builder);
  2204. // TODO: Use foldMallocMemset() with memset intrinsic.
  2205. default:
  2206. return nullptr;
  2207. }
  2208. }
  2209. // Also try to simplify calls to fortified library functions.
  2210. if (Value *SimplifiedFortifiedCI = FortifiedSimplifier.optimizeCall(CI)) {
  2211. // Try to further simplify the result.
  2212. CallInst *SimplifiedCI = dyn_cast<CallInst>(SimplifiedFortifiedCI);
  2213. if (SimplifiedCI && SimplifiedCI->getCalledFunction()) {
  2214. // Use an IR Builder from SimplifiedCI if available instead of CI
  2215. // to guarantee we reach all uses we might replace later on.
  2216. IRBuilder<> TmpBuilder(SimplifiedCI);
  2217. if (Value *V = optimizeStringMemoryLibCall(SimplifiedCI, TmpBuilder)) {
  2218. // If we were able to further simplify, remove the now redundant call.
  2219. SimplifiedCI->replaceAllUsesWith(V);
  2220. eraseFromParent(SimplifiedCI);
  2221. return V;
  2222. }
  2223. }
  2224. return SimplifiedFortifiedCI;
  2225. }
  2226. // Then check for known library functions.
  2227. if (TLI->getLibFunc(*Callee, Func) && TLI->has(Func)) {
  2228. // We never change the calling convention.
  2229. if (!ignoreCallingConv(Func) && !isCallingConvC)
  2230. return nullptr;
  2231. if (Value *V = optimizeStringMemoryLibCall(CI, Builder))
  2232. return V;
  2233. if (Value *V = optimizeFloatingPointLibCall(CI, Func, Builder))
  2234. return V;
  2235. switch (Func) {
  2236. case LibFunc_ffs:
  2237. case LibFunc_ffsl:
  2238. case LibFunc_ffsll:
  2239. return optimizeFFS(CI, Builder);
  2240. case LibFunc_fls:
  2241. case LibFunc_flsl:
  2242. case LibFunc_flsll:
  2243. return optimizeFls(CI, Builder);
  2244. case LibFunc_abs:
  2245. case LibFunc_labs:
  2246. case LibFunc_llabs:
  2247. return optimizeAbs(CI, Builder);
  2248. case LibFunc_isdigit:
  2249. return optimizeIsDigit(CI, Builder);
  2250. case LibFunc_isascii:
  2251. return optimizeIsAscii(CI, Builder);
  2252. case LibFunc_toascii:
  2253. return optimizeToAscii(CI, Builder);
  2254. case LibFunc_atoi:
  2255. case LibFunc_atol:
  2256. case LibFunc_atoll:
  2257. return optimizeAtoi(CI, Builder);
  2258. case LibFunc_strtol:
  2259. case LibFunc_strtoll:
  2260. return optimizeStrtol(CI, Builder);
  2261. case LibFunc_printf:
  2262. return optimizePrintF(CI, Builder);
  2263. case LibFunc_sprintf:
  2264. return optimizeSPrintF(CI, Builder);
  2265. case LibFunc_snprintf:
  2266. return optimizeSnPrintF(CI, Builder);
  2267. case LibFunc_fprintf:
  2268. return optimizeFPrintF(CI, Builder);
  2269. case LibFunc_fwrite:
  2270. return optimizeFWrite(CI, Builder);
  2271. case LibFunc_fread:
  2272. return optimizeFRead(CI, Builder);
  2273. case LibFunc_fputs:
  2274. return optimizeFPuts(CI, Builder);
  2275. case LibFunc_fgets:
  2276. return optimizeFGets(CI, Builder);
  2277. case LibFunc_fputc:
  2278. return optimizeFPutc(CI, Builder);
  2279. case LibFunc_fgetc:
  2280. return optimizeFGetc(CI, Builder);
  2281. case LibFunc_puts:
  2282. return optimizePuts(CI, Builder);
  2283. case LibFunc_perror:
  2284. return optimizeErrorReporting(CI, Builder);
  2285. case LibFunc_vfprintf:
  2286. case LibFunc_fiprintf:
  2287. return optimizeErrorReporting(CI, Builder, 0);
  2288. default:
  2289. return nullptr;
  2290. }
  2291. }
  2292. return nullptr;
  2293. }
  2294. LibCallSimplifier::LibCallSimplifier(
  2295. const DataLayout &DL, const TargetLibraryInfo *TLI,
  2296. OptimizationRemarkEmitter &ORE,
  2297. function_ref<void(Instruction *, Value *)> Replacer,
  2298. function_ref<void(Instruction *)> Eraser)
  2299. : FortifiedSimplifier(TLI), DL(DL), TLI(TLI), ORE(ORE),
  2300. UnsafeFPShrink(false), Replacer(Replacer), Eraser(Eraser) {}
  2301. void LibCallSimplifier::replaceAllUsesWith(Instruction *I, Value *With) {
  2302. // Indirect through the replacer used in this instance.
  2303. Replacer(I, With);
  2304. }
  2305. void LibCallSimplifier::eraseFromParent(Instruction *I) {
  2306. Eraser(I);
  2307. }
  2308. // TODO:
  2309. // Additional cases that we need to add to this file:
  2310. //
  2311. // cbrt:
  2312. // * cbrt(expN(X)) -> expN(x/3)
  2313. // * cbrt(sqrt(x)) -> pow(x,1/6)
  2314. // * cbrt(cbrt(x)) -> pow(x,1/9)
  2315. //
  2316. // exp, expf, expl:
  2317. // * exp(log(x)) -> x
  2318. //
  2319. // log, logf, logl:
  2320. // * log(exp(x)) -> x
  2321. // * log(exp(y)) -> y*log(e)
  2322. // * log(exp10(y)) -> y*log(10)
  2323. // * log(sqrt(x)) -> 0.5*log(x)
  2324. //
  2325. // pow, powf, powl:
  2326. // * pow(sqrt(x),y) -> pow(x,y*0.5)
  2327. // * pow(pow(x,y),z)-> pow(x,y*z)
  2328. //
  2329. // signbit:
  2330. // * signbit(cnst) -> cnst'
  2331. // * signbit(nncst) -> 0 (if pstv is a non-negative constant)
  2332. //
  2333. // sqrt, sqrtf, sqrtl:
  2334. // * sqrt(expN(x)) -> expN(x*0.5)
  2335. // * sqrt(Nroot(x)) -> pow(x,1/(2*N))
  2336. // * sqrt(pow(x,y)) -> pow(|x|,y*0.5)
  2337. //
  2338. //===----------------------------------------------------------------------===//
  2339. // Fortified Library Call Optimizations
  2340. //===----------------------------------------------------------------------===//
  2341. bool FortifiedLibCallSimplifier::isFortifiedCallFoldable(CallInst *CI,
  2342. unsigned ObjSizeOp,
  2343. unsigned SizeOp,
  2344. bool isString) {
  2345. if (CI->getArgOperand(ObjSizeOp) == CI->getArgOperand(SizeOp))
  2346. return true;
  2347. if (ConstantInt *ObjSizeCI =
  2348. dyn_cast<ConstantInt>(CI->getArgOperand(ObjSizeOp))) {
  2349. if (ObjSizeCI->isMinusOne())
  2350. return true;
  2351. // If the object size wasn't -1 (unknown), bail out if we were asked to.
  2352. if (OnlyLowerUnknownSize)
  2353. return false;
  2354. if (isString) {
  2355. uint64_t Len = GetStringLength(CI->getArgOperand(SizeOp));
  2356. // If the length is 0 we don't know how long it is and so we can't
  2357. // remove the check.
  2358. if (Len == 0)
  2359. return false;
  2360. return ObjSizeCI->getZExtValue() >= Len;
  2361. }
  2362. if (ConstantInt *SizeCI = dyn_cast<ConstantInt>(CI->getArgOperand(SizeOp)))
  2363. return ObjSizeCI->getZExtValue() >= SizeCI->getZExtValue();
  2364. }
  2365. return false;
  2366. }
  2367. Value *FortifiedLibCallSimplifier::optimizeMemCpyChk(CallInst *CI,
  2368. IRBuilder<> &B) {
  2369. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  2370. B.CreateMemCpy(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
  2371. CI->getArgOperand(2));
  2372. return CI->getArgOperand(0);
  2373. }
  2374. return nullptr;
  2375. }
  2376. Value *FortifiedLibCallSimplifier::optimizeMemMoveChk(CallInst *CI,
  2377. IRBuilder<> &B) {
  2378. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  2379. B.CreateMemMove(CI->getArgOperand(0), 1, CI->getArgOperand(1), 1,
  2380. CI->getArgOperand(2));
  2381. return CI->getArgOperand(0);
  2382. }
  2383. return nullptr;
  2384. }
  2385. Value *FortifiedLibCallSimplifier::optimizeMemSetChk(CallInst *CI,
  2386. IRBuilder<> &B) {
  2387. // TODO: Try foldMallocMemset() here.
  2388. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  2389. Value *Val = B.CreateIntCast(CI->getArgOperand(1), B.getInt8Ty(), false);
  2390. B.CreateMemSet(CI->getArgOperand(0), Val, CI->getArgOperand(2), 1);
  2391. return CI->getArgOperand(0);
  2392. }
  2393. return nullptr;
  2394. }
  2395. Value *FortifiedLibCallSimplifier::optimizeStrpCpyChk(CallInst *CI,
  2396. IRBuilder<> &B,
  2397. LibFunc Func) {
  2398. Function *Callee = CI->getCalledFunction();
  2399. StringRef Name = Callee->getName();
  2400. const DataLayout &DL = CI->getModule()->getDataLayout();
  2401. Value *Dst = CI->getArgOperand(0), *Src = CI->getArgOperand(1),
  2402. *ObjSize = CI->getArgOperand(2);
  2403. // __stpcpy_chk(x,x,...) -> x+strlen(x)
  2404. if (Func == LibFunc_stpcpy_chk && !OnlyLowerUnknownSize && Dst == Src) {
  2405. Value *StrLen = emitStrLen(Src, B, DL, TLI);
  2406. return StrLen ? B.CreateInBoundsGEP(B.getInt8Ty(), Dst, StrLen) : nullptr;
  2407. }
  2408. // If a) we don't have any length information, or b) we know this will
  2409. // fit then just lower to a plain st[rp]cpy. Otherwise we'll keep our
  2410. // st[rp]cpy_chk call which may fail at runtime if the size is too long.
  2411. // TODO: It might be nice to get a maximum length out of the possible
  2412. // string lengths for varying.
  2413. if (isFortifiedCallFoldable(CI, 2, 1, true))
  2414. return emitStrCpy(Dst, Src, B, TLI, Name.substr(2, 6));
  2415. if (OnlyLowerUnknownSize)
  2416. return nullptr;
  2417. // Maybe we can stil fold __st[rp]cpy_chk to __memcpy_chk.
  2418. uint64_t Len = GetStringLength(Src);
  2419. if (Len == 0)
  2420. return nullptr;
  2421. Type *SizeTTy = DL.getIntPtrType(CI->getContext());
  2422. Value *LenV = ConstantInt::get(SizeTTy, Len);
  2423. Value *Ret = emitMemCpyChk(Dst, Src, LenV, ObjSize, B, DL, TLI);
  2424. // If the function was an __stpcpy_chk, and we were able to fold it into
  2425. // a __memcpy_chk, we still need to return the correct end pointer.
  2426. if (Ret && Func == LibFunc_stpcpy_chk)
  2427. return B.CreateGEP(B.getInt8Ty(), Dst, ConstantInt::get(SizeTTy, Len - 1));
  2428. return Ret;
  2429. }
  2430. Value *FortifiedLibCallSimplifier::optimizeStrpNCpyChk(CallInst *CI,
  2431. IRBuilder<> &B,
  2432. LibFunc Func) {
  2433. Function *Callee = CI->getCalledFunction();
  2434. StringRef Name = Callee->getName();
  2435. if (isFortifiedCallFoldable(CI, 3, 2, false)) {
  2436. Value *Ret = emitStrNCpy(CI->getArgOperand(0), CI->getArgOperand(1),
  2437. CI->getArgOperand(2), B, TLI, Name.substr(2, 7));
  2438. return Ret;
  2439. }
  2440. return nullptr;
  2441. }
  2442. Value *FortifiedLibCallSimplifier::optimizeCall(CallInst *CI) {
  2443. // FIXME: We shouldn't be changing "nobuiltin" or TLI unavailable calls here.
  2444. // Some clang users checked for _chk libcall availability using:
  2445. // __has_builtin(__builtin___memcpy_chk)
  2446. // When compiling with -fno-builtin, this is always true.
  2447. // When passing -ffreestanding/-mkernel, which both imply -fno-builtin, we
  2448. // end up with fortified libcalls, which isn't acceptable in a freestanding
  2449. // environment which only provides their non-fortified counterparts.
  2450. //
  2451. // Until we change clang and/or teach external users to check for availability
  2452. // differently, disregard the "nobuiltin" attribute and TLI::has.
  2453. //
  2454. // PR23093.
  2455. LibFunc Func;
  2456. Function *Callee = CI->getCalledFunction();
  2457. SmallVector<OperandBundleDef, 2> OpBundles;
  2458. CI->getOperandBundlesAsDefs(OpBundles);
  2459. IRBuilder<> Builder(CI, /*FPMathTag=*/nullptr, OpBundles);
  2460. bool isCallingConvC = isCallingConvCCompatible(CI);
  2461. // First, check that this is a known library functions and that the prototype
  2462. // is correct.
  2463. if (!TLI->getLibFunc(*Callee, Func))
  2464. return nullptr;
  2465. // We never change the calling convention.
  2466. if (!ignoreCallingConv(Func) && !isCallingConvC)
  2467. return nullptr;
  2468. switch (Func) {
  2469. case LibFunc_memcpy_chk:
  2470. return optimizeMemCpyChk(CI, Builder);
  2471. case LibFunc_memmove_chk:
  2472. return optimizeMemMoveChk(CI, Builder);
  2473. case LibFunc_memset_chk:
  2474. return optimizeMemSetChk(CI, Builder);
  2475. case LibFunc_stpcpy_chk:
  2476. case LibFunc_strcpy_chk:
  2477. return optimizeStrpCpyChk(CI, Builder, Func);
  2478. case LibFunc_stpncpy_chk:
  2479. case LibFunc_strncpy_chk:
  2480. return optimizeStrpNCpyChk(CI, Builder, Func);
  2481. default:
  2482. break;
  2483. }
  2484. return nullptr;
  2485. }
  2486. FortifiedLibCallSimplifier::FortifiedLibCallSimplifier(
  2487. const TargetLibraryInfo *TLI, bool OnlyLowerUnknownSize)
  2488. : TLI(TLI), OnlyLowerUnknownSize(OnlyLowerUnknownSize) {}