2
0

ConstantFolding.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. //===-- ConstantFolding.cpp - Fold instructions into constants ------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines routines for folding instructions into constants.
  11. //
  12. // Also, to supplement the basic IR ConstantExpr simplifications,
  13. // this file defines some additional folding routines that can make use of
  14. // DataLayout information. These functions cannot go in IR due to library
  15. // dependency issues.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Analysis/ConstantFolding.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/StringMap.h"
  22. #include "llvm/Analysis/TargetLibraryInfo.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/Config/config.h"
  25. #include "llvm/IR/Constants.h"
  26. #include "llvm/IR/DataLayout.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Function.h"
  29. #include "llvm/IR/GetElementPtrTypeIterator.h"
  30. #include "llvm/IR/GlobalVariable.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/Operator.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/MathExtras.h"
  36. #include <cerrno>
  37. #include <cmath>
  38. #include "llvm/Analysis/DxilConstantFolding.h" // HLSL Change
  39. #ifdef HAVE_FENV_H
  40. #include <fenv.h>
  41. #endif
  42. using namespace llvm;
  43. //===----------------------------------------------------------------------===//
  44. // Constant Folding internal helper functions
  45. //===----------------------------------------------------------------------===//
  46. /// Constant fold bitcast, symbolically evaluating it with DataLayout.
  47. /// This always returns a non-null constant, but it may be a
  48. /// ConstantExpr if unfoldable.
  49. static Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
  50. // Catch the obvious splat cases.
  51. if (C->isNullValue() && !DestTy->isX86_MMXTy())
  52. return Constant::getNullValue(DestTy);
  53. if (C->isAllOnesValue() && !DestTy->isX86_MMXTy() &&
  54. !DestTy->isPtrOrPtrVectorTy()) // Don't get ones for ptr types!
  55. return Constant::getAllOnesValue(DestTy);
  56. // Handle a vector->integer cast.
  57. if (IntegerType *IT = dyn_cast<IntegerType>(DestTy)) {
  58. VectorType *VTy = dyn_cast<VectorType>(C->getType());
  59. if (!VTy)
  60. return ConstantExpr::getBitCast(C, DestTy);
  61. unsigned NumSrcElts = VTy->getNumElements();
  62. Type *SrcEltTy = VTy->getElementType();
  63. // If the vector is a vector of floating point, convert it to vector of int
  64. // to simplify things.
  65. if (SrcEltTy->isFloatingPointTy()) {
  66. unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
  67. Type *SrcIVTy =
  68. VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElts);
  69. // Ask IR to do the conversion now that #elts line up.
  70. C = ConstantExpr::getBitCast(C, SrcIVTy);
  71. }
  72. ConstantDataVector *CDV = dyn_cast<ConstantDataVector>(C);
  73. if (!CDV)
  74. return ConstantExpr::getBitCast(C, DestTy);
  75. // Now that we know that the input value is a vector of integers, just shift
  76. // and insert them into our result.
  77. unsigned BitShift = DL.getTypeAllocSizeInBits(SrcEltTy);
  78. APInt Result(IT->getBitWidth(), 0);
  79. for (unsigned i = 0; i != NumSrcElts; ++i) {
  80. Result <<= BitShift;
  81. if (DL.isLittleEndian())
  82. Result |= CDV->getElementAsInteger(NumSrcElts-i-1);
  83. else
  84. Result |= CDV->getElementAsInteger(i);
  85. }
  86. return ConstantInt::get(IT, Result);
  87. }
  88. // The code below only handles casts to vectors currently.
  89. VectorType *DestVTy = dyn_cast<VectorType>(DestTy);
  90. if (!DestVTy)
  91. return ConstantExpr::getBitCast(C, DestTy);
  92. // If this is a scalar -> vector cast, convert the input into a <1 x scalar>
  93. // vector so the code below can handle it uniformly.
  94. if (isa<ConstantFP>(C) || isa<ConstantInt>(C)) {
  95. Constant *Ops = C; // don't take the address of C!
  96. return FoldBitCast(ConstantVector::get(Ops), DestTy, DL);
  97. }
  98. // If this is a bitcast from constant vector -> vector, fold it.
  99. if (!isa<ConstantDataVector>(C) && !isa<ConstantVector>(C))
  100. return ConstantExpr::getBitCast(C, DestTy);
  101. // If the element types match, IR can fold it.
  102. unsigned NumDstElt = DestVTy->getNumElements();
  103. unsigned NumSrcElt = C->getType()->getVectorNumElements();
  104. if (NumDstElt == NumSrcElt)
  105. return ConstantExpr::getBitCast(C, DestTy);
  106. Type *SrcEltTy = C->getType()->getVectorElementType();
  107. Type *DstEltTy = DestVTy->getElementType();
  108. // Otherwise, we're changing the number of elements in a vector, which
  109. // requires endianness information to do the right thing. For example,
  110. // bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
  111. // folds to (little endian):
  112. // <4 x i32> <i32 0, i32 0, i32 1, i32 0>
  113. // and to (big endian):
  114. // <4 x i32> <i32 0, i32 0, i32 0, i32 1>
  115. // First thing is first. We only want to think about integer here, so if
  116. // we have something in FP form, recast it as integer.
  117. if (DstEltTy->isFloatingPointTy()) {
  118. // Fold to an vector of integers with same size as our FP type.
  119. unsigned FPWidth = DstEltTy->getPrimitiveSizeInBits();
  120. Type *DestIVTy =
  121. VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumDstElt);
  122. // Recursively handle this integer conversion, if possible.
  123. C = FoldBitCast(C, DestIVTy, DL);
  124. // Finally, IR can handle this now that #elts line up.
  125. return ConstantExpr::getBitCast(C, DestTy);
  126. }
  127. // Okay, we know the destination is integer, if the input is FP, convert
  128. // it to integer first.
  129. if (SrcEltTy->isFloatingPointTy()) {
  130. unsigned FPWidth = SrcEltTy->getPrimitiveSizeInBits();
  131. Type *SrcIVTy =
  132. VectorType::get(IntegerType::get(C->getContext(), FPWidth), NumSrcElt);
  133. // Ask IR to do the conversion now that #elts line up.
  134. C = ConstantExpr::getBitCast(C, SrcIVTy);
  135. // If IR wasn't able to fold it, bail out.
  136. if (!isa<ConstantVector>(C) && // FIXME: Remove ConstantVector.
  137. !isa<ConstantDataVector>(C))
  138. return C;
  139. }
  140. // Now we know that the input and output vectors are both integer vectors
  141. // of the same size, and that their #elements is not the same. Do the
  142. // conversion here, which depends on whether the input or output has
  143. // more elements.
  144. bool isLittleEndian = DL.isLittleEndian();
  145. SmallVector<Constant*, 32> Result;
  146. if (NumDstElt < NumSrcElt) {
  147. // Handle: bitcast (<4 x i32> <i32 0, i32 1, i32 2, i32 3> to <2 x i64>)
  148. Constant *Zero = Constant::getNullValue(DstEltTy);
  149. unsigned Ratio = NumSrcElt/NumDstElt;
  150. unsigned SrcBitSize = SrcEltTy->getPrimitiveSizeInBits();
  151. unsigned SrcElt = 0;
  152. for (unsigned i = 0; i != NumDstElt; ++i) {
  153. // Build each element of the result.
  154. Constant *Elt = Zero;
  155. unsigned ShiftAmt = isLittleEndian ? 0 : SrcBitSize*(Ratio-1);
  156. for (unsigned j = 0; j != Ratio; ++j) {
  157. Constant *Src =dyn_cast<ConstantInt>(C->getAggregateElement(SrcElt++));
  158. if (!Src) // Reject constantexpr elements.
  159. return ConstantExpr::getBitCast(C, DestTy);
  160. // Zero extend the element to the right size.
  161. Src = ConstantExpr::getZExt(Src, Elt->getType());
  162. // Shift it to the right place, depending on endianness.
  163. Src = ConstantExpr::getShl(Src,
  164. ConstantInt::get(Src->getType(), ShiftAmt));
  165. ShiftAmt += isLittleEndian ? SrcBitSize : -SrcBitSize;
  166. // Mix it in.
  167. Elt = ConstantExpr::getOr(Elt, Src);
  168. }
  169. Result.push_back(Elt);
  170. }
  171. return ConstantVector::get(Result);
  172. }
  173. // Handle: bitcast (<2 x i64> <i64 0, i64 1> to <4 x i32>)
  174. unsigned Ratio = NumDstElt/NumSrcElt;
  175. unsigned DstBitSize = DL.getTypeSizeInBits(DstEltTy);
  176. // Loop over each source value, expanding into multiple results.
  177. for (unsigned i = 0; i != NumSrcElt; ++i) {
  178. Constant *Src = dyn_cast<ConstantInt>(C->getAggregateElement(i));
  179. if (!Src) // Reject constantexpr elements.
  180. return ConstantExpr::getBitCast(C, DestTy);
  181. unsigned ShiftAmt = isLittleEndian ? 0 : DstBitSize*(Ratio-1);
  182. for (unsigned j = 0; j != Ratio; ++j) {
  183. // Shift the piece of the value into the right place, depending on
  184. // endianness.
  185. Constant *Elt = ConstantExpr::getLShr(Src,
  186. ConstantInt::get(Src->getType(), ShiftAmt));
  187. ShiftAmt += isLittleEndian ? DstBitSize : -DstBitSize;
  188. // Truncate the element to an integer with the same pointer size and
  189. // convert the element back to a pointer using a inttoptr.
  190. if (DstEltTy->isPointerTy()) {
  191. IntegerType *DstIntTy = Type::getIntNTy(C->getContext(), DstBitSize);
  192. Constant *CE = ConstantExpr::getTrunc(Elt, DstIntTy);
  193. Result.push_back(ConstantExpr::getIntToPtr(CE, DstEltTy));
  194. continue;
  195. }
  196. // Truncate and remember this piece.
  197. Result.push_back(ConstantExpr::getTrunc(Elt, DstEltTy));
  198. }
  199. }
  200. return ConstantVector::get(Result);
  201. }
  202. /// If this constant is a constant offset from a global, return the global and
  203. /// the constant. Because of constantexprs, this function is recursive.
  204. static bool IsConstantOffsetFromGlobal(Constant *C, GlobalValue *&GV,
  205. APInt &Offset, const DataLayout &DL) {
  206. // Trivial case, constant is the global.
  207. if ((GV = dyn_cast<GlobalValue>(C))) {
  208. unsigned BitWidth = DL.getPointerTypeSizeInBits(GV->getType());
  209. Offset = APInt(BitWidth, 0);
  210. return true;
  211. }
  212. // Otherwise, if this isn't a constant expr, bail out.
  213. ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
  214. if (!CE) return false;
  215. // Look through ptr->int and ptr->ptr casts.
  216. if (CE->getOpcode() == Instruction::PtrToInt ||
  217. CE->getOpcode() == Instruction::BitCast ||
  218. CE->getOpcode() == Instruction::AddrSpaceCast)
  219. return IsConstantOffsetFromGlobal(CE->getOperand(0), GV, Offset, DL);
  220. // i32* getelementptr ([5 x i32]* @a, i32 0, i32 5)
  221. GEPOperator *GEP = dyn_cast<GEPOperator>(CE);
  222. if (!GEP)
  223. return false;
  224. unsigned BitWidth = DL.getPointerTypeSizeInBits(GEP->getType());
  225. APInt TmpOffset(BitWidth, 0);
  226. // If the base isn't a global+constant, we aren't either.
  227. if (!IsConstantOffsetFromGlobal(CE->getOperand(0), GV, TmpOffset, DL))
  228. return false;
  229. // Otherwise, add any offset that our operands provide.
  230. if (!GEP->accumulateConstantOffset(DL, TmpOffset))
  231. return false;
  232. Offset = TmpOffset;
  233. return true;
  234. }
  235. /// Recursive helper to read bits out of global. C is the constant being copied
  236. /// out of. ByteOffset is an offset into C. CurPtr is the pointer to copy
  237. /// results into and BytesLeft is the number of bytes left in
  238. /// the CurPtr buffer. DL is the DataLayout.
  239. static bool ReadDataFromGlobal(Constant *C, uint64_t ByteOffset,
  240. unsigned char *CurPtr, unsigned BytesLeft,
  241. const DataLayout &DL) {
  242. assert(ByteOffset <= DL.getTypeAllocSize(C->getType()) &&
  243. "Out of range access");
  244. // If this element is zero or undefined, we can just return since *CurPtr is
  245. // zero initialized.
  246. if (isa<ConstantAggregateZero>(C) || isa<UndefValue>(C))
  247. return true;
  248. if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
  249. if (CI->getBitWidth() > 64 ||
  250. (CI->getBitWidth() & 7) != 0)
  251. return false;
  252. uint64_t Val = CI->getZExtValue();
  253. unsigned IntBytes = unsigned(CI->getBitWidth()/8);
  254. for (unsigned i = 0; i != BytesLeft && ByteOffset != IntBytes; ++i) {
  255. int n = ByteOffset;
  256. if (!DL.isLittleEndian())
  257. n = IntBytes - n - 1;
  258. CurPtr[i] = (unsigned char)(Val >> (n * 8));
  259. ++ByteOffset;
  260. }
  261. return true;
  262. }
  263. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  264. if (CFP->getType()->isDoubleTy()) {
  265. C = FoldBitCast(C, Type::getInt64Ty(C->getContext()), DL);
  266. return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
  267. }
  268. if (CFP->getType()->isFloatTy()){
  269. C = FoldBitCast(C, Type::getInt32Ty(C->getContext()), DL);
  270. return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
  271. }
  272. if (CFP->getType()->isHalfTy()){
  273. C = FoldBitCast(C, Type::getInt16Ty(C->getContext()), DL);
  274. return ReadDataFromGlobal(C, ByteOffset, CurPtr, BytesLeft, DL);
  275. }
  276. return false;
  277. }
  278. if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
  279. const StructLayout *SL = DL.getStructLayout(CS->getType());
  280. unsigned Index = SL->getElementContainingOffset(ByteOffset);
  281. uint64_t CurEltOffset = SL->getElementOffset(Index);
  282. ByteOffset -= CurEltOffset;
  283. while (1) {
  284. // If the element access is to the element itself and not to tail padding,
  285. // read the bytes from the element.
  286. uint64_t EltSize = DL.getTypeAllocSize(CS->getOperand(Index)->getType());
  287. if (ByteOffset < EltSize &&
  288. !ReadDataFromGlobal(CS->getOperand(Index), ByteOffset, CurPtr,
  289. BytesLeft, DL))
  290. return false;
  291. ++Index;
  292. // Check to see if we read from the last struct element, if so we're done.
  293. if (Index == CS->getType()->getNumElements())
  294. return true;
  295. // If we read all of the bytes we needed from this element we're done.
  296. uint64_t NextEltOffset = SL->getElementOffset(Index);
  297. if (BytesLeft <= NextEltOffset - CurEltOffset - ByteOffset)
  298. return true;
  299. // Move to the next element of the struct.
  300. CurPtr += NextEltOffset - CurEltOffset - ByteOffset;
  301. BytesLeft -= NextEltOffset - CurEltOffset - ByteOffset;
  302. ByteOffset = 0;
  303. CurEltOffset = NextEltOffset;
  304. }
  305. // not reached.
  306. }
  307. if (isa<ConstantArray>(C) || isa<ConstantVector>(C) ||
  308. isa<ConstantDataSequential>(C)) {
  309. Type *EltTy = C->getType()->getSequentialElementType();
  310. uint64_t EltSize = DL.getTypeAllocSize(EltTy);
  311. uint64_t Index = ByteOffset / EltSize;
  312. uint64_t Offset = ByteOffset - Index * EltSize;
  313. uint64_t NumElts;
  314. if (ArrayType *AT = dyn_cast<ArrayType>(C->getType()))
  315. NumElts = AT->getNumElements();
  316. else
  317. NumElts = C->getType()->getVectorNumElements();
  318. for (; Index != NumElts; ++Index) {
  319. if (!ReadDataFromGlobal(C->getAggregateElement(Index), Offset, CurPtr,
  320. BytesLeft, DL))
  321. return false;
  322. uint64_t BytesWritten = EltSize - Offset;
  323. assert(BytesWritten <= EltSize && "Not indexing into this element?");
  324. if (BytesWritten >= BytesLeft)
  325. return true;
  326. Offset = 0;
  327. BytesLeft -= BytesWritten;
  328. CurPtr += BytesWritten;
  329. }
  330. return true;
  331. }
  332. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  333. if (CE->getOpcode() == Instruction::IntToPtr &&
  334. CE->getOperand(0)->getType() == DL.getIntPtrType(CE->getType())) {
  335. return ReadDataFromGlobal(CE->getOperand(0), ByteOffset, CurPtr,
  336. BytesLeft, DL);
  337. }
  338. }
  339. // Otherwise, unknown initializer type.
  340. return false;
  341. }
  342. static Constant *FoldReinterpretLoadFromConstPtr(Constant *C,
  343. const DataLayout &DL) {
  344. PointerType *PTy = cast<PointerType>(C->getType());
  345. Type *LoadTy = PTy->getElementType();
  346. IntegerType *IntType = dyn_cast<IntegerType>(LoadTy);
  347. // If this isn't an integer load we can't fold it directly.
  348. if (!IntType) {
  349. unsigned AS = PTy->getAddressSpace();
  350. // If this is a float/double load, we can try folding it as an int32/64 load
  351. // and then bitcast the result. This can be useful for union cases. Note
  352. // that address spaces don't matter here since we're not going to result in
  353. // an actual new load.
  354. Type *MapTy;
  355. if (LoadTy->isHalfTy())
  356. MapTy = Type::getInt16PtrTy(C->getContext(), AS);
  357. else if (LoadTy->isFloatTy())
  358. MapTy = Type::getInt32PtrTy(C->getContext(), AS);
  359. else if (LoadTy->isDoubleTy())
  360. MapTy = Type::getInt64PtrTy(C->getContext(), AS);
  361. else if (LoadTy->isVectorTy()) {
  362. MapTy = PointerType::getIntNPtrTy(C->getContext(),
  363. DL.getTypeAllocSizeInBits(LoadTy), AS);
  364. } else
  365. return nullptr;
  366. C = FoldBitCast(C, MapTy, DL);
  367. if (Constant *Res = FoldReinterpretLoadFromConstPtr(C, DL))
  368. return FoldBitCast(Res, LoadTy, DL);
  369. return nullptr;
  370. }
  371. unsigned BytesLoaded = (IntType->getBitWidth() + 7) / 8;
  372. if (BytesLoaded > 32 || BytesLoaded == 0)
  373. return nullptr;
  374. GlobalValue *GVal;
  375. APInt Offset;
  376. if (!IsConstantOffsetFromGlobal(C, GVal, Offset, DL))
  377. return nullptr;
  378. GlobalVariable *GV = dyn_cast<GlobalVariable>(GVal);
  379. if (!GV || !GV->isConstant() || !GV->hasDefinitiveInitializer() ||
  380. !GV->getInitializer()->getType()->isSized())
  381. return nullptr;
  382. // If we're loading off the beginning of the global, some bytes may be valid,
  383. // but we don't try to handle this.
  384. if (Offset.isNegative())
  385. return nullptr;
  386. // If we're not accessing anything in this constant, the result is undefined.
  387. if (Offset.getZExtValue() >=
  388. DL.getTypeAllocSize(GV->getInitializer()->getType()))
  389. return UndefValue::get(IntType);
  390. unsigned char RawBytes[32] = {0};
  391. if (!ReadDataFromGlobal(GV->getInitializer(), Offset.getZExtValue(), RawBytes,
  392. BytesLoaded, DL))
  393. return nullptr;
  394. APInt ResultVal = APInt(IntType->getBitWidth(), 0);
  395. if (DL.isLittleEndian()) {
  396. ResultVal = RawBytes[BytesLoaded - 1];
  397. for (unsigned i = 1; i != BytesLoaded; ++i) {
  398. ResultVal <<= 8;
  399. ResultVal |= RawBytes[BytesLoaded - 1 - i];
  400. }
  401. } else {
  402. ResultVal = RawBytes[0];
  403. for (unsigned i = 1; i != BytesLoaded; ++i) {
  404. ResultVal <<= 8;
  405. ResultVal |= RawBytes[i];
  406. }
  407. }
  408. return ConstantInt::get(IntType->getContext(), ResultVal);
  409. }
  410. static Constant *ConstantFoldLoadThroughBitcast(ConstantExpr *CE,
  411. const DataLayout &DL) {
  412. auto *DestPtrTy = dyn_cast<PointerType>(CE->getType());
  413. if (!DestPtrTy)
  414. return nullptr;
  415. Type *DestTy = DestPtrTy->getElementType();
  416. Constant *C = ConstantFoldLoadFromConstPtr(CE->getOperand(0), DL);
  417. if (!C)
  418. return nullptr;
  419. do {
  420. Type *SrcTy = C->getType();
  421. // If the type sizes are the same and a cast is legal, just directly
  422. // cast the constant.
  423. if (DL.getTypeSizeInBits(DestTy) == DL.getTypeSizeInBits(SrcTy)) {
  424. Instruction::CastOps Cast = Instruction::BitCast;
  425. // If we are going from a pointer to int or vice versa, we spell the cast
  426. // differently.
  427. if (SrcTy->isIntegerTy() && DestTy->isPointerTy())
  428. Cast = Instruction::IntToPtr;
  429. else if (SrcTy->isPointerTy() && DestTy->isIntegerTy())
  430. Cast = Instruction::PtrToInt;
  431. if (CastInst::castIsValid(Cast, C, DestTy))
  432. return ConstantExpr::getCast(Cast, C, DestTy);
  433. }
  434. // If this isn't an aggregate type, there is nothing we can do to drill down
  435. // and find a bitcastable constant.
  436. if (!SrcTy->isAggregateType())
  437. return nullptr;
  438. // We're simulating a load through a pointer that was bitcast to point to
  439. // a different type, so we can try to walk down through the initial
  440. // elements of an aggregate to see if some part of th e aggregate is
  441. // castable to implement the "load" semantic model.
  442. C = C->getAggregateElement(0u);
  443. } while (C);
  444. return nullptr;
  445. }
  446. /// Return the value that a load from C would produce if it is constant and
  447. /// determinable. If this is not determinable, return null.
  448. Constant *llvm::ConstantFoldLoadFromConstPtr(Constant *C,
  449. const DataLayout &DL) {
  450. // First, try the easy cases:
  451. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
  452. if (GV->isConstant() && GV->hasDefinitiveInitializer())
  453. return GV->getInitializer();
  454. // If the loaded value isn't a constant expr, we can't handle it.
  455. ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
  456. if (!CE)
  457. return nullptr;
  458. if (CE->getOpcode() == Instruction::GetElementPtr) {
  459. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0))) {
  460. if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
  461. if (Constant *V =
  462. ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
  463. return V;
  464. }
  465. }
  466. }
  467. if (CE->getOpcode() == Instruction::BitCast)
  468. if (Constant *LoadedC = ConstantFoldLoadThroughBitcast(CE, DL))
  469. return LoadedC;
  470. // Instead of loading constant c string, use corresponding integer value
  471. // directly if string length is small enough.
  472. StringRef Str;
  473. if (getConstantStringInfo(CE, Str) && !Str.empty()) {
  474. unsigned StrLen = Str.size();
  475. Type *Ty = cast<PointerType>(CE->getType())->getElementType();
  476. unsigned NumBits = Ty->getPrimitiveSizeInBits();
  477. // Replace load with immediate integer if the result is an integer or fp
  478. // value.
  479. if ((NumBits >> 3) == StrLen + 1 && (NumBits & 7) == 0 &&
  480. (isa<IntegerType>(Ty) || Ty->isFloatingPointTy())) {
  481. APInt StrVal(NumBits, 0);
  482. APInt SingleChar(NumBits, 0);
  483. if (DL.isLittleEndian()) {
  484. for (signed i = StrLen-1; i >= 0; i--) {
  485. SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
  486. StrVal = (StrVal << 8) | SingleChar;
  487. }
  488. } else {
  489. for (unsigned i = 0; i < StrLen; i++) {
  490. SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
  491. StrVal = (StrVal << 8) | SingleChar;
  492. }
  493. // Append NULL at the end.
  494. SingleChar = 0;
  495. StrVal = (StrVal << 8) | SingleChar;
  496. }
  497. Constant *Res = ConstantInt::get(CE->getContext(), StrVal);
  498. if (Ty->isFloatingPointTy())
  499. Res = ConstantExpr::getBitCast(Res, Ty);
  500. return Res;
  501. }
  502. }
  503. // If this load comes from anywhere in a constant global, and if the global
  504. // is all undef or zero, we know what it loads.
  505. if (GlobalVariable *GV =
  506. dyn_cast<GlobalVariable>(GetUnderlyingObject(CE, DL))) {
  507. if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
  508. Type *ResTy = cast<PointerType>(C->getType())->getElementType();
  509. if (GV->getInitializer()->isNullValue())
  510. return Constant::getNullValue(ResTy);
  511. if (isa<UndefValue>(GV->getInitializer()))
  512. return UndefValue::get(ResTy);
  513. }
  514. }
  515. // Try hard to fold loads from bitcasted strange and non-type-safe things.
  516. return FoldReinterpretLoadFromConstPtr(CE, DL);
  517. }
  518. static Constant *ConstantFoldLoadInst(const LoadInst *LI,
  519. const DataLayout &DL) {
  520. if (LI->isVolatile()) return nullptr;
  521. if (Constant *C = dyn_cast<Constant>(LI->getOperand(0)))
  522. return ConstantFoldLoadFromConstPtr(C, DL);
  523. return nullptr;
  524. }
  525. /// One of Op0/Op1 is a constant expression.
  526. /// Attempt to symbolically evaluate the result of a binary operator merging
  527. /// these together. If target data info is available, it is provided as DL,
  528. /// otherwise DL is null.
  529. static Constant *SymbolicallyEvaluateBinop(unsigned Opc, Constant *Op0,
  530. Constant *Op1,
  531. const DataLayout &DL) {
  532. // SROA
  533. // Fold (and 0xffffffff00000000, (shl x, 32)) -> shl.
  534. // Fold (lshr (or X, Y), 32) -> (lshr [X/Y], 32) if one doesn't contribute
  535. // bits.
  536. if (Opc == Instruction::And) {
  537. unsigned BitWidth = DL.getTypeSizeInBits(Op0->getType()->getScalarType());
  538. APInt KnownZero0(BitWidth, 0), KnownOne0(BitWidth, 0);
  539. APInt KnownZero1(BitWidth, 0), KnownOne1(BitWidth, 0);
  540. computeKnownBits(Op0, KnownZero0, KnownOne0, DL);
  541. computeKnownBits(Op1, KnownZero1, KnownOne1, DL);
  542. if ((KnownOne1 | KnownZero0).isAllOnesValue()) {
  543. // All the bits of Op0 that the 'and' could be masking are already zero.
  544. return Op0;
  545. }
  546. if ((KnownOne0 | KnownZero1).isAllOnesValue()) {
  547. // All the bits of Op1 that the 'and' could be masking are already zero.
  548. return Op1;
  549. }
  550. APInt KnownZero = KnownZero0 | KnownZero1;
  551. APInt KnownOne = KnownOne0 & KnownOne1;
  552. if ((KnownZero | KnownOne).isAllOnesValue()) {
  553. return ConstantInt::get(Op0->getType(), KnownOne);
  554. }
  555. }
  556. // If the constant expr is something like &A[123] - &A[4].f, fold this into a
  557. // constant. This happens frequently when iterating over a global array.
  558. if (Opc == Instruction::Sub) {
  559. GlobalValue *GV1, *GV2;
  560. APInt Offs1, Offs2;
  561. if (IsConstantOffsetFromGlobal(Op0, GV1, Offs1, DL))
  562. if (IsConstantOffsetFromGlobal(Op1, GV2, Offs2, DL) && GV1 == GV2) {
  563. unsigned OpSize = DL.getTypeSizeInBits(Op0->getType());
  564. // (&GV+C1) - (&GV+C2) -> C1-C2, pointer arithmetic cannot overflow.
  565. // PtrToInt may change the bitwidth so we have convert to the right size
  566. // first.
  567. return ConstantInt::get(Op0->getType(), Offs1.zextOrTrunc(OpSize) -
  568. Offs2.zextOrTrunc(OpSize));
  569. }
  570. }
  571. return nullptr;
  572. }
  573. /// If array indices are not pointer-sized integers, explicitly cast them so
  574. /// that they aren't implicitly casted by the getelementptr.
  575. static Constant *CastGEPIndices(Type *SrcTy, ArrayRef<Constant *> Ops,
  576. Type *ResultTy, const DataLayout &DL,
  577. const TargetLibraryInfo *TLI) {
  578. Type *IntPtrTy = DL.getIntPtrType(ResultTy);
  579. bool Any = false;
  580. SmallVector<Constant*, 32> NewIdxs;
  581. for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
  582. if ((i == 1 ||
  583. !isa<StructType>(GetElementPtrInst::getIndexedType(
  584. cast<PointerType>(Ops[0]->getType()->getScalarType())
  585. ->getElementType(),
  586. Ops.slice(1, i - 1)))) &&
  587. Ops[i]->getType() != IntPtrTy) {
  588. Any = true;
  589. NewIdxs.push_back(ConstantExpr::getCast(CastInst::getCastOpcode(Ops[i],
  590. true,
  591. IntPtrTy,
  592. true),
  593. Ops[i], IntPtrTy));
  594. } else
  595. NewIdxs.push_back(Ops[i]);
  596. }
  597. if (!Any)
  598. return nullptr;
  599. Constant *C = ConstantExpr::getGetElementPtr(SrcTy, Ops[0], NewIdxs);
  600. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  601. if (Constant *Folded = ConstantFoldConstantExpression(CE, DL, TLI))
  602. C = Folded;
  603. }
  604. return C;
  605. }
  606. /// Strip the pointer casts, but preserve the address space information.
  607. static Constant* StripPtrCastKeepAS(Constant* Ptr) {
  608. assert(Ptr->getType()->isPointerTy() && "Not a pointer type");
  609. PointerType *OldPtrTy = cast<PointerType>(Ptr->getType());
  610. Ptr = Ptr->stripPointerCasts();
  611. PointerType *NewPtrTy = cast<PointerType>(Ptr->getType());
  612. // Preserve the address space number of the pointer.
  613. if (NewPtrTy->getAddressSpace() != OldPtrTy->getAddressSpace()) {
  614. NewPtrTy = NewPtrTy->getElementType()->getPointerTo(
  615. OldPtrTy->getAddressSpace());
  616. Ptr = ConstantExpr::getPointerCast(Ptr, NewPtrTy);
  617. }
  618. return Ptr;
  619. }
  620. /// If we can symbolically evaluate the GEP constant expression, do so.
  621. static Constant *SymbolicallyEvaluateGEP(Type *SrcTy, ArrayRef<Constant *> Ops,
  622. Type *ResultTy, const DataLayout &DL,
  623. const TargetLibraryInfo *TLI) {
  624. Constant *Ptr = Ops[0];
  625. if (!Ptr->getType()->getPointerElementType()->isSized() ||
  626. !Ptr->getType()->isPointerTy())
  627. return nullptr;
  628. Type *IntPtrTy = DL.getIntPtrType(Ptr->getType());
  629. Type *ResultElementTy = ResultTy->getPointerElementType();
  630. // If this is a constant expr gep that is effectively computing an
  631. // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
  632. for (unsigned i = 1, e = Ops.size(); i != e; ++i)
  633. if (!isa<ConstantInt>(Ops[i])) {
  634. // If this is "gep i8* Ptr, (sub 0, V)", fold this as:
  635. // "inttoptr (sub (ptrtoint Ptr), V)"
  636. if (Ops.size() == 2 && ResultElementTy->isIntegerTy(8)) {
  637. ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[1]);
  638. assert((!CE || CE->getType() == IntPtrTy) &&
  639. "CastGEPIndices didn't canonicalize index types!");
  640. if (CE && CE->getOpcode() == Instruction::Sub &&
  641. CE->getOperand(0)->isNullValue()) {
  642. Constant *Res = ConstantExpr::getPtrToInt(Ptr, CE->getType());
  643. Res = ConstantExpr::getSub(Res, CE->getOperand(1));
  644. Res = ConstantExpr::getIntToPtr(Res, ResultTy);
  645. if (ConstantExpr *ResCE = dyn_cast<ConstantExpr>(Res))
  646. Res = ConstantFoldConstantExpression(ResCE, DL, TLI);
  647. return Res;
  648. }
  649. }
  650. return nullptr;
  651. }
  652. unsigned BitWidth = DL.getTypeSizeInBits(IntPtrTy);
  653. APInt Offset =
  654. APInt(BitWidth,
  655. DL.getIndexedOffset(
  656. Ptr->getType(),
  657. makeArrayRef((Value * const *)Ops.data() + 1, Ops.size() - 1)));
  658. Ptr = StripPtrCastKeepAS(Ptr);
  659. // If this is a GEP of a GEP, fold it all into a single GEP.
  660. while (GEPOperator *GEP = dyn_cast<GEPOperator>(Ptr)) {
  661. SmallVector<Value *, 4> NestedOps(GEP->op_begin() + 1, GEP->op_end());
  662. // Do not try the incorporate the sub-GEP if some index is not a number.
  663. bool AllConstantInt = true;
  664. for (unsigned i = 0, e = NestedOps.size(); i != e; ++i)
  665. if (!isa<ConstantInt>(NestedOps[i])) {
  666. AllConstantInt = false;
  667. break;
  668. }
  669. if (!AllConstantInt)
  670. break;
  671. Ptr = cast<Constant>(GEP->getOperand(0));
  672. Offset += APInt(BitWidth, DL.getIndexedOffset(Ptr->getType(), NestedOps));
  673. Ptr = StripPtrCastKeepAS(Ptr);
  674. }
  675. // If the base value for this address is a literal integer value, fold the
  676. // getelementptr to the resulting integer value casted to the pointer type.
  677. APInt BasePtr(BitWidth, 0);
  678. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  679. if (CE->getOpcode() == Instruction::IntToPtr) {
  680. if (ConstantInt *Base = dyn_cast<ConstantInt>(CE->getOperand(0)))
  681. BasePtr = Base->getValue().zextOrTrunc(BitWidth);
  682. }
  683. }
  684. if (Ptr->isNullValue() || BasePtr != 0) {
  685. Constant *C = ConstantInt::get(Ptr->getContext(), Offset + BasePtr);
  686. return ConstantExpr::getIntToPtr(C, ResultTy);
  687. }
  688. // Otherwise form a regular getelementptr. Recompute the indices so that
  689. // we eliminate over-indexing of the notional static type array bounds.
  690. // This makes it easy to determine if the getelementptr is "inbounds".
  691. // Also, this helps GlobalOpt do SROA on GlobalVariables.
  692. Type *Ty = Ptr->getType();
  693. assert(Ty->isPointerTy() && "Forming regular GEP of non-pointer type");
  694. SmallVector<Constant *, 32> NewIdxs;
  695. do {
  696. if (SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
  697. if (ATy->isPointerTy()) {
  698. // The only pointer indexing we'll do is on the first index of the GEP.
  699. if (!NewIdxs.empty())
  700. break;
  701. // Only handle pointers to sized types, not pointers to functions.
  702. if (!ATy->getElementType()->isSized())
  703. return nullptr;
  704. }
  705. // Determine which element of the array the offset points into.
  706. APInt ElemSize(BitWidth, DL.getTypeAllocSize(ATy->getElementType()));
  707. if (ElemSize == 0)
  708. // The element size is 0. This may be [0 x Ty]*, so just use a zero
  709. // index for this level and proceed to the next level to see if it can
  710. // accommodate the offset.
  711. NewIdxs.push_back(ConstantInt::get(IntPtrTy, 0));
  712. else {
  713. // The element size is non-zero divide the offset by the element
  714. // size (rounding down), to compute the index at this level.
  715. APInt NewIdx = Offset.udiv(ElemSize);
  716. Offset -= NewIdx * ElemSize;
  717. NewIdxs.push_back(ConstantInt::get(IntPtrTy, NewIdx));
  718. }
  719. Ty = ATy->getElementType();
  720. } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
  721. // If we end up with an offset that isn't valid for this struct type, we
  722. // can't re-form this GEP in a regular form, so bail out. The pointer
  723. // operand likely went through casts that are necessary to make the GEP
  724. // sensible.
  725. const StructLayout &SL = *DL.getStructLayout(STy);
  726. if (Offset.uge(SL.getSizeInBytes()))
  727. break;
  728. // Determine which field of the struct the offset points into. The
  729. // getZExtValue is fine as we've already ensured that the offset is
  730. // within the range representable by the StructLayout API.
  731. unsigned ElIdx = SL.getElementContainingOffset(Offset.getZExtValue());
  732. NewIdxs.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
  733. ElIdx));
  734. Offset -= APInt(BitWidth, SL.getElementOffset(ElIdx));
  735. Ty = STy->getTypeAtIndex(ElIdx);
  736. } else {
  737. // We've reached some non-indexable type.
  738. break;
  739. }
  740. } while (Ty != ResultElementTy);
  741. // If we haven't used up the entire offset by descending the static
  742. // type, then the offset is pointing into the middle of an indivisible
  743. // member, so we can't simplify it.
  744. if (Offset != 0)
  745. return nullptr;
  746. // Create a GEP.
  747. Constant *C = ConstantExpr::getGetElementPtr(SrcTy, Ptr, NewIdxs);
  748. assert(C->getType()->getPointerElementType() == Ty &&
  749. "Computed GetElementPtr has unexpected type!");
  750. // If we ended up indexing a member with a type that doesn't match
  751. // the type of what the original indices indexed, add a cast.
  752. if (Ty != ResultElementTy)
  753. C = FoldBitCast(C, ResultTy, DL);
  754. return C;
  755. }
  756. //===----------------------------------------------------------------------===//
  757. // Constant Folding public APIs
  758. //===----------------------------------------------------------------------===//
  759. /// Try to constant fold the specified instruction.
  760. /// If successful, the constant result is returned, if not, null is returned.
  761. /// Note that this fails if not all of the operands are constant. Otherwise,
  762. /// this function can only fail when attempting to fold instructions like loads
  763. /// and stores, which have no constant expression form.
  764. Constant *llvm::ConstantFoldInstruction(Instruction *I, const DataLayout &DL,
  765. const TargetLibraryInfo *TLI) {
  766. // Handle PHI nodes quickly here...
  767. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  768. Constant *CommonValue = nullptr;
  769. for (Value *Incoming : PN->incoming_values()) {
  770. // If the incoming value is undef then skip it. Note that while we could
  771. // skip the value if it is equal to the phi node itself we choose not to
  772. // because that would break the rule that constant folding only applies if
  773. // all operands are constants.
  774. if (isa<UndefValue>(Incoming))
  775. continue;
  776. // If the incoming value is not a constant, then give up.
  777. Constant *C = dyn_cast<Constant>(Incoming);
  778. if (!C)
  779. return nullptr;
  780. // Fold the PHI's operands.
  781. if (ConstantExpr *NewC = dyn_cast<ConstantExpr>(C))
  782. C = ConstantFoldConstantExpression(NewC, DL, TLI);
  783. // If the incoming value is a different constant to
  784. // the one we saw previously, then give up.
  785. if (CommonValue && C != CommonValue)
  786. return nullptr;
  787. CommonValue = C;
  788. }
  789. // If we reach here, all incoming values are the same constant or undef.
  790. return CommonValue ? CommonValue : UndefValue::get(PN->getType());
  791. }
  792. // Scan the operand list, checking to see if they are all constants, if so,
  793. // hand off to ConstantFoldInstOperands.
  794. SmallVector<Constant*, 8> Ops;
  795. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
  796. Constant *Op = dyn_cast<Constant>(*i);
  797. if (!Op)
  798. return nullptr; // All operands not constant!
  799. // Fold the Instruction's operands.
  800. if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(Op))
  801. Op = ConstantFoldConstantExpression(NewCE, DL, TLI);
  802. Ops.push_back(Op);
  803. }
  804. if (const CmpInst *CI = dyn_cast<CmpInst>(I))
  805. return ConstantFoldCompareInstOperands(CI->getPredicate(), Ops[0], Ops[1],
  806. DL, TLI);
  807. if (const LoadInst *LI = dyn_cast<LoadInst>(I))
  808. return ConstantFoldLoadInst(LI, DL);
  809. if (InsertValueInst *IVI = dyn_cast<InsertValueInst>(I)) {
  810. return ConstantExpr::getInsertValue(
  811. cast<Constant>(IVI->getAggregateOperand()),
  812. cast<Constant>(IVI->getInsertedValueOperand()),
  813. IVI->getIndices());
  814. }
  815. if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(I)) {
  816. return ConstantExpr::getExtractValue(
  817. cast<Constant>(EVI->getAggregateOperand()),
  818. EVI->getIndices());
  819. }
  820. return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops, DL, TLI);
  821. }
  822. static Constant *
  823. ConstantFoldConstantExpressionImpl(const ConstantExpr *CE, const DataLayout &DL,
  824. const TargetLibraryInfo *TLI,
  825. SmallPtrSetImpl<ConstantExpr *> &FoldedOps) {
  826. SmallVector<Constant *, 8> Ops;
  827. for (User::const_op_iterator i = CE->op_begin(), e = CE->op_end(); i != e;
  828. ++i) {
  829. Constant *NewC = cast<Constant>(*i);
  830. // Recursively fold the ConstantExpr's operands. If we have already folded
  831. // a ConstantExpr, we don't have to process it again.
  832. if (ConstantExpr *NewCE = dyn_cast<ConstantExpr>(NewC)) {
  833. if (FoldedOps.insert(NewCE).second)
  834. NewC = ConstantFoldConstantExpressionImpl(NewCE, DL, TLI, FoldedOps);
  835. }
  836. Ops.push_back(NewC);
  837. }
  838. if (CE->isCompare())
  839. return ConstantFoldCompareInstOperands(CE->getPredicate(), Ops[0], Ops[1],
  840. DL, TLI);
  841. return ConstantFoldInstOperands(CE->getOpcode(), CE->getType(), Ops, DL, TLI);
  842. }
  843. /// Attempt to fold the constant expression
  844. /// using the specified DataLayout. If successful, the constant result is
  845. /// result is returned, if not, null is returned.
  846. Constant *llvm::ConstantFoldConstantExpression(const ConstantExpr *CE,
  847. const DataLayout &DL,
  848. const TargetLibraryInfo *TLI) {
  849. SmallPtrSet<ConstantExpr *, 4> FoldedOps;
  850. return ConstantFoldConstantExpressionImpl(CE, DL, TLI, FoldedOps);
  851. }
  852. /// Attempt to constant fold an instruction with the
  853. /// specified opcode and operands. If successful, the constant result is
  854. /// returned, if not, null is returned. Note that this function can fail when
  855. /// attempting to fold instructions like loads and stores, which have no
  856. /// constant expression form.
  857. ///
  858. /// TODO: This function neither utilizes nor preserves nsw/nuw/inbounds/etc
  859. /// information, due to only being passed an opcode and operands. Constant
  860. /// folding using this function strips this information.
  861. ///
  862. Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, Type *DestTy,
  863. ArrayRef<Constant *> Ops,
  864. const DataLayout &DL,
  865. const TargetLibraryInfo *TLI) {
  866. // Handle easy binops first.
  867. if (Instruction::isBinaryOp(Opcode)) {
  868. if (isa<ConstantExpr>(Ops[0]) || isa<ConstantExpr>(Ops[1])) {
  869. if (Constant *C = SymbolicallyEvaluateBinop(Opcode, Ops[0], Ops[1], DL))
  870. return C;
  871. }
  872. return ConstantExpr::get(Opcode, Ops[0], Ops[1]);
  873. }
  874. switch (Opcode) {
  875. default: return nullptr;
  876. case Instruction::ICmp:
  877. case Instruction::FCmp: llvm_unreachable("Invalid for compares");
  878. case Instruction::Call:
  879. if (Function *F = dyn_cast<Function>(Ops.back()))
  880. if (canConstantFoldCallTo(F))
  881. return ConstantFoldCall(F, Ops.slice(0, Ops.size() - 1), TLI);
  882. return nullptr;
  883. case Instruction::PtrToInt:
  884. // If the input is a inttoptr, eliminate the pair. This requires knowing
  885. // the width of a pointer, so it can't be done in ConstantExpr::getCast.
  886. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
  887. if (CE->getOpcode() == Instruction::IntToPtr) {
  888. Constant *Input = CE->getOperand(0);
  889. unsigned InWidth = Input->getType()->getScalarSizeInBits();
  890. unsigned PtrWidth = DL.getPointerTypeSizeInBits(CE->getType());
  891. if (PtrWidth < InWidth) {
  892. Constant *Mask =
  893. ConstantInt::get(CE->getContext(),
  894. APInt::getLowBitsSet(InWidth, PtrWidth));
  895. Input = ConstantExpr::getAnd(Input, Mask);
  896. }
  897. // Do a zext or trunc to get to the dest size.
  898. return ConstantExpr::getIntegerCast(Input, DestTy, false);
  899. }
  900. }
  901. return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
  902. case Instruction::IntToPtr:
  903. // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
  904. // the int size is >= the ptr size and the address spaces are the same.
  905. // This requires knowing the width of a pointer, so it can't be done in
  906. // ConstantExpr::getCast.
  907. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
  908. if (CE->getOpcode() == Instruction::PtrToInt) {
  909. Constant *SrcPtr = CE->getOperand(0);
  910. unsigned SrcPtrSize = DL.getPointerTypeSizeInBits(SrcPtr->getType());
  911. unsigned MidIntSize = CE->getType()->getScalarSizeInBits();
  912. if (MidIntSize >= SrcPtrSize) {
  913. unsigned SrcAS = SrcPtr->getType()->getPointerAddressSpace();
  914. if (SrcAS == DestTy->getPointerAddressSpace())
  915. return FoldBitCast(CE->getOperand(0), DestTy, DL);
  916. }
  917. }
  918. }
  919. return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
  920. case Instruction::Trunc:
  921. case Instruction::ZExt:
  922. case Instruction::SExt:
  923. case Instruction::FPTrunc:
  924. case Instruction::FPExt:
  925. case Instruction::UIToFP:
  926. case Instruction::SIToFP:
  927. case Instruction::FPToUI:
  928. case Instruction::FPToSI:
  929. case Instruction::AddrSpaceCast:
  930. return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
  931. case Instruction::BitCast:
  932. return FoldBitCast(Ops[0], DestTy, DL);
  933. case Instruction::Select:
  934. return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);
  935. case Instruction::ExtractElement:
  936. return ConstantExpr::getExtractElement(Ops[0], Ops[1]);
  937. case Instruction::InsertElement:
  938. return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);
  939. case Instruction::ShuffleVector:
  940. return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);
  941. case Instruction::GetElementPtr: {
  942. Type *SrcTy = nullptr;
  943. if (Constant *C = CastGEPIndices(SrcTy, Ops, DestTy, DL, TLI))
  944. return C;
  945. if (Constant *C = SymbolicallyEvaluateGEP(SrcTy, Ops, DestTy, DL, TLI))
  946. return C;
  947. return ConstantExpr::getGetElementPtr(SrcTy, Ops[0], Ops.slice(1));
  948. }
  949. }
  950. }
  951. /// Attempt to constant fold a compare
  952. /// instruction (icmp/fcmp) with the specified operands. If it fails, it
  953. /// returns a constant expression of the specified operands.
  954. Constant *llvm::ConstantFoldCompareInstOperands(unsigned Predicate,
  955. Constant *Ops0, Constant *Ops1,
  956. const DataLayout &DL,
  957. const TargetLibraryInfo *TLI) {
  958. // fold: icmp (inttoptr x), null -> icmp x, 0
  959. // fold: icmp (ptrtoint x), 0 -> icmp x, null
  960. // fold: icmp (inttoptr x), (inttoptr y) -> icmp trunc/zext x, trunc/zext y
  961. // fold: icmp (ptrtoint x), (ptrtoint y) -> icmp x, y
  962. //
  963. // FIXME: The following comment is out of data and the DataLayout is here now.
  964. // ConstantExpr::getCompare cannot do this, because it doesn't have DL
  965. // around to know if bit truncation is happening.
  966. if (ConstantExpr *CE0 = dyn_cast<ConstantExpr>(Ops0)) {
  967. if (Ops1->isNullValue()) {
  968. if (CE0->getOpcode() == Instruction::IntToPtr) {
  969. Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
  970. // Convert the integer value to the right size to ensure we get the
  971. // proper extension or truncation.
  972. Constant *C = ConstantExpr::getIntegerCast(CE0->getOperand(0),
  973. IntPtrTy, false);
  974. Constant *Null = Constant::getNullValue(C->getType());
  975. return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
  976. }
  977. // Only do this transformation if the int is intptrty in size, otherwise
  978. // there is a truncation or extension that we aren't modeling.
  979. if (CE0->getOpcode() == Instruction::PtrToInt) {
  980. Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
  981. if (CE0->getType() == IntPtrTy) {
  982. Constant *C = CE0->getOperand(0);
  983. Constant *Null = Constant::getNullValue(C->getType());
  984. return ConstantFoldCompareInstOperands(Predicate, C, Null, DL, TLI);
  985. }
  986. }
  987. }
  988. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(Ops1)) {
  989. if (CE0->getOpcode() == CE1->getOpcode()) {
  990. if (CE0->getOpcode() == Instruction::IntToPtr) {
  991. Type *IntPtrTy = DL.getIntPtrType(CE0->getType());
  992. // Convert the integer value to the right size to ensure we get the
  993. // proper extension or truncation.
  994. Constant *C0 = ConstantExpr::getIntegerCast(CE0->getOperand(0),
  995. IntPtrTy, false);
  996. Constant *C1 = ConstantExpr::getIntegerCast(CE1->getOperand(0),
  997. IntPtrTy, false);
  998. return ConstantFoldCompareInstOperands(Predicate, C0, C1, DL, TLI);
  999. }
  1000. // Only do this transformation if the int is intptrty in size, otherwise
  1001. // there is a truncation or extension that we aren't modeling.
  1002. if (CE0->getOpcode() == Instruction::PtrToInt) {
  1003. Type *IntPtrTy = DL.getIntPtrType(CE0->getOperand(0)->getType());
  1004. if (CE0->getType() == IntPtrTy &&
  1005. CE0->getOperand(0)->getType() == CE1->getOperand(0)->getType()) {
  1006. return ConstantFoldCompareInstOperands(
  1007. Predicate, CE0->getOperand(0), CE1->getOperand(0), DL, TLI);
  1008. }
  1009. }
  1010. }
  1011. }
  1012. // icmp eq (or x, y), 0 -> (icmp eq x, 0) & (icmp eq y, 0)
  1013. // icmp ne (or x, y), 0 -> (icmp ne x, 0) | (icmp ne y, 0)
  1014. if ((Predicate == ICmpInst::ICMP_EQ || Predicate == ICmpInst::ICMP_NE) &&
  1015. CE0->getOpcode() == Instruction::Or && Ops1->isNullValue()) {
  1016. Constant *LHS = ConstantFoldCompareInstOperands(
  1017. Predicate, CE0->getOperand(0), Ops1, DL, TLI);
  1018. Constant *RHS = ConstantFoldCompareInstOperands(
  1019. Predicate, CE0->getOperand(1), Ops1, DL, TLI);
  1020. unsigned OpC =
  1021. Predicate == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
  1022. Constant *Ops[] = { LHS, RHS };
  1023. return ConstantFoldInstOperands(OpC, LHS->getType(), Ops, DL, TLI);
  1024. }
  1025. }
  1026. return ConstantExpr::getCompare(Predicate, Ops0, Ops1);
  1027. }
  1028. /// Given a constant and a getelementptr constantexpr, return the constant value
  1029. /// being addressed by the constant expression, or null if something is funny
  1030. /// and we can't decide.
  1031. Constant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C,
  1032. ConstantExpr *CE) {
  1033. if (!CE->getOperand(1)->isNullValue())
  1034. return nullptr; // Do not allow stepping over the value!
  1035. // Loop over all of the operands, tracking down which value we are
  1036. // addressing.
  1037. for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i) {
  1038. C = C->getAggregateElement(CE->getOperand(i));
  1039. if (!C)
  1040. return nullptr;
  1041. }
  1042. return C;
  1043. }
  1044. /// Given a constant and getelementptr indices (with an *implied* zero pointer
  1045. /// index that is not in the list), return the constant value being addressed by
  1046. /// a virtual load, or null if something is funny and we can't decide.
  1047. Constant *llvm::ConstantFoldLoadThroughGEPIndices(Constant *C,
  1048. ArrayRef<Constant*> Indices) {
  1049. // Loop over all of the operands, tracking down which value we are
  1050. // addressing.
  1051. for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
  1052. C = C->getAggregateElement(Indices[i]);
  1053. if (!C)
  1054. return nullptr;
  1055. }
  1056. return C;
  1057. }
  1058. //===----------------------------------------------------------------------===//
  1059. // Constant Folding for Calls
  1060. //
  1061. /// Return true if it's even possible to fold a call to the specified function.
  1062. bool llvm::canConstantFoldCallTo(const Function *F) {
  1063. if (hlsl::CanConstantFoldCallTo(F)) // HLSL Change
  1064. return true;
  1065. switch (F->getIntrinsicID()) {
  1066. case Intrinsic::fabs:
  1067. case Intrinsic::minnum:
  1068. case Intrinsic::maxnum:
  1069. case Intrinsic::log:
  1070. case Intrinsic::log2:
  1071. case Intrinsic::log10:
  1072. case Intrinsic::exp:
  1073. case Intrinsic::exp2:
  1074. case Intrinsic::floor:
  1075. case Intrinsic::ceil:
  1076. case Intrinsic::sqrt:
  1077. case Intrinsic::sin:
  1078. case Intrinsic::cos:
  1079. case Intrinsic::pow:
  1080. case Intrinsic::powi:
  1081. case Intrinsic::bswap:
  1082. case Intrinsic::ctpop:
  1083. case Intrinsic::ctlz:
  1084. case Intrinsic::cttz:
  1085. case Intrinsic::fma:
  1086. case Intrinsic::fmuladd:
  1087. case Intrinsic::copysign:
  1088. case Intrinsic::round:
  1089. case Intrinsic::sadd_with_overflow:
  1090. case Intrinsic::uadd_with_overflow:
  1091. case Intrinsic::ssub_with_overflow:
  1092. case Intrinsic::usub_with_overflow:
  1093. case Intrinsic::smul_with_overflow:
  1094. case Intrinsic::umul_with_overflow:
  1095. case Intrinsic::convert_from_fp16:
  1096. case Intrinsic::convert_to_fp16:
  1097. #if 0 // HLSL Change - remove platform intrinsics
  1098. case Intrinsic::x86_sse_cvtss2si:
  1099. case Intrinsic::x86_sse_cvtss2si64:
  1100. case Intrinsic::x86_sse_cvttss2si:
  1101. case Intrinsic::x86_sse_cvttss2si64:
  1102. case Intrinsic::x86_sse2_cvtsd2si:
  1103. case Intrinsic::x86_sse2_cvtsd2si64:
  1104. case Intrinsic::x86_sse2_cvttsd2si:
  1105. case Intrinsic::x86_sse2_cvttsd2si64:
  1106. #endif // HLSL Change - remove platform intrinsics
  1107. return true;
  1108. default:
  1109. return false;
  1110. case 0: break;
  1111. }
  1112. if (!F->hasName())
  1113. return false;
  1114. StringRef Name = F->getName();
  1115. // In these cases, the check of the length is required. We don't want to
  1116. // return true for a name like "cos\0blah" which strcmp would return equal to
  1117. // "cos", but has length 8.
  1118. switch (Name[0]) {
  1119. default: return false;
  1120. case 'a':
  1121. return Name == "acos" || Name == "asin" || Name == "atan" || Name =="atan2";
  1122. case 'c':
  1123. return Name == "cos" || Name == "ceil" || Name == "cosf" || Name == "cosh";
  1124. case 'e':
  1125. return Name == "exp" || Name == "exp2";
  1126. case 'f':
  1127. return Name == "fabs" || Name == "fmod" || Name == "floor";
  1128. case 'l':
  1129. return Name == "log" || Name == "log10";
  1130. case 'p':
  1131. return Name == "pow";
  1132. case 's':
  1133. return Name == "sin" || Name == "sinh" || Name == "sqrt" ||
  1134. Name == "sinf" || Name == "sqrtf";
  1135. case 't':
  1136. return Name == "tan" || Name == "tanh";
  1137. }
  1138. }
  1139. static Constant *GetConstantFoldFPValue(double V, Type *Ty) {
  1140. if (Ty->isHalfTy()) {
  1141. APFloat APF(V);
  1142. bool unused;
  1143. APF.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &unused);
  1144. return ConstantFP::get(Ty->getContext(), APF);
  1145. }
  1146. if (Ty->isFloatTy())
  1147. return ConstantFP::get(Ty->getContext(), APFloat((float)V));
  1148. if (Ty->isDoubleTy())
  1149. return ConstantFP::get(Ty->getContext(), APFloat(V));
  1150. llvm_unreachable("Can only constant fold half/float/double");
  1151. }
  1152. namespace {
  1153. /// Clear the floating-point exception state.
  1154. static inline void llvm_fenv_clearexcept() {
  1155. #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT
  1156. feclearexcept(FE_ALL_EXCEPT);
  1157. #endif
  1158. errno = 0;
  1159. }
  1160. /// Test if a floating-point exception was raised.
  1161. static inline bool llvm_fenv_testexcept() {
  1162. int errno_val = errno;
  1163. if (errno_val == ERANGE || errno_val == EDOM)
  1164. return true;
  1165. #if defined(HAVE_FENV_H) && HAVE_DECL_FE_ALL_EXCEPT && HAVE_DECL_FE_INEXACT
  1166. if (fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT))
  1167. return true;
  1168. #endif
  1169. return false;
  1170. }
  1171. } // End namespace
  1172. // HLSL Change: changed calling convention of NativeFP to __cdecl and make non-static
  1173. Constant *llvm::ConstantFoldFP(double (__cdecl *NativeFP)(double), double V,
  1174. Type *Ty) {
  1175. llvm_fenv_clearexcept();
  1176. V = NativeFP(V);
  1177. if (llvm_fenv_testexcept()) {
  1178. llvm_fenv_clearexcept();
  1179. return nullptr;
  1180. }
  1181. return GetConstantFoldFPValue(V, Ty);
  1182. }
  1183. // HLSL Change: changed calling convention of NativeFP to __cdecl
  1184. static Constant *ConstantFoldBinaryFP(double (__cdecl *NativeFP)(double, double),
  1185. double V, double W, Type *Ty) {
  1186. llvm_fenv_clearexcept();
  1187. V = NativeFP(V, W);
  1188. if (llvm_fenv_testexcept()) {
  1189. llvm_fenv_clearexcept();
  1190. return nullptr;
  1191. }
  1192. return GetConstantFoldFPValue(V, Ty);
  1193. }
  1194. #if 0 // HLSL Change - remove platform intrinsics
  1195. /// Attempt to fold an SSE floating point to integer conversion of a constant
  1196. /// floating point. If roundTowardZero is false, the default IEEE rounding is
  1197. /// used (toward nearest, ties to even). This matches the behavior of the
  1198. /// non-truncating SSE instructions in the default rounding mode. The desired
  1199. /// integer type Ty is used to select how many bits are available for the
  1200. /// result. Returns null if the conversion cannot be performed, otherwise
  1201. /// returns the Constant value resulting from the conversion.
  1202. static Constant *ConstantFoldConvertToInt(const APFloat &Val,
  1203. bool roundTowardZero, Type *Ty) {
  1204. // All of these conversion intrinsics form an integer of at most 64bits.
  1205. unsigned ResultWidth = Ty->getIntegerBitWidth();
  1206. assert(ResultWidth <= 64 &&
  1207. "Can only constant fold conversions to 64 and 32 bit ints");
  1208. uint64_t UIntVal;
  1209. bool isExact = false;
  1210. APFloat::roundingMode mode = roundTowardZero? APFloat::rmTowardZero
  1211. : APFloat::rmNearestTiesToEven;
  1212. APFloat::opStatus status = Val.convertToInteger(&UIntVal, ResultWidth,
  1213. /*isSigned=*/true, mode,
  1214. &isExact);
  1215. if (status != APFloat::opOK && status != APFloat::opInexact)
  1216. return nullptr;
  1217. return ConstantInt::get(Ty, UIntVal, /*isSigned=*/true);
  1218. }
  1219. #endif // HLSL Change Ends
  1220. // HLSL Change - make non-static.
  1221. double llvm::getValueAsDouble(ConstantFP *Op) {
  1222. Type *Ty = Op->getType();
  1223. if (Ty->isFloatTy())
  1224. return Op->getValueAPF().convertToFloat();
  1225. if (Ty->isDoubleTy())
  1226. return Op->getValueAPF().convertToDouble();
  1227. bool unused;
  1228. APFloat APF = Op->getValueAPF();
  1229. APF.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven, &unused);
  1230. return APF.convertToDouble();
  1231. }
  1232. static Constant *ConstantFoldScalarCall(StringRef Name, unsigned IntrinsicID,
  1233. Type *Ty, ArrayRef<Constant *> Operands,
  1234. const TargetLibraryInfo *TLI) {
  1235. if (Constant *C = hlsl::ConstantFoldScalarCall(Name, Ty, Operands)) // HLSL Change - Try hlsl constant folding first.
  1236. return C;
  1237. if (Operands.size() == 1) {
  1238. if (ConstantFP *Op = dyn_cast<ConstantFP>(Operands[0])) {
  1239. if (IntrinsicID == Intrinsic::convert_to_fp16) {
  1240. APFloat Val(Op->getValueAPF());
  1241. bool lost = false;
  1242. Val.convert(APFloat::IEEEhalf, APFloat::rmNearestTiesToEven, &lost);
  1243. return ConstantInt::get(Ty->getContext(), Val.bitcastToAPInt());
  1244. }
  1245. if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
  1246. return nullptr;
  1247. if (IntrinsicID == Intrinsic::round) {
  1248. APFloat V = Op->getValueAPF();
  1249. V.roundToIntegral(APFloat::rmNearestTiesToAway);
  1250. return ConstantFP::get(Ty->getContext(), V);
  1251. }
  1252. /// We only fold functions with finite arguments. Folding NaN and inf is
  1253. /// likely to be aborted with an exception anyway, and some host libms
  1254. /// have known errors raising exceptions.
  1255. if (Op->getValueAPF().isNaN() || Op->getValueAPF().isInfinity())
  1256. return nullptr;
  1257. /// Currently APFloat versions of these functions do not exist, so we use
  1258. /// the host native double versions. Float versions are not called
  1259. /// directly but for all these it is true (float)(f((double)arg)) ==
  1260. /// f(arg). Long double not supported yet.
  1261. double V = getValueAsDouble(Op);
  1262. switch (IntrinsicID) {
  1263. default: break;
  1264. case Intrinsic::fabs:
  1265. return ConstantFoldFP(fabs, V, Ty);
  1266. case Intrinsic::log2:
  1267. return ConstantFoldFP(Log2, V, Ty);
  1268. case Intrinsic::log:
  1269. return ConstantFoldFP(log, V, Ty);
  1270. case Intrinsic::log10:
  1271. return ConstantFoldFP(log10, V, Ty);
  1272. case Intrinsic::exp:
  1273. return ConstantFoldFP(exp, V, Ty);
  1274. case Intrinsic::exp2:
  1275. return ConstantFoldFP(exp2, V, Ty);
  1276. case Intrinsic::floor:
  1277. return ConstantFoldFP(floor, V, Ty);
  1278. case Intrinsic::ceil:
  1279. return ConstantFoldFP(ceil, V, Ty);
  1280. case Intrinsic::sin:
  1281. return ConstantFoldFP(sin, V, Ty);
  1282. case Intrinsic::cos:
  1283. return ConstantFoldFP(cos, V, Ty);
  1284. }
  1285. if (!TLI)
  1286. return nullptr;
  1287. switch (Name[0]) {
  1288. case 'a':
  1289. if (Name == "acos" && TLI->has(LibFunc::acos))
  1290. return ConstantFoldFP(acos, V, Ty);
  1291. else if (Name == "asin" && TLI->has(LibFunc::asin))
  1292. return ConstantFoldFP(asin, V, Ty);
  1293. else if (Name == "atan" && TLI->has(LibFunc::atan))
  1294. return ConstantFoldFP(atan, V, Ty);
  1295. break;
  1296. case 'c':
  1297. if (Name == "ceil" && TLI->has(LibFunc::ceil))
  1298. return ConstantFoldFP(ceil, V, Ty);
  1299. else if (Name == "cos" && TLI->has(LibFunc::cos))
  1300. return ConstantFoldFP(cos, V, Ty);
  1301. else if (Name == "cosh" && TLI->has(LibFunc::cosh))
  1302. return ConstantFoldFP(cosh, V, Ty);
  1303. else if (Name == "cosf" && TLI->has(LibFunc::cosf))
  1304. return ConstantFoldFP(cos, V, Ty);
  1305. break;
  1306. case 'e':
  1307. if (Name == "exp" && TLI->has(LibFunc::exp))
  1308. return ConstantFoldFP(exp, V, Ty);
  1309. if (Name == "exp2" && TLI->has(LibFunc::exp2)) {
  1310. // Constant fold exp2(x) as pow(2,x) in case the host doesn't have a
  1311. // C99 library.
  1312. return ConstantFoldBinaryFP(pow, 2.0, V, Ty);
  1313. }
  1314. break;
  1315. case 'f':
  1316. if (Name == "fabs" && TLI->has(LibFunc::fabs))
  1317. return ConstantFoldFP(fabs, V, Ty);
  1318. else if (Name == "floor" && TLI->has(LibFunc::floor))
  1319. return ConstantFoldFP(floor, V, Ty);
  1320. break;
  1321. case 'l':
  1322. if (Name == "log" && V > 0 && TLI->has(LibFunc::log))
  1323. return ConstantFoldFP(log, V, Ty);
  1324. else if (Name == "log10" && V > 0 && TLI->has(LibFunc::log10))
  1325. return ConstantFoldFP(log10, V, Ty);
  1326. else if (IntrinsicID == Intrinsic::sqrt &&
  1327. (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy())) {
  1328. if (V >= -0.0)
  1329. return ConstantFoldFP(sqrt, V, Ty);
  1330. else {
  1331. // Unlike the sqrt definitions in C/C++, POSIX, and IEEE-754 - which
  1332. // all guarantee or favor returning NaN - the square root of a
  1333. // negative number is not defined for the LLVM sqrt intrinsic.
  1334. // This is because the intrinsic should only be emitted in place of
  1335. // libm's sqrt function when using "no-nans-fp-math".
  1336. return UndefValue::get(Ty);
  1337. }
  1338. }
  1339. break;
  1340. case 's':
  1341. if (Name == "sin" && TLI->has(LibFunc::sin))
  1342. return ConstantFoldFP(sin, V, Ty);
  1343. else if (Name == "sinh" && TLI->has(LibFunc::sinh))
  1344. return ConstantFoldFP(sinh, V, Ty);
  1345. else if (Name == "sqrt" && V >= 0 && TLI->has(LibFunc::sqrt))
  1346. return ConstantFoldFP(sqrt, V, Ty);
  1347. else if (Name == "sqrtf" && V >= 0 && TLI->has(LibFunc::sqrtf))
  1348. return ConstantFoldFP(sqrt, V, Ty);
  1349. else if (Name == "sinf" && TLI->has(LibFunc::sinf))
  1350. return ConstantFoldFP(sin, V, Ty);
  1351. break;
  1352. case 't':
  1353. if (Name == "tan" && TLI->has(LibFunc::tan))
  1354. return ConstantFoldFP(tan, V, Ty);
  1355. else if (Name == "tanh" && TLI->has(LibFunc::tanh))
  1356. return ConstantFoldFP(tanh, V, Ty);
  1357. break;
  1358. default:
  1359. break;
  1360. }
  1361. return nullptr;
  1362. }
  1363. if (ConstantInt *Op = dyn_cast<ConstantInt>(Operands[0])) {
  1364. switch (IntrinsicID) {
  1365. case Intrinsic::bswap:
  1366. return ConstantInt::get(Ty->getContext(), Op->getValue().byteSwap());
  1367. case Intrinsic::ctpop:
  1368. return ConstantInt::get(Ty, Op->getValue().countPopulation());
  1369. case Intrinsic::convert_from_fp16: {
  1370. APFloat Val(APFloat::IEEEhalf, Op->getValue());
  1371. bool lost = false;
  1372. APFloat::opStatus status = Val.convert(
  1373. Ty->getFltSemantics(), APFloat::rmNearestTiesToEven, &lost);
  1374. // Conversion is always precise.
  1375. (void)status;
  1376. assert(status == APFloat::opOK && !lost &&
  1377. "Precision lost during fp16 constfolding");
  1378. return ConstantFP::get(Ty->getContext(), Val);
  1379. }
  1380. default:
  1381. return nullptr;
  1382. }
  1383. }
  1384. #if 0 // HLSL Change - remove platform intrinsics
  1385. // Support ConstantVector in case we have an Undef in the top.
  1386. if (isa<ConstantVector>(Operands[0]) ||
  1387. isa<ConstantDataVector>(Operands[0])) {
  1388. Constant *Op = cast<Constant>(Operands[0]);
  1389. switch (IntrinsicID) {
  1390. default: break;
  1391. case Intrinsic::x86_sse_cvtss2si:
  1392. case Intrinsic::x86_sse_cvtss2si64:
  1393. case Intrinsic::x86_sse2_cvtsd2si:
  1394. case Intrinsic::x86_sse2_cvtsd2si64:
  1395. if (ConstantFP *FPOp =
  1396. dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
  1397. return ConstantFoldConvertToInt(FPOp->getValueAPF(),
  1398. /*roundTowardZero=*/false, Ty);
  1399. case Intrinsic::x86_sse_cvttss2si:
  1400. case Intrinsic::x86_sse_cvttss2si64:
  1401. case Intrinsic::x86_sse2_cvttsd2si:
  1402. case Intrinsic::x86_sse2_cvttsd2si64:
  1403. if (ConstantFP *FPOp =
  1404. dyn_cast_or_null<ConstantFP>(Op->getAggregateElement(0U)))
  1405. return ConstantFoldConvertToInt(FPOp->getValueAPF(),
  1406. /*roundTowardZero=*/true, Ty);
  1407. }
  1408. }
  1409. #endif // HLSL Change - remove platform intrinsics
  1410. if (isa<UndefValue>(Operands[0])) {
  1411. if (IntrinsicID == Intrinsic::bswap)
  1412. return Operands[0];
  1413. return nullptr;
  1414. }
  1415. return nullptr;
  1416. }
  1417. if (Operands.size() == 2) {
  1418. if (ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
  1419. if (!Ty->isHalfTy() && !Ty->isFloatTy() && !Ty->isDoubleTy())
  1420. return nullptr;
  1421. double Op1V = getValueAsDouble(Op1);
  1422. if (ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
  1423. if (Op2->getType() != Op1->getType())
  1424. return nullptr;
  1425. double Op2V = getValueAsDouble(Op2);
  1426. if (IntrinsicID == Intrinsic::pow) {
  1427. return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
  1428. }
  1429. if (IntrinsicID == Intrinsic::copysign) {
  1430. APFloat V1 = Op1->getValueAPF();
  1431. APFloat V2 = Op2->getValueAPF();
  1432. V1.copySign(V2);
  1433. return ConstantFP::get(Ty->getContext(), V1);
  1434. }
  1435. if (IntrinsicID == Intrinsic::minnum) {
  1436. const APFloat &C1 = Op1->getValueAPF();
  1437. const APFloat &C2 = Op2->getValueAPF();
  1438. return ConstantFP::get(Ty->getContext(), minnum(C1, C2));
  1439. }
  1440. if (IntrinsicID == Intrinsic::maxnum) {
  1441. const APFloat &C1 = Op1->getValueAPF();
  1442. const APFloat &C2 = Op2->getValueAPF();
  1443. return ConstantFP::get(Ty->getContext(), maxnum(C1, C2));
  1444. }
  1445. if (!TLI)
  1446. return nullptr;
  1447. if (Name == "pow" && TLI->has(LibFunc::pow))
  1448. return ConstantFoldBinaryFP(pow, Op1V, Op2V, Ty);
  1449. if (Name == "fmod" && TLI->has(LibFunc::fmod))
  1450. return ConstantFoldBinaryFP(fmod, Op1V, Op2V, Ty);
  1451. if (Name == "atan2" && TLI->has(LibFunc::atan2))
  1452. return ConstantFoldBinaryFP(atan2, Op1V, Op2V, Ty);
  1453. } else if (ConstantInt *Op2C = dyn_cast<ConstantInt>(Operands[1])) {
  1454. if (IntrinsicID == Intrinsic::powi && Ty->isHalfTy())
  1455. return ConstantFP::get(Ty->getContext(),
  1456. APFloat((float)std::pow((float)Op1V,
  1457. (int)Op2C->getZExtValue())));
  1458. if (IntrinsicID == Intrinsic::powi && Ty->isFloatTy())
  1459. return ConstantFP::get(Ty->getContext(),
  1460. APFloat((float)std::pow((float)Op1V,
  1461. (int)Op2C->getZExtValue())));
  1462. if (IntrinsicID == Intrinsic::powi && Ty->isDoubleTy())
  1463. return ConstantFP::get(Ty->getContext(),
  1464. APFloat((double)std::pow((double)Op1V,
  1465. (int)Op2C->getZExtValue())));
  1466. }
  1467. return nullptr;
  1468. }
  1469. if (ConstantInt *Op1 = dyn_cast<ConstantInt>(Operands[0])) {
  1470. if (ConstantInt *Op2 = dyn_cast<ConstantInt>(Operands[1])) {
  1471. switch (IntrinsicID) {
  1472. default: break;
  1473. case Intrinsic::sadd_with_overflow:
  1474. case Intrinsic::uadd_with_overflow:
  1475. case Intrinsic::ssub_with_overflow:
  1476. case Intrinsic::usub_with_overflow:
  1477. case Intrinsic::smul_with_overflow:
  1478. case Intrinsic::umul_with_overflow: {
  1479. APInt Res;
  1480. bool Overflow;
  1481. switch (IntrinsicID) {
  1482. default: llvm_unreachable("Invalid case");
  1483. case Intrinsic::sadd_with_overflow:
  1484. Res = Op1->getValue().sadd_ov(Op2->getValue(), Overflow);
  1485. break;
  1486. case Intrinsic::uadd_with_overflow:
  1487. Res = Op1->getValue().uadd_ov(Op2->getValue(), Overflow);
  1488. break;
  1489. case Intrinsic::ssub_with_overflow:
  1490. Res = Op1->getValue().ssub_ov(Op2->getValue(), Overflow);
  1491. break;
  1492. case Intrinsic::usub_with_overflow:
  1493. Res = Op1->getValue().usub_ov(Op2->getValue(), Overflow);
  1494. break;
  1495. case Intrinsic::smul_with_overflow:
  1496. Res = Op1->getValue().smul_ov(Op2->getValue(), Overflow);
  1497. break;
  1498. case Intrinsic::umul_with_overflow:
  1499. Res = Op1->getValue().umul_ov(Op2->getValue(), Overflow);
  1500. break;
  1501. }
  1502. Constant *Ops[] = {
  1503. ConstantInt::get(Ty->getContext(), Res),
  1504. ConstantInt::get(Type::getInt1Ty(Ty->getContext()), Overflow)
  1505. };
  1506. return ConstantStruct::get(cast<StructType>(Ty), Ops);
  1507. }
  1508. case Intrinsic::cttz:
  1509. if (Op2->isOne() && Op1->isZero()) // cttz(0, 1) is undef.
  1510. return UndefValue::get(Ty);
  1511. return ConstantInt::get(Ty, Op1->getValue().countTrailingZeros());
  1512. case Intrinsic::ctlz:
  1513. if (Op2->isOne() && Op1->isZero()) // ctlz(0, 1) is undef.
  1514. return UndefValue::get(Ty);
  1515. return ConstantInt::get(Ty, Op1->getValue().countLeadingZeros());
  1516. }
  1517. }
  1518. return nullptr;
  1519. }
  1520. return nullptr;
  1521. }
  1522. if (Operands.size() != 3)
  1523. return nullptr;
  1524. if (const ConstantFP *Op1 = dyn_cast<ConstantFP>(Operands[0])) {
  1525. if (const ConstantFP *Op2 = dyn_cast<ConstantFP>(Operands[1])) {
  1526. if (const ConstantFP *Op3 = dyn_cast<ConstantFP>(Operands[2])) {
  1527. switch (IntrinsicID) {
  1528. default: break;
  1529. case Intrinsic::fma:
  1530. case Intrinsic::fmuladd: {
  1531. APFloat V = Op1->getValueAPF();
  1532. APFloat::opStatus s = V.fusedMultiplyAdd(Op2->getValueAPF(),
  1533. Op3->getValueAPF(),
  1534. APFloat::rmNearestTiesToEven);
  1535. if (s != APFloat::opInvalidOp)
  1536. return ConstantFP::get(Ty->getContext(), V);
  1537. return nullptr;
  1538. }
  1539. }
  1540. }
  1541. }
  1542. }
  1543. return nullptr;
  1544. }
  1545. static Constant *ConstantFoldVectorCall(StringRef Name, unsigned IntrinsicID,
  1546. VectorType *VTy,
  1547. ArrayRef<Constant *> Operands,
  1548. const TargetLibraryInfo *TLI) {
  1549. SmallVector<Constant *, 4> Result(VTy->getNumElements());
  1550. SmallVector<Constant *, 4> Lane(Operands.size());
  1551. Type *Ty = VTy->getElementType();
  1552. for (unsigned I = 0, E = VTy->getNumElements(); I != E; ++I) {
  1553. // Gather a column of constants.
  1554. for (unsigned J = 0, JE = Operands.size(); J != JE; ++J) {
  1555. Constant *Agg = Operands[J]->getAggregateElement(I);
  1556. if (!Agg)
  1557. return nullptr;
  1558. Lane[J] = Agg;
  1559. }
  1560. // Use the regular scalar folding to simplify this column.
  1561. Constant *Folded = ConstantFoldScalarCall(Name, IntrinsicID, Ty, Lane, TLI);
  1562. if (!Folded)
  1563. return nullptr;
  1564. Result[I] = Folded;
  1565. }
  1566. return ConstantVector::get(Result);
  1567. }
  1568. /// Attempt to constant fold a call to the specified function
  1569. /// with the specified arguments, returning null if unsuccessful.
  1570. Constant *
  1571. llvm::ConstantFoldCall(Function *F, ArrayRef<Constant *> Operands,
  1572. const TargetLibraryInfo *TLI) {
  1573. if (!F->hasName())
  1574. return nullptr;
  1575. StringRef Name = F->getName();
  1576. Type *Ty = F->getReturnType();
  1577. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  1578. return ConstantFoldVectorCall(Name, F->getIntrinsicID(), VTy, Operands, TLI);
  1579. return ConstantFoldScalarCall(Name, F->getIntrinsicID(), Ty, Operands, TLI);
  1580. }