ConstantFold.cpp 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288
  1. //===- ConstantFold.cpp - LLVM constant folder ----------------------------===//
  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 folding of constants for LLVM. This implements the
  10. // (internal) ConstantFold.h interface, which is used by the
  11. // ConstantExpr::get* methods to automatically fold constants when possible.
  12. //
  13. // The current constant folding implementation is implemented in two pieces: the
  14. // pieces that don't need DataLayout, and the pieces that do. This is to avoid
  15. // a dependence in IR on Target.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/IR/ConstantFold.h"
  19. #include "llvm/ADT/APSInt.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/IR/Constants.h"
  22. #include "llvm/IR/DerivedTypes.h"
  23. #include "llvm/IR/Function.h"
  24. #include "llvm/IR/GetElementPtrTypeIterator.h"
  25. #include "llvm/IR/GlobalAlias.h"
  26. #include "llvm/IR/GlobalVariable.h"
  27. #include "llvm/IR/Instructions.h"
  28. #include "llvm/IR/Module.h"
  29. #include "llvm/IR/Operator.h"
  30. #include "llvm/IR/PatternMatch.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. using namespace llvm;
  33. using namespace llvm::PatternMatch;
  34. //===----------------------------------------------------------------------===//
  35. // ConstantFold*Instruction Implementations
  36. //===----------------------------------------------------------------------===//
  37. /// Convert the specified vector Constant node to the specified vector type.
  38. /// At this point, we know that the elements of the input vector constant are
  39. /// all simple integer or FP values.
  40. static Constant *BitCastConstantVector(Constant *CV, VectorType *DstTy) {
  41. if (CV->isAllOnesValue()) return Constant::getAllOnesValue(DstTy);
  42. if (CV->isNullValue()) return Constant::getNullValue(DstTy);
  43. // Do not iterate on scalable vector. The num of elements is unknown at
  44. // compile-time.
  45. if (isa<ScalableVectorType>(DstTy))
  46. return nullptr;
  47. // If this cast changes element count then we can't handle it here:
  48. // doing so requires endianness information. This should be handled by
  49. // Analysis/ConstantFolding.cpp
  50. unsigned NumElts = cast<FixedVectorType>(DstTy)->getNumElements();
  51. if (NumElts != cast<FixedVectorType>(CV->getType())->getNumElements())
  52. return nullptr;
  53. Type *DstEltTy = DstTy->getElementType();
  54. // Fast path for splatted constants.
  55. if (Constant *Splat = CV->getSplatValue()) {
  56. return ConstantVector::getSplat(DstTy->getElementCount(),
  57. ConstantExpr::getBitCast(Splat, DstEltTy));
  58. }
  59. SmallVector<Constant*, 16> Result;
  60. Type *Ty = IntegerType::get(CV->getContext(), 32);
  61. for (unsigned i = 0; i != NumElts; ++i) {
  62. Constant *C =
  63. ConstantExpr::getExtractElement(CV, ConstantInt::get(Ty, i));
  64. C = ConstantExpr::getBitCast(C, DstEltTy);
  65. Result.push_back(C);
  66. }
  67. return ConstantVector::get(Result);
  68. }
  69. /// This function determines which opcode to use to fold two constant cast
  70. /// expressions together. It uses CastInst::isEliminableCastPair to determine
  71. /// the opcode. Consequently its just a wrapper around that function.
  72. /// Determine if it is valid to fold a cast of a cast
  73. static unsigned
  74. foldConstantCastPair(
  75. unsigned opc, ///< opcode of the second cast constant expression
  76. ConstantExpr *Op, ///< the first cast constant expression
  77. Type *DstTy ///< destination type of the first cast
  78. ) {
  79. assert(Op && Op->isCast() && "Can't fold cast of cast without a cast!");
  80. assert(DstTy && DstTy->isFirstClassType() && "Invalid cast destination type");
  81. assert(CastInst::isCast(opc) && "Invalid cast opcode");
  82. // The types and opcodes for the two Cast constant expressions
  83. Type *SrcTy = Op->getOperand(0)->getType();
  84. Type *MidTy = Op->getType();
  85. Instruction::CastOps firstOp = Instruction::CastOps(Op->getOpcode());
  86. Instruction::CastOps secondOp = Instruction::CastOps(opc);
  87. // Assume that pointers are never more than 64 bits wide, and only use this
  88. // for the middle type. Otherwise we could end up folding away illegal
  89. // bitcasts between address spaces with different sizes.
  90. IntegerType *FakeIntPtrTy = Type::getInt64Ty(DstTy->getContext());
  91. // Let CastInst::isEliminableCastPair do the heavy lifting.
  92. return CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy, DstTy,
  93. nullptr, FakeIntPtrTy, nullptr);
  94. }
  95. static Constant *FoldBitCast(Constant *V, Type *DestTy) {
  96. Type *SrcTy = V->getType();
  97. if (SrcTy == DestTy)
  98. return V; // no-op cast
  99. // Check to see if we are casting a pointer to an aggregate to a pointer to
  100. // the first element. If so, return the appropriate GEP instruction.
  101. if (PointerType *PTy = dyn_cast<PointerType>(V->getType()))
  102. if (PointerType *DPTy = dyn_cast<PointerType>(DestTy))
  103. if (PTy->getAddressSpace() == DPTy->getAddressSpace() &&
  104. !PTy->isOpaque() && !DPTy->isOpaque() &&
  105. PTy->getNonOpaquePointerElementType()->isSized()) {
  106. SmallVector<Value*, 8> IdxList;
  107. Value *Zero =
  108. Constant::getNullValue(Type::getInt32Ty(DPTy->getContext()));
  109. IdxList.push_back(Zero);
  110. Type *ElTy = PTy->getNonOpaquePointerElementType();
  111. while (ElTy && ElTy != DPTy->getNonOpaquePointerElementType()) {
  112. ElTy = GetElementPtrInst::getTypeAtIndex(ElTy, (uint64_t)0);
  113. IdxList.push_back(Zero);
  114. }
  115. if (ElTy == DPTy->getNonOpaquePointerElementType())
  116. // This GEP is inbounds because all indices are zero.
  117. return ConstantExpr::getInBoundsGetElementPtr(
  118. PTy->getNonOpaquePointerElementType(), V, IdxList);
  119. }
  120. // Handle casts from one vector constant to another. We know that the src
  121. // and dest type have the same size (otherwise its an illegal cast).
  122. if (VectorType *DestPTy = dyn_cast<VectorType>(DestTy)) {
  123. if (VectorType *SrcTy = dyn_cast<VectorType>(V->getType())) {
  124. assert(DestPTy->getPrimitiveSizeInBits() ==
  125. SrcTy->getPrimitiveSizeInBits() &&
  126. "Not cast between same sized vectors!");
  127. SrcTy = nullptr;
  128. // First, check for null. Undef is already handled.
  129. if (isa<ConstantAggregateZero>(V))
  130. return Constant::getNullValue(DestTy);
  131. // Handle ConstantVector and ConstantAggregateVector.
  132. return BitCastConstantVector(V, DestPTy);
  133. }
  134. // Canonicalize scalar-to-vector bitcasts into vector-to-vector bitcasts
  135. // This allows for other simplifications (although some of them
  136. // can only be handled by Analysis/ConstantFolding.cpp).
  137. if (isa<ConstantInt>(V) || isa<ConstantFP>(V))
  138. return ConstantExpr::getBitCast(ConstantVector::get(V), DestPTy);
  139. }
  140. // Finally, implement bitcast folding now. The code below doesn't handle
  141. // bitcast right.
  142. if (isa<ConstantPointerNull>(V)) // ptr->ptr cast.
  143. return ConstantPointerNull::get(cast<PointerType>(DestTy));
  144. // Handle integral constant input.
  145. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  146. if (DestTy->isIntegerTy())
  147. // Integral -> Integral. This is a no-op because the bit widths must
  148. // be the same. Consequently, we just fold to V.
  149. return V;
  150. // See note below regarding the PPC_FP128 restriction.
  151. if (DestTy->isFloatingPointTy() && !DestTy->isPPC_FP128Ty())
  152. return ConstantFP::get(DestTy->getContext(),
  153. APFloat(DestTy->getFltSemantics(),
  154. CI->getValue()));
  155. // Otherwise, can't fold this (vector?)
  156. return nullptr;
  157. }
  158. // Handle ConstantFP input: FP -> Integral.
  159. if (ConstantFP *FP = dyn_cast<ConstantFP>(V)) {
  160. // PPC_FP128 is really the sum of two consecutive doubles, where the first
  161. // double is always stored first in memory, regardless of the target
  162. // endianness. The memory layout of i128, however, depends on the target
  163. // endianness, and so we can't fold this without target endianness
  164. // information. This should instead be handled by
  165. // Analysis/ConstantFolding.cpp
  166. if (FP->getType()->isPPC_FP128Ty())
  167. return nullptr;
  168. // Make sure dest type is compatible with the folded integer constant.
  169. if (!DestTy->isIntegerTy())
  170. return nullptr;
  171. return ConstantInt::get(FP->getContext(),
  172. FP->getValueAPF().bitcastToAPInt());
  173. }
  174. return nullptr;
  175. }
  176. /// V is an integer constant which only has a subset of its bytes used.
  177. /// The bytes used are indicated by ByteStart (which is the first byte used,
  178. /// counting from the least significant byte) and ByteSize, which is the number
  179. /// of bytes used.
  180. ///
  181. /// This function analyzes the specified constant to see if the specified byte
  182. /// range can be returned as a simplified constant. If so, the constant is
  183. /// returned, otherwise null is returned.
  184. static Constant *ExtractConstantBytes(Constant *C, unsigned ByteStart,
  185. unsigned ByteSize) {
  186. assert(C->getType()->isIntegerTy() &&
  187. (cast<IntegerType>(C->getType())->getBitWidth() & 7) == 0 &&
  188. "Non-byte sized integer input");
  189. unsigned CSize = cast<IntegerType>(C->getType())->getBitWidth()/8;
  190. assert(ByteSize && "Must be accessing some piece");
  191. assert(ByteStart+ByteSize <= CSize && "Extracting invalid piece from input");
  192. assert(ByteSize != CSize && "Should not extract everything");
  193. // Constant Integers are simple.
  194. if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
  195. APInt V = CI->getValue();
  196. if (ByteStart)
  197. V.lshrInPlace(ByteStart*8);
  198. V = V.trunc(ByteSize*8);
  199. return ConstantInt::get(CI->getContext(), V);
  200. }
  201. // In the input is a constant expr, we might be able to recursively simplify.
  202. // If not, we definitely can't do anything.
  203. ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
  204. if (!CE) return nullptr;
  205. switch (CE->getOpcode()) {
  206. default: return nullptr;
  207. case Instruction::Or: {
  208. Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
  209. if (!RHS)
  210. return nullptr;
  211. // X | -1 -> -1.
  212. if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS))
  213. if (RHSC->isMinusOne())
  214. return RHSC;
  215. Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
  216. if (!LHS)
  217. return nullptr;
  218. return ConstantExpr::getOr(LHS, RHS);
  219. }
  220. case Instruction::And: {
  221. Constant *RHS = ExtractConstantBytes(CE->getOperand(1), ByteStart,ByteSize);
  222. if (!RHS)
  223. return nullptr;
  224. // X & 0 -> 0.
  225. if (RHS->isNullValue())
  226. return RHS;
  227. Constant *LHS = ExtractConstantBytes(CE->getOperand(0), ByteStart,ByteSize);
  228. if (!LHS)
  229. return nullptr;
  230. return ConstantExpr::getAnd(LHS, RHS);
  231. }
  232. case Instruction::LShr: {
  233. ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
  234. if (!Amt)
  235. return nullptr;
  236. APInt ShAmt = Amt->getValue();
  237. // Cannot analyze non-byte shifts.
  238. if ((ShAmt & 7) != 0)
  239. return nullptr;
  240. ShAmt.lshrInPlace(3);
  241. // If the extract is known to be all zeros, return zero.
  242. if (ShAmt.uge(CSize - ByteStart))
  243. return Constant::getNullValue(
  244. IntegerType::get(CE->getContext(), ByteSize * 8));
  245. // If the extract is known to be fully in the input, extract it.
  246. if (ShAmt.ule(CSize - (ByteStart + ByteSize)))
  247. return ExtractConstantBytes(CE->getOperand(0),
  248. ByteStart + ShAmt.getZExtValue(), ByteSize);
  249. // TODO: Handle the 'partially zero' case.
  250. return nullptr;
  251. }
  252. case Instruction::Shl: {
  253. ConstantInt *Amt = dyn_cast<ConstantInt>(CE->getOperand(1));
  254. if (!Amt)
  255. return nullptr;
  256. APInt ShAmt = Amt->getValue();
  257. // Cannot analyze non-byte shifts.
  258. if ((ShAmt & 7) != 0)
  259. return nullptr;
  260. ShAmt.lshrInPlace(3);
  261. // If the extract is known to be all zeros, return zero.
  262. if (ShAmt.uge(ByteStart + ByteSize))
  263. return Constant::getNullValue(
  264. IntegerType::get(CE->getContext(), ByteSize * 8));
  265. // If the extract is known to be fully in the input, extract it.
  266. if (ShAmt.ule(ByteStart))
  267. return ExtractConstantBytes(CE->getOperand(0),
  268. ByteStart - ShAmt.getZExtValue(), ByteSize);
  269. // TODO: Handle the 'partially zero' case.
  270. return nullptr;
  271. }
  272. case Instruction::ZExt: {
  273. unsigned SrcBitSize =
  274. cast<IntegerType>(CE->getOperand(0)->getType())->getBitWidth();
  275. // If extracting something that is completely zero, return 0.
  276. if (ByteStart*8 >= SrcBitSize)
  277. return Constant::getNullValue(IntegerType::get(CE->getContext(),
  278. ByteSize*8));
  279. // If exactly extracting the input, return it.
  280. if (ByteStart == 0 && ByteSize*8 == SrcBitSize)
  281. return CE->getOperand(0);
  282. // If extracting something completely in the input, if the input is a
  283. // multiple of 8 bits, recurse.
  284. if ((SrcBitSize&7) == 0 && (ByteStart+ByteSize)*8 <= SrcBitSize)
  285. return ExtractConstantBytes(CE->getOperand(0), ByteStart, ByteSize);
  286. // Otherwise, if extracting a subset of the input, which is not multiple of
  287. // 8 bits, do a shift and trunc to get the bits.
  288. if ((ByteStart+ByteSize)*8 < SrcBitSize) {
  289. assert((SrcBitSize&7) && "Shouldn't get byte sized case here");
  290. Constant *Res = CE->getOperand(0);
  291. if (ByteStart)
  292. Res = ConstantExpr::getLShr(Res,
  293. ConstantInt::get(Res->getType(), ByteStart*8));
  294. return ConstantExpr::getTrunc(Res, IntegerType::get(C->getContext(),
  295. ByteSize*8));
  296. }
  297. // TODO: Handle the 'partially zero' case.
  298. return nullptr;
  299. }
  300. }
  301. }
  302. Constant *llvm::ConstantFoldCastInstruction(unsigned opc, Constant *V,
  303. Type *DestTy) {
  304. if (isa<PoisonValue>(V))
  305. return PoisonValue::get(DestTy);
  306. if (isa<UndefValue>(V)) {
  307. // zext(undef) = 0, because the top bits will be zero.
  308. // sext(undef) = 0, because the top bits will all be the same.
  309. // [us]itofp(undef) = 0, because the result value is bounded.
  310. if (opc == Instruction::ZExt || opc == Instruction::SExt ||
  311. opc == Instruction::UIToFP || opc == Instruction::SIToFP)
  312. return Constant::getNullValue(DestTy);
  313. return UndefValue::get(DestTy);
  314. }
  315. if (V->isNullValue() && !DestTy->isX86_MMXTy() && !DestTy->isX86_AMXTy() &&
  316. opc != Instruction::AddrSpaceCast)
  317. return Constant::getNullValue(DestTy);
  318. // If the cast operand is a constant expression, there's a few things we can
  319. // do to try to simplify it.
  320. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
  321. if (CE->isCast()) {
  322. // Try hard to fold cast of cast because they are often eliminable.
  323. if (unsigned newOpc = foldConstantCastPair(opc, CE, DestTy))
  324. return ConstantExpr::getCast(newOpc, CE->getOperand(0), DestTy);
  325. } else if (CE->getOpcode() == Instruction::GetElementPtr &&
  326. // Do not fold addrspacecast (gep 0, .., 0). It might make the
  327. // addrspacecast uncanonicalized.
  328. opc != Instruction::AddrSpaceCast &&
  329. // Do not fold bitcast (gep) with inrange index, as this loses
  330. // information.
  331. !cast<GEPOperator>(CE)->getInRangeIndex() &&
  332. // Do not fold if the gep type is a vector, as bitcasting
  333. // operand 0 of a vector gep will result in a bitcast between
  334. // different sizes.
  335. !CE->getType()->isVectorTy()) {
  336. // If all of the indexes in the GEP are null values, there is no pointer
  337. // adjustment going on. We might as well cast the source pointer.
  338. bool isAllNull = true;
  339. for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
  340. if (!CE->getOperand(i)->isNullValue()) {
  341. isAllNull = false;
  342. break;
  343. }
  344. if (isAllNull)
  345. // This is casting one pointer type to another, always BitCast
  346. return ConstantExpr::getPointerCast(CE->getOperand(0), DestTy);
  347. }
  348. }
  349. // If the cast operand is a constant vector, perform the cast by
  350. // operating on each element. In the cast of bitcasts, the element
  351. // count may be mismatched; don't attempt to handle that here.
  352. if ((isa<ConstantVector>(V) || isa<ConstantDataVector>(V)) &&
  353. DestTy->isVectorTy() &&
  354. cast<FixedVectorType>(DestTy)->getNumElements() ==
  355. cast<FixedVectorType>(V->getType())->getNumElements()) {
  356. VectorType *DestVecTy = cast<VectorType>(DestTy);
  357. Type *DstEltTy = DestVecTy->getElementType();
  358. // Fast path for splatted constants.
  359. if (Constant *Splat = V->getSplatValue()) {
  360. return ConstantVector::getSplat(
  361. cast<VectorType>(DestTy)->getElementCount(),
  362. ConstantExpr::getCast(opc, Splat, DstEltTy));
  363. }
  364. SmallVector<Constant *, 16> res;
  365. Type *Ty = IntegerType::get(V->getContext(), 32);
  366. for (unsigned i = 0,
  367. e = cast<FixedVectorType>(V->getType())->getNumElements();
  368. i != e; ++i) {
  369. Constant *C =
  370. ConstantExpr::getExtractElement(V, ConstantInt::get(Ty, i));
  371. res.push_back(ConstantExpr::getCast(opc, C, DstEltTy));
  372. }
  373. return ConstantVector::get(res);
  374. }
  375. // We actually have to do a cast now. Perform the cast according to the
  376. // opcode specified.
  377. switch (opc) {
  378. default:
  379. llvm_unreachable("Failed to cast constant expression");
  380. case Instruction::FPTrunc:
  381. case Instruction::FPExt:
  382. if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
  383. bool ignored;
  384. APFloat Val = FPC->getValueAPF();
  385. Val.convert(DestTy->getFltSemantics(), APFloat::rmNearestTiesToEven,
  386. &ignored);
  387. return ConstantFP::get(V->getContext(), Val);
  388. }
  389. return nullptr; // Can't fold.
  390. case Instruction::FPToUI:
  391. case Instruction::FPToSI:
  392. if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
  393. const APFloat &V = FPC->getValueAPF();
  394. bool ignored;
  395. uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  396. APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
  397. if (APFloat::opInvalidOp ==
  398. V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
  399. // Undefined behavior invoked - the destination type can't represent
  400. // the input constant.
  401. return PoisonValue::get(DestTy);
  402. }
  403. return ConstantInt::get(FPC->getContext(), IntVal);
  404. }
  405. return nullptr; // Can't fold.
  406. case Instruction::IntToPtr: //always treated as unsigned
  407. if (V->isNullValue()) // Is it an integral null value?
  408. return ConstantPointerNull::get(cast<PointerType>(DestTy));
  409. return nullptr; // Other pointer types cannot be casted
  410. case Instruction::PtrToInt: // always treated as unsigned
  411. // Is it a null pointer value?
  412. if (V->isNullValue())
  413. return ConstantInt::get(DestTy, 0);
  414. // Other pointer types cannot be casted
  415. return nullptr;
  416. case Instruction::UIToFP:
  417. case Instruction::SIToFP:
  418. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  419. const APInt &api = CI->getValue();
  420. APFloat apf(DestTy->getFltSemantics(),
  421. APInt::getZero(DestTy->getPrimitiveSizeInBits()));
  422. apf.convertFromAPInt(api, opc==Instruction::SIToFP,
  423. APFloat::rmNearestTiesToEven);
  424. return ConstantFP::get(V->getContext(), apf);
  425. }
  426. return nullptr;
  427. case Instruction::ZExt:
  428. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  429. uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  430. return ConstantInt::get(V->getContext(),
  431. CI->getValue().zext(BitWidth));
  432. }
  433. return nullptr;
  434. case Instruction::SExt:
  435. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  436. uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  437. return ConstantInt::get(V->getContext(),
  438. CI->getValue().sext(BitWidth));
  439. }
  440. return nullptr;
  441. case Instruction::Trunc: {
  442. if (V->getType()->isVectorTy())
  443. return nullptr;
  444. uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  445. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  446. return ConstantInt::get(V->getContext(),
  447. CI->getValue().trunc(DestBitWidth));
  448. }
  449. // The input must be a constantexpr. See if we can simplify this based on
  450. // the bytes we are demanding. Only do this if the source and dest are an
  451. // even multiple of a byte.
  452. if ((DestBitWidth & 7) == 0 &&
  453. (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
  454. if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
  455. return Res;
  456. return nullptr;
  457. }
  458. case Instruction::BitCast:
  459. return FoldBitCast(V, DestTy);
  460. case Instruction::AddrSpaceCast:
  461. return nullptr;
  462. }
  463. }
  464. Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
  465. Constant *V1, Constant *V2) {
  466. // Check for i1 and vector true/false conditions.
  467. if (Cond->isNullValue()) return V2;
  468. if (Cond->isAllOnesValue()) return V1;
  469. // If the condition is a vector constant, fold the result elementwise.
  470. if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
  471. auto *V1VTy = CondV->getType();
  472. SmallVector<Constant*, 16> Result;
  473. Type *Ty = IntegerType::get(CondV->getContext(), 32);
  474. for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
  475. Constant *V;
  476. Constant *V1Element = ConstantExpr::getExtractElement(V1,
  477. ConstantInt::get(Ty, i));
  478. Constant *V2Element = ConstantExpr::getExtractElement(V2,
  479. ConstantInt::get(Ty, i));
  480. auto *Cond = cast<Constant>(CondV->getOperand(i));
  481. if (isa<PoisonValue>(Cond)) {
  482. V = PoisonValue::get(V1Element->getType());
  483. } else if (V1Element == V2Element) {
  484. V = V1Element;
  485. } else if (isa<UndefValue>(Cond)) {
  486. V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
  487. } else {
  488. if (!isa<ConstantInt>(Cond)) break;
  489. V = Cond->isNullValue() ? V2Element : V1Element;
  490. }
  491. Result.push_back(V);
  492. }
  493. // If we were able to build the vector, return it.
  494. if (Result.size() == V1VTy->getNumElements())
  495. return ConstantVector::get(Result);
  496. }
  497. if (isa<PoisonValue>(Cond))
  498. return PoisonValue::get(V1->getType());
  499. if (isa<UndefValue>(Cond)) {
  500. if (isa<UndefValue>(V1)) return V1;
  501. return V2;
  502. }
  503. if (V1 == V2) return V1;
  504. if (isa<PoisonValue>(V1))
  505. return V2;
  506. if (isa<PoisonValue>(V2))
  507. return V1;
  508. // If the true or false value is undef, we can fold to the other value as
  509. // long as the other value isn't poison.
  510. auto NotPoison = [](Constant *C) {
  511. if (isa<PoisonValue>(C))
  512. return false;
  513. // TODO: We can analyze ConstExpr by opcode to determine if there is any
  514. // possibility of poison.
  515. if (isa<ConstantExpr>(C))
  516. return false;
  517. if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(C) ||
  518. isa<ConstantPointerNull>(C) || isa<Function>(C))
  519. return true;
  520. if (C->getType()->isVectorTy())
  521. return !C->containsPoisonElement() && !C->containsConstantExpression();
  522. // TODO: Recursively analyze aggregates or other constants.
  523. return false;
  524. };
  525. if (isa<UndefValue>(V1) && NotPoison(V2)) return V2;
  526. if (isa<UndefValue>(V2) && NotPoison(V1)) return V1;
  527. if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
  528. if (TrueVal->getOpcode() == Instruction::Select)
  529. if (TrueVal->getOperand(0) == Cond)
  530. return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
  531. }
  532. if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
  533. if (FalseVal->getOpcode() == Instruction::Select)
  534. if (FalseVal->getOperand(0) == Cond)
  535. return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
  536. }
  537. return nullptr;
  538. }
  539. Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
  540. Constant *Idx) {
  541. auto *ValVTy = cast<VectorType>(Val->getType());
  542. // extractelt poison, C -> poison
  543. // extractelt C, undef -> poison
  544. if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))
  545. return PoisonValue::get(ValVTy->getElementType());
  546. // extractelt undef, C -> undef
  547. if (isa<UndefValue>(Val))
  548. return UndefValue::get(ValVTy->getElementType());
  549. auto *CIdx = dyn_cast<ConstantInt>(Idx);
  550. if (!CIdx)
  551. return nullptr;
  552. if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {
  553. // ee({w,x,y,z}, wrong_value) -> poison
  554. if (CIdx->uge(ValFVTy->getNumElements()))
  555. return PoisonValue::get(ValFVTy->getElementType());
  556. }
  557. // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
  558. if (auto *CE = dyn_cast<ConstantExpr>(Val)) {
  559. if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
  560. SmallVector<Constant *, 8> Ops;
  561. Ops.reserve(CE->getNumOperands());
  562. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  563. Constant *Op = CE->getOperand(i);
  564. if (Op->getType()->isVectorTy()) {
  565. Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx);
  566. if (!ScalarOp)
  567. return nullptr;
  568. Ops.push_back(ScalarOp);
  569. } else
  570. Ops.push_back(Op);
  571. }
  572. return CE->getWithOperands(Ops, ValVTy->getElementType(), false,
  573. GEP->getSourceElementType());
  574. } else if (CE->getOpcode() == Instruction::InsertElement) {
  575. if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
  576. if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
  577. APSInt(CIdx->getValue()))) {
  578. return CE->getOperand(1);
  579. } else {
  580. return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
  581. }
  582. }
  583. }
  584. }
  585. if (Constant *C = Val->getAggregateElement(CIdx))
  586. return C;
  587. // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
  588. if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {
  589. if (Constant *SplatVal = Val->getSplatValue())
  590. return SplatVal;
  591. }
  592. return nullptr;
  593. }
  594. Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
  595. Constant *Elt,
  596. Constant *Idx) {
  597. if (isa<UndefValue>(Idx))
  598. return PoisonValue::get(Val->getType());
  599. // Inserting null into all zeros is still all zeros.
  600. // TODO: This is true for undef and poison splats too.
  601. if (isa<ConstantAggregateZero>(Val) && Elt->isNullValue())
  602. return Val;
  603. ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
  604. if (!CIdx) return nullptr;
  605. // Do not iterate on scalable vector. The num of elements is unknown at
  606. // compile-time.
  607. if (isa<ScalableVectorType>(Val->getType()))
  608. return nullptr;
  609. auto *ValTy = cast<FixedVectorType>(Val->getType());
  610. unsigned NumElts = ValTy->getNumElements();
  611. if (CIdx->uge(NumElts))
  612. return PoisonValue::get(Val->getType());
  613. SmallVector<Constant*, 16> Result;
  614. Result.reserve(NumElts);
  615. auto *Ty = Type::getInt32Ty(Val->getContext());
  616. uint64_t IdxVal = CIdx->getZExtValue();
  617. for (unsigned i = 0; i != NumElts; ++i) {
  618. if (i == IdxVal) {
  619. Result.push_back(Elt);
  620. continue;
  621. }
  622. Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
  623. Result.push_back(C);
  624. }
  625. return ConstantVector::get(Result);
  626. }
  627. Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2,
  628. ArrayRef<int> Mask) {
  629. auto *V1VTy = cast<VectorType>(V1->getType());
  630. unsigned MaskNumElts = Mask.size();
  631. auto MaskEltCount =
  632. ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
  633. Type *EltTy = V1VTy->getElementType();
  634. // Undefined shuffle mask -> undefined value.
  635. if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
  636. return UndefValue::get(VectorType::get(EltTy, MaskEltCount));
  637. }
  638. // If the mask is all zeros this is a splat, no need to go through all
  639. // elements.
  640. if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
  641. Type *Ty = IntegerType::get(V1->getContext(), 32);
  642. Constant *Elt =
  643. ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0));
  644. if (Elt->isNullValue()) {
  645. auto *VTy = VectorType::get(EltTy, MaskEltCount);
  646. return ConstantAggregateZero::get(VTy);
  647. } else if (!MaskEltCount.isScalable())
  648. return ConstantVector::getSplat(MaskEltCount, Elt);
  649. }
  650. // Do not iterate on scalable vector. The num of elements is unknown at
  651. // compile-time.
  652. if (isa<ScalableVectorType>(V1VTy))
  653. return nullptr;
  654. unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
  655. // Loop over the shuffle mask, evaluating each element.
  656. SmallVector<Constant*, 32> Result;
  657. for (unsigned i = 0; i != MaskNumElts; ++i) {
  658. int Elt = Mask[i];
  659. if (Elt == -1) {
  660. Result.push_back(UndefValue::get(EltTy));
  661. continue;
  662. }
  663. Constant *InElt;
  664. if (unsigned(Elt) >= SrcNumElts*2)
  665. InElt = UndefValue::get(EltTy);
  666. else if (unsigned(Elt) >= SrcNumElts) {
  667. Type *Ty = IntegerType::get(V2->getContext(), 32);
  668. InElt =
  669. ConstantExpr::getExtractElement(V2,
  670. ConstantInt::get(Ty, Elt - SrcNumElts));
  671. } else {
  672. Type *Ty = IntegerType::get(V1->getContext(), 32);
  673. InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
  674. }
  675. Result.push_back(InElt);
  676. }
  677. return ConstantVector::get(Result);
  678. }
  679. Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
  680. ArrayRef<unsigned> Idxs) {
  681. // Base case: no indices, so return the entire value.
  682. if (Idxs.empty())
  683. return Agg;
  684. if (Constant *C = Agg->getAggregateElement(Idxs[0]))
  685. return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
  686. return nullptr;
  687. }
  688. Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
  689. Constant *Val,
  690. ArrayRef<unsigned> Idxs) {
  691. // Base case: no indices, so replace the entire value.
  692. if (Idxs.empty())
  693. return Val;
  694. unsigned NumElts;
  695. if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
  696. NumElts = ST->getNumElements();
  697. else
  698. NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
  699. SmallVector<Constant*, 32> Result;
  700. for (unsigned i = 0; i != NumElts; ++i) {
  701. Constant *C = Agg->getAggregateElement(i);
  702. if (!C) return nullptr;
  703. if (Idxs[0] == i)
  704. C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
  705. Result.push_back(C);
  706. }
  707. if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
  708. return ConstantStruct::get(ST, Result);
  709. return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
  710. }
  711. Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {
  712. assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
  713. // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
  714. // vectors are always evaluated per element.
  715. bool IsScalableVector = isa<ScalableVectorType>(C->getType());
  716. bool HasScalarUndefOrScalableVectorUndef =
  717. (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
  718. if (HasScalarUndefOrScalableVectorUndef) {
  719. switch (static_cast<Instruction::UnaryOps>(Opcode)) {
  720. case Instruction::FNeg:
  721. return C; // -undef -> undef
  722. case Instruction::UnaryOpsEnd:
  723. llvm_unreachable("Invalid UnaryOp");
  724. }
  725. }
  726. // Constant should not be UndefValue, unless these are vector constants.
  727. assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
  728. // We only have FP UnaryOps right now.
  729. assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
  730. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  731. const APFloat &CV = CFP->getValueAPF();
  732. switch (Opcode) {
  733. default:
  734. break;
  735. case Instruction::FNeg:
  736. return ConstantFP::get(C->getContext(), neg(CV));
  737. }
  738. } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {
  739. Type *Ty = IntegerType::get(VTy->getContext(), 32);
  740. // Fast path for splatted constants.
  741. if (Constant *Splat = C->getSplatValue())
  742. if (Constant *Elt = ConstantFoldUnaryInstruction(Opcode, Splat))
  743. return ConstantVector::getSplat(VTy->getElementCount(), Elt);
  744. // Fold each element and create a vector constant from those constants.
  745. SmallVector<Constant *, 16> Result;
  746. for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
  747. Constant *ExtractIdx = ConstantInt::get(Ty, i);
  748. Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
  749. Constant *Res = ConstantFoldUnaryInstruction(Opcode, Elt);
  750. if (!Res)
  751. return nullptr;
  752. Result.push_back(Res);
  753. }
  754. return ConstantVector::get(Result);
  755. }
  756. // We don't know how to fold this.
  757. return nullptr;
  758. }
  759. Constant *llvm::ConstantFoldBinaryInstruction(unsigned Opcode, Constant *C1,
  760. Constant *C2) {
  761. assert(Instruction::isBinaryOp(Opcode) && "Non-binary instruction detected");
  762. // Simplify BinOps with their identity values first. They are no-ops and we
  763. // can always return the other value, including undef or poison values.
  764. // FIXME: remove unnecessary duplicated identity patterns below.
  765. // FIXME: Use AllowRHSConstant with getBinOpIdentity to handle additional ops,
  766. // like X << 0 = X.
  767. Constant *Identity = ConstantExpr::getBinOpIdentity(Opcode, C1->getType());
  768. if (Identity) {
  769. if (C1 == Identity)
  770. return C2;
  771. if (C2 == Identity)
  772. return C1;
  773. }
  774. // Binary operations propagate poison.
  775. if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
  776. return PoisonValue::get(C1->getType());
  777. // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
  778. // vectors are always evaluated per element.
  779. bool IsScalableVector = isa<ScalableVectorType>(C1->getType());
  780. bool HasScalarUndefOrScalableVectorUndef =
  781. (!C1->getType()->isVectorTy() || IsScalableVector) &&
  782. (isa<UndefValue>(C1) || isa<UndefValue>(C2));
  783. if (HasScalarUndefOrScalableVectorUndef) {
  784. switch (static_cast<Instruction::BinaryOps>(Opcode)) {
  785. case Instruction::Xor:
  786. if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
  787. // Handle undef ^ undef -> 0 special case. This is a common
  788. // idiom (misuse).
  789. return Constant::getNullValue(C1->getType());
  790. [[fallthrough]];
  791. case Instruction::Add:
  792. case Instruction::Sub:
  793. return UndefValue::get(C1->getType());
  794. case Instruction::And:
  795. if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef & undef -> undef
  796. return C1;
  797. return Constant::getNullValue(C1->getType()); // undef & X -> 0
  798. case Instruction::Mul: {
  799. // undef * undef -> undef
  800. if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
  801. return C1;
  802. const APInt *CV;
  803. // X * undef -> undef if X is odd
  804. if (match(C1, m_APInt(CV)) || match(C2, m_APInt(CV)))
  805. if ((*CV)[0])
  806. return UndefValue::get(C1->getType());
  807. // X * undef -> 0 otherwise
  808. return Constant::getNullValue(C1->getType());
  809. }
  810. case Instruction::SDiv:
  811. case Instruction::UDiv:
  812. // X / undef -> poison
  813. // X / 0 -> poison
  814. if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
  815. return PoisonValue::get(C2->getType());
  816. // undef / 1 -> undef
  817. if (match(C2, m_One()))
  818. return C1;
  819. // undef / X -> 0 otherwise
  820. return Constant::getNullValue(C1->getType());
  821. case Instruction::URem:
  822. case Instruction::SRem:
  823. // X % undef -> poison
  824. // X % 0 -> poison
  825. if (match(C2, m_CombineOr(m_Undef(), m_Zero())))
  826. return PoisonValue::get(C2->getType());
  827. // undef % X -> 0 otherwise
  828. return Constant::getNullValue(C1->getType());
  829. case Instruction::Or: // X | undef -> -1
  830. if (isa<UndefValue>(C1) && isa<UndefValue>(C2)) // undef | undef -> undef
  831. return C1;
  832. return Constant::getAllOnesValue(C1->getType()); // undef | X -> ~0
  833. case Instruction::LShr:
  834. // X >>l undef -> poison
  835. if (isa<UndefValue>(C2))
  836. return PoisonValue::get(C2->getType());
  837. // undef >>l 0 -> undef
  838. if (match(C2, m_Zero()))
  839. return C1;
  840. // undef >>l X -> 0
  841. return Constant::getNullValue(C1->getType());
  842. case Instruction::AShr:
  843. // X >>a undef -> poison
  844. if (isa<UndefValue>(C2))
  845. return PoisonValue::get(C2->getType());
  846. // undef >>a 0 -> undef
  847. if (match(C2, m_Zero()))
  848. return C1;
  849. // TODO: undef >>a X -> poison if the shift is exact
  850. // undef >>a X -> 0
  851. return Constant::getNullValue(C1->getType());
  852. case Instruction::Shl:
  853. // X << undef -> undef
  854. if (isa<UndefValue>(C2))
  855. return PoisonValue::get(C2->getType());
  856. // undef << 0 -> undef
  857. if (match(C2, m_Zero()))
  858. return C1;
  859. // undef << X -> 0
  860. return Constant::getNullValue(C1->getType());
  861. case Instruction::FSub:
  862. // -0.0 - undef --> undef (consistent with "fneg undef")
  863. if (match(C1, m_NegZeroFP()) && isa<UndefValue>(C2))
  864. return C2;
  865. [[fallthrough]];
  866. case Instruction::FAdd:
  867. case Instruction::FMul:
  868. case Instruction::FDiv:
  869. case Instruction::FRem:
  870. // [any flop] undef, undef -> undef
  871. if (isa<UndefValue>(C1) && isa<UndefValue>(C2))
  872. return C1;
  873. // [any flop] C, undef -> NaN
  874. // [any flop] undef, C -> NaN
  875. // We could potentially specialize NaN/Inf constants vs. 'normal'
  876. // constants (possibly differently depending on opcode and operand). This
  877. // would allow returning undef sometimes. But it is always safe to fold to
  878. // NaN because we can choose the undef operand as NaN, and any FP opcode
  879. // with a NaN operand will propagate NaN.
  880. return ConstantFP::getNaN(C1->getType());
  881. case Instruction::BinaryOpsEnd:
  882. llvm_unreachable("Invalid BinaryOp");
  883. }
  884. }
  885. // Neither constant should be UndefValue, unless these are vector constants.
  886. assert((!HasScalarUndefOrScalableVectorUndef) && "Unexpected UndefValue");
  887. // Handle simplifications when the RHS is a constant int.
  888. if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
  889. switch (Opcode) {
  890. case Instruction::Add:
  891. if (CI2->isZero()) return C1; // X + 0 == X
  892. break;
  893. case Instruction::Sub:
  894. if (CI2->isZero()) return C1; // X - 0 == X
  895. break;
  896. case Instruction::Mul:
  897. if (CI2->isZero()) return C2; // X * 0 == 0
  898. if (CI2->isOne())
  899. return C1; // X * 1 == X
  900. break;
  901. case Instruction::UDiv:
  902. case Instruction::SDiv:
  903. if (CI2->isOne())
  904. return C1; // X / 1 == X
  905. if (CI2->isZero())
  906. return PoisonValue::get(CI2->getType()); // X / 0 == poison
  907. break;
  908. case Instruction::URem:
  909. case Instruction::SRem:
  910. if (CI2->isOne())
  911. return Constant::getNullValue(CI2->getType()); // X % 1 == 0
  912. if (CI2->isZero())
  913. return PoisonValue::get(CI2->getType()); // X % 0 == poison
  914. break;
  915. case Instruction::And:
  916. if (CI2->isZero()) return C2; // X & 0 == 0
  917. if (CI2->isMinusOne())
  918. return C1; // X & -1 == X
  919. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  920. // (zext i32 to i64) & 4294967295 -> (zext i32 to i64)
  921. if (CE1->getOpcode() == Instruction::ZExt) {
  922. unsigned DstWidth = CI2->getType()->getBitWidth();
  923. unsigned SrcWidth =
  924. CE1->getOperand(0)->getType()->getPrimitiveSizeInBits();
  925. APInt PossiblySetBits(APInt::getLowBitsSet(DstWidth, SrcWidth));
  926. if ((PossiblySetBits & CI2->getValue()) == PossiblySetBits)
  927. return C1;
  928. }
  929. // If and'ing the address of a global with a constant, fold it.
  930. if (CE1->getOpcode() == Instruction::PtrToInt &&
  931. isa<GlobalValue>(CE1->getOperand(0))) {
  932. GlobalValue *GV = cast<GlobalValue>(CE1->getOperand(0));
  933. MaybeAlign GVAlign;
  934. if (Module *TheModule = GV->getParent()) {
  935. const DataLayout &DL = TheModule->getDataLayout();
  936. GVAlign = GV->getPointerAlignment(DL);
  937. // If the function alignment is not specified then assume that it
  938. // is 4.
  939. // This is dangerous; on x86, the alignment of the pointer
  940. // corresponds to the alignment of the function, but might be less
  941. // than 4 if it isn't explicitly specified.
  942. // However, a fix for this behaviour was reverted because it
  943. // increased code size (see https://reviews.llvm.org/D55115)
  944. // FIXME: This code should be deleted once existing targets have
  945. // appropriate defaults
  946. if (isa<Function>(GV) && !DL.getFunctionPtrAlign())
  947. GVAlign = Align(4);
  948. } else if (isa<Function>(GV)) {
  949. // Without a datalayout we have to assume the worst case: that the
  950. // function pointer isn't aligned at all.
  951. GVAlign = std::nullopt;
  952. } else if (isa<GlobalVariable>(GV)) {
  953. GVAlign = cast<GlobalVariable>(GV)->getAlign();
  954. }
  955. if (GVAlign && *GVAlign > 1) {
  956. unsigned DstWidth = CI2->getType()->getBitWidth();
  957. unsigned SrcWidth = std::min(DstWidth, Log2(*GVAlign));
  958. APInt BitsNotSet(APInt::getLowBitsSet(DstWidth, SrcWidth));
  959. // If checking bits we know are clear, return zero.
  960. if ((CI2->getValue() & BitsNotSet) == CI2->getValue())
  961. return Constant::getNullValue(CI2->getType());
  962. }
  963. }
  964. }
  965. break;
  966. case Instruction::Or:
  967. if (CI2->isZero()) return C1; // X | 0 == X
  968. if (CI2->isMinusOne())
  969. return C2; // X | -1 == -1
  970. break;
  971. case Instruction::Xor:
  972. if (CI2->isZero()) return C1; // X ^ 0 == X
  973. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  974. switch (CE1->getOpcode()) {
  975. default: break;
  976. case Instruction::ICmp:
  977. case Instruction::FCmp:
  978. // cmp pred ^ true -> cmp !pred
  979. assert(CI2->isOne());
  980. CmpInst::Predicate pred = (CmpInst::Predicate)CE1->getPredicate();
  981. pred = CmpInst::getInversePredicate(pred);
  982. return ConstantExpr::getCompare(pred, CE1->getOperand(0),
  983. CE1->getOperand(1));
  984. }
  985. }
  986. break;
  987. case Instruction::AShr:
  988. // ashr (zext C to Ty), C2 -> lshr (zext C, CSA), C2
  989. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1))
  990. if (CE1->getOpcode() == Instruction::ZExt) // Top bits known zero.
  991. return ConstantExpr::getLShr(C1, C2);
  992. break;
  993. }
  994. } else if (isa<ConstantInt>(C1)) {
  995. // If C1 is a ConstantInt and C2 is not, swap the operands.
  996. if (Instruction::isCommutative(Opcode))
  997. return ConstantExpr::get(Opcode, C2, C1);
  998. }
  999. if (ConstantInt *CI1 = dyn_cast<ConstantInt>(C1)) {
  1000. if (ConstantInt *CI2 = dyn_cast<ConstantInt>(C2)) {
  1001. const APInt &C1V = CI1->getValue();
  1002. const APInt &C2V = CI2->getValue();
  1003. switch (Opcode) {
  1004. default:
  1005. break;
  1006. case Instruction::Add:
  1007. return ConstantInt::get(CI1->getContext(), C1V + C2V);
  1008. case Instruction::Sub:
  1009. return ConstantInt::get(CI1->getContext(), C1V - C2V);
  1010. case Instruction::Mul:
  1011. return ConstantInt::get(CI1->getContext(), C1V * C2V);
  1012. case Instruction::UDiv:
  1013. assert(!CI2->isZero() && "Div by zero handled above");
  1014. return ConstantInt::get(CI1->getContext(), C1V.udiv(C2V));
  1015. case Instruction::SDiv:
  1016. assert(!CI2->isZero() && "Div by zero handled above");
  1017. if (C2V.isAllOnes() && C1V.isMinSignedValue())
  1018. return PoisonValue::get(CI1->getType()); // MIN_INT / -1 -> poison
  1019. return ConstantInt::get(CI1->getContext(), C1V.sdiv(C2V));
  1020. case Instruction::URem:
  1021. assert(!CI2->isZero() && "Div by zero handled above");
  1022. return ConstantInt::get(CI1->getContext(), C1V.urem(C2V));
  1023. case Instruction::SRem:
  1024. assert(!CI2->isZero() && "Div by zero handled above");
  1025. if (C2V.isAllOnes() && C1V.isMinSignedValue())
  1026. return PoisonValue::get(CI1->getType()); // MIN_INT % -1 -> poison
  1027. return ConstantInt::get(CI1->getContext(), C1V.srem(C2V));
  1028. case Instruction::And:
  1029. return ConstantInt::get(CI1->getContext(), C1V & C2V);
  1030. case Instruction::Or:
  1031. return ConstantInt::get(CI1->getContext(), C1V | C2V);
  1032. case Instruction::Xor:
  1033. return ConstantInt::get(CI1->getContext(), C1V ^ C2V);
  1034. case Instruction::Shl:
  1035. if (C2V.ult(C1V.getBitWidth()))
  1036. return ConstantInt::get(CI1->getContext(), C1V.shl(C2V));
  1037. return PoisonValue::get(C1->getType()); // too big shift is poison
  1038. case Instruction::LShr:
  1039. if (C2V.ult(C1V.getBitWidth()))
  1040. return ConstantInt::get(CI1->getContext(), C1V.lshr(C2V));
  1041. return PoisonValue::get(C1->getType()); // too big shift is poison
  1042. case Instruction::AShr:
  1043. if (C2V.ult(C1V.getBitWidth()))
  1044. return ConstantInt::get(CI1->getContext(), C1V.ashr(C2V));
  1045. return PoisonValue::get(C1->getType()); // too big shift is poison
  1046. }
  1047. }
  1048. switch (Opcode) {
  1049. case Instruction::SDiv:
  1050. case Instruction::UDiv:
  1051. case Instruction::URem:
  1052. case Instruction::SRem:
  1053. case Instruction::LShr:
  1054. case Instruction::AShr:
  1055. case Instruction::Shl:
  1056. if (CI1->isZero()) return C1;
  1057. break;
  1058. default:
  1059. break;
  1060. }
  1061. } else if (ConstantFP *CFP1 = dyn_cast<ConstantFP>(C1)) {
  1062. if (ConstantFP *CFP2 = dyn_cast<ConstantFP>(C2)) {
  1063. const APFloat &C1V = CFP1->getValueAPF();
  1064. const APFloat &C2V = CFP2->getValueAPF();
  1065. APFloat C3V = C1V; // copy for modification
  1066. switch (Opcode) {
  1067. default:
  1068. break;
  1069. case Instruction::FAdd:
  1070. (void)C3V.add(C2V, APFloat::rmNearestTiesToEven);
  1071. return ConstantFP::get(C1->getContext(), C3V);
  1072. case Instruction::FSub:
  1073. (void)C3V.subtract(C2V, APFloat::rmNearestTiesToEven);
  1074. return ConstantFP::get(C1->getContext(), C3V);
  1075. case Instruction::FMul:
  1076. (void)C3V.multiply(C2V, APFloat::rmNearestTiesToEven);
  1077. return ConstantFP::get(C1->getContext(), C3V);
  1078. case Instruction::FDiv:
  1079. (void)C3V.divide(C2V, APFloat::rmNearestTiesToEven);
  1080. return ConstantFP::get(C1->getContext(), C3V);
  1081. case Instruction::FRem:
  1082. (void)C3V.mod(C2V);
  1083. return ConstantFP::get(C1->getContext(), C3V);
  1084. }
  1085. }
  1086. } else if (auto *VTy = dyn_cast<VectorType>(C1->getType())) {
  1087. // Fast path for splatted constants.
  1088. if (Constant *C2Splat = C2->getSplatValue()) {
  1089. if (Instruction::isIntDivRem(Opcode) && C2Splat->isNullValue())
  1090. return PoisonValue::get(VTy);
  1091. if (Constant *C1Splat = C1->getSplatValue()) {
  1092. Constant *Res =
  1093. ConstantExpr::isDesirableBinOp(Opcode)
  1094. ? ConstantExpr::get(Opcode, C1Splat, C2Splat)
  1095. : ConstantFoldBinaryInstruction(Opcode, C1Splat, C2Splat);
  1096. if (!Res)
  1097. return nullptr;
  1098. return ConstantVector::getSplat(VTy->getElementCount(), Res);
  1099. }
  1100. }
  1101. if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
  1102. // Fold each element and create a vector constant from those constants.
  1103. SmallVector<Constant*, 16> Result;
  1104. Type *Ty = IntegerType::get(FVTy->getContext(), 32);
  1105. for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
  1106. Constant *ExtractIdx = ConstantInt::get(Ty, i);
  1107. Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
  1108. Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
  1109. // If any element of a divisor vector is zero, the whole op is poison.
  1110. if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
  1111. return PoisonValue::get(VTy);
  1112. Constant *Res = ConstantExpr::isDesirableBinOp(Opcode)
  1113. ? ConstantExpr::get(Opcode, LHS, RHS)
  1114. : ConstantFoldBinaryInstruction(Opcode, LHS, RHS);
  1115. if (!Res)
  1116. return nullptr;
  1117. Result.push_back(Res);
  1118. }
  1119. return ConstantVector::get(Result);
  1120. }
  1121. }
  1122. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1123. // There are many possible foldings we could do here. We should probably
  1124. // at least fold add of a pointer with an integer into the appropriate
  1125. // getelementptr. This will improve alias analysis a bit.
  1126. // Given ((a + b) + c), if (b + c) folds to something interesting, return
  1127. // (a + (b + c)).
  1128. if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
  1129. Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
  1130. if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
  1131. return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
  1132. }
  1133. } else if (isa<ConstantExpr>(C2)) {
  1134. // If C2 is a constant expr and C1 isn't, flop them around and fold the
  1135. // other way if possible.
  1136. if (Instruction::isCommutative(Opcode))
  1137. return ConstantFoldBinaryInstruction(Opcode, C2, C1);
  1138. }
  1139. // i1 can be simplified in many cases.
  1140. if (C1->getType()->isIntegerTy(1)) {
  1141. switch (Opcode) {
  1142. case Instruction::Add:
  1143. case Instruction::Sub:
  1144. return ConstantExpr::getXor(C1, C2);
  1145. case Instruction::Mul:
  1146. return ConstantExpr::getAnd(C1, C2);
  1147. case Instruction::Shl:
  1148. case Instruction::LShr:
  1149. case Instruction::AShr:
  1150. // We can assume that C2 == 0. If it were one the result would be
  1151. // undefined because the shift value is as large as the bitwidth.
  1152. return C1;
  1153. case Instruction::SDiv:
  1154. case Instruction::UDiv:
  1155. // We can assume that C2 == 1. If it were zero the result would be
  1156. // undefined through division by zero.
  1157. return C1;
  1158. case Instruction::URem:
  1159. case Instruction::SRem:
  1160. // We can assume that C2 == 1. If it were zero the result would be
  1161. // undefined through division by zero.
  1162. return ConstantInt::getFalse(C1->getContext());
  1163. default:
  1164. break;
  1165. }
  1166. }
  1167. // We don't know how to fold this.
  1168. return nullptr;
  1169. }
  1170. /// This function determines if there is anything we can decide about the two
  1171. /// constants provided. This doesn't need to handle simple things like
  1172. /// ConstantFP comparisons, but should instead handle ConstantExprs.
  1173. /// If we can determine that the two constants have a particular relation to
  1174. /// each other, we should return the corresponding FCmpInst predicate,
  1175. /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
  1176. /// ConstantFoldCompareInstruction.
  1177. ///
  1178. /// To simplify this code we canonicalize the relation so that the first
  1179. /// operand is always the most "complex" of the two. We consider ConstantFP
  1180. /// to be the simplest, and ConstantExprs to be the most complex.
  1181. static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
  1182. assert(V1->getType() == V2->getType() &&
  1183. "Cannot compare values of different types!");
  1184. // We do not know if a constant expression will evaluate to a number or NaN.
  1185. // Therefore, we can only say that the relation is unordered or equal.
  1186. if (V1 == V2) return FCmpInst::FCMP_UEQ;
  1187. if (!isa<ConstantExpr>(V1)) {
  1188. if (!isa<ConstantExpr>(V2)) {
  1189. // Simple case, use the standard constant folder.
  1190. ConstantInt *R = nullptr;
  1191. R = dyn_cast<ConstantInt>(
  1192. ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
  1193. if (R && !R->isZero())
  1194. return FCmpInst::FCMP_OEQ;
  1195. R = dyn_cast<ConstantInt>(
  1196. ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
  1197. if (R && !R->isZero())
  1198. return FCmpInst::FCMP_OLT;
  1199. R = dyn_cast<ConstantInt>(
  1200. ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
  1201. if (R && !R->isZero())
  1202. return FCmpInst::FCMP_OGT;
  1203. // Nothing more we can do
  1204. return FCmpInst::BAD_FCMP_PREDICATE;
  1205. }
  1206. // If the first operand is simple and second is ConstantExpr, swap operands.
  1207. FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
  1208. if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
  1209. return FCmpInst::getSwappedPredicate(SwappedRelation);
  1210. } else {
  1211. // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
  1212. // constantexpr or a simple constant.
  1213. ConstantExpr *CE1 = cast<ConstantExpr>(V1);
  1214. switch (CE1->getOpcode()) {
  1215. case Instruction::FPTrunc:
  1216. case Instruction::FPExt:
  1217. case Instruction::UIToFP:
  1218. case Instruction::SIToFP:
  1219. // We might be able to do something with these but we don't right now.
  1220. break;
  1221. default:
  1222. break;
  1223. }
  1224. }
  1225. // There are MANY other foldings that we could perform here. They will
  1226. // probably be added on demand, as they seem needed.
  1227. return FCmpInst::BAD_FCMP_PREDICATE;
  1228. }
  1229. static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
  1230. const GlobalValue *GV2) {
  1231. auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
  1232. if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
  1233. return true;
  1234. if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
  1235. Type *Ty = GVar->getValueType();
  1236. // A global with opaque type might end up being zero sized.
  1237. if (!Ty->isSized())
  1238. return true;
  1239. // A global with an empty type might lie at the address of any other
  1240. // global.
  1241. if (Ty->isEmptyTy())
  1242. return true;
  1243. }
  1244. return false;
  1245. };
  1246. // Don't try to decide equality of aliases.
  1247. if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
  1248. if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
  1249. return ICmpInst::ICMP_NE;
  1250. return ICmpInst::BAD_ICMP_PREDICATE;
  1251. }
  1252. /// This function determines if there is anything we can decide about the two
  1253. /// constants provided. This doesn't need to handle simple things like integer
  1254. /// comparisons, but should instead handle ConstantExprs and GlobalValues.
  1255. /// If we can determine that the two constants have a particular relation to
  1256. /// each other, we should return the corresponding ICmp predicate, otherwise
  1257. /// return ICmpInst::BAD_ICMP_PREDICATE.
  1258. ///
  1259. /// To simplify this code we canonicalize the relation so that the first
  1260. /// operand is always the most "complex" of the two. We consider simple
  1261. /// constants (like ConstantInt) to be the simplest, followed by
  1262. /// GlobalValues, followed by ConstantExpr's (the most complex).
  1263. ///
  1264. static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
  1265. bool isSigned) {
  1266. assert(V1->getType() == V2->getType() &&
  1267. "Cannot compare different types of values!");
  1268. if (V1 == V2) return ICmpInst::ICMP_EQ;
  1269. if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
  1270. !isa<BlockAddress>(V1)) {
  1271. if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
  1272. !isa<BlockAddress>(V2)) {
  1273. // We distilled this down to a simple case, use the standard constant
  1274. // folder.
  1275. ConstantInt *R = nullptr;
  1276. ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
  1277. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1278. if (R && !R->isZero())
  1279. return pred;
  1280. pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  1281. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1282. if (R && !R->isZero())
  1283. return pred;
  1284. pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  1285. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1286. if (R && !R->isZero())
  1287. return pred;
  1288. // If we couldn't figure it out, bail.
  1289. return ICmpInst::BAD_ICMP_PREDICATE;
  1290. }
  1291. // If the first operand is simple, swap operands.
  1292. ICmpInst::Predicate SwappedRelation =
  1293. evaluateICmpRelation(V2, V1, isSigned);
  1294. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1295. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1296. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
  1297. if (isa<ConstantExpr>(V2)) { // Swap as necessary.
  1298. ICmpInst::Predicate SwappedRelation =
  1299. evaluateICmpRelation(V2, V1, isSigned);
  1300. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1301. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1302. return ICmpInst::BAD_ICMP_PREDICATE;
  1303. }
  1304. // Now we know that the RHS is a GlobalValue, BlockAddress or simple
  1305. // constant (which, since the types must match, means that it's a
  1306. // ConstantPointerNull).
  1307. if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
  1308. return areGlobalsPotentiallyEqual(GV, GV2);
  1309. } else if (isa<BlockAddress>(V2)) {
  1310. return ICmpInst::ICMP_NE; // Globals never equal labels.
  1311. } else {
  1312. assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
  1313. // GlobalVals can never be null unless they have external weak linkage.
  1314. // We don't try to evaluate aliases here.
  1315. // NOTE: We should not be doing this constant folding if null pointer
  1316. // is considered valid for the function. But currently there is no way to
  1317. // query it from the Constant type.
  1318. if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
  1319. !NullPointerIsDefined(nullptr /* F */,
  1320. GV->getType()->getAddressSpace()))
  1321. return ICmpInst::ICMP_UGT;
  1322. }
  1323. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
  1324. if (isa<ConstantExpr>(V2)) { // Swap as necessary.
  1325. ICmpInst::Predicate SwappedRelation =
  1326. evaluateICmpRelation(V2, V1, isSigned);
  1327. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1328. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1329. return ICmpInst::BAD_ICMP_PREDICATE;
  1330. }
  1331. // Now we know that the RHS is a GlobalValue, BlockAddress or simple
  1332. // constant (which, since the types must match, means that it is a
  1333. // ConstantPointerNull).
  1334. if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
  1335. // Block address in another function can't equal this one, but block
  1336. // addresses in the current function might be the same if blocks are
  1337. // empty.
  1338. if (BA2->getFunction() != BA->getFunction())
  1339. return ICmpInst::ICMP_NE;
  1340. } else {
  1341. // Block addresses aren't null, don't equal the address of globals.
  1342. assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
  1343. "Canonicalization guarantee!");
  1344. return ICmpInst::ICMP_NE;
  1345. }
  1346. } else {
  1347. // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
  1348. // constantexpr, a global, block address, or a simple constant.
  1349. ConstantExpr *CE1 = cast<ConstantExpr>(V1);
  1350. Constant *CE1Op0 = CE1->getOperand(0);
  1351. switch (CE1->getOpcode()) {
  1352. case Instruction::Trunc:
  1353. case Instruction::FPTrunc:
  1354. case Instruction::FPExt:
  1355. case Instruction::FPToUI:
  1356. case Instruction::FPToSI:
  1357. break; // We can't evaluate floating point casts or truncations.
  1358. case Instruction::BitCast:
  1359. // If this is a global value cast, check to see if the RHS is also a
  1360. // GlobalValue.
  1361. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0))
  1362. if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2))
  1363. return areGlobalsPotentiallyEqual(GV, GV2);
  1364. [[fallthrough]];
  1365. case Instruction::UIToFP:
  1366. case Instruction::SIToFP:
  1367. case Instruction::ZExt:
  1368. case Instruction::SExt:
  1369. // We can't evaluate floating point casts or truncations.
  1370. if (CE1Op0->getType()->isFPOrFPVectorTy())
  1371. break;
  1372. // If the cast is not actually changing bits, and the second operand is a
  1373. // null pointer, do the comparison with the pre-casted value.
  1374. if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) {
  1375. if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
  1376. if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
  1377. return evaluateICmpRelation(CE1Op0,
  1378. Constant::getNullValue(CE1Op0->getType()),
  1379. isSigned);
  1380. }
  1381. break;
  1382. case Instruction::GetElementPtr: {
  1383. GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
  1384. // Ok, since this is a getelementptr, we know that the constant has a
  1385. // pointer type. Check the various cases.
  1386. if (isa<ConstantPointerNull>(V2)) {
  1387. // If we are comparing a GEP to a null pointer, check to see if the base
  1388. // of the GEP equals the null pointer.
  1389. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
  1390. // If its not weak linkage, the GVal must have a non-zero address
  1391. // so the result is greater-than
  1392. if (!GV->hasExternalWeakLinkage() && CE1GEP->isInBounds())
  1393. return ICmpInst::ICMP_UGT;
  1394. }
  1395. } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
  1396. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
  1397. if (GV != GV2) {
  1398. if (CE1GEP->hasAllZeroIndices())
  1399. return areGlobalsPotentiallyEqual(GV, GV2);
  1400. return ICmpInst::BAD_ICMP_PREDICATE;
  1401. }
  1402. }
  1403. } else if (const auto *CE2GEP = dyn_cast<GEPOperator>(V2)) {
  1404. // By far the most common case to handle is when the base pointers are
  1405. // obviously to the same global.
  1406. const Constant *CE2Op0 = cast<Constant>(CE2GEP->getPointerOperand());
  1407. if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
  1408. // Don't know relative ordering, but check for inequality.
  1409. if (CE1Op0 != CE2Op0) {
  1410. if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
  1411. return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
  1412. cast<GlobalValue>(CE2Op0));
  1413. return ICmpInst::BAD_ICMP_PREDICATE;
  1414. }
  1415. }
  1416. }
  1417. break;
  1418. }
  1419. default:
  1420. break;
  1421. }
  1422. }
  1423. return ICmpInst::BAD_ICMP_PREDICATE;
  1424. }
  1425. static Constant *constantFoldCompareGlobalToNull(CmpInst::Predicate Predicate,
  1426. Constant *C1, Constant *C2) {
  1427. const GlobalValue *GV = dyn_cast<GlobalValue>(C2);
  1428. if (!GV || !C1->isNullValue())
  1429. return nullptr;
  1430. // Don't try to evaluate aliases. External weak GV can be null.
  1431. if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
  1432. !NullPointerIsDefined(nullptr /* F */,
  1433. GV->getType()->getAddressSpace())) {
  1434. if (Predicate == ICmpInst::ICMP_EQ)
  1435. return ConstantInt::getFalse(C1->getContext());
  1436. else if (Predicate == ICmpInst::ICMP_NE)
  1437. return ConstantInt::getTrue(C1->getContext());
  1438. }
  1439. return nullptr;
  1440. }
  1441. Constant *llvm::ConstantFoldCompareInstruction(CmpInst::Predicate Predicate,
  1442. Constant *C1, Constant *C2) {
  1443. Type *ResultTy;
  1444. if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
  1445. ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
  1446. VT->getElementCount());
  1447. else
  1448. ResultTy = Type::getInt1Ty(C1->getContext());
  1449. // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
  1450. if (Predicate == FCmpInst::FCMP_FALSE)
  1451. return Constant::getNullValue(ResultTy);
  1452. if (Predicate == FCmpInst::FCMP_TRUE)
  1453. return Constant::getAllOnesValue(ResultTy);
  1454. // Handle some degenerate cases first
  1455. if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
  1456. return PoisonValue::get(ResultTy);
  1457. if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
  1458. bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
  1459. // For EQ and NE, we can always pick a value for the undef to make the
  1460. // predicate pass or fail, so we can return undef.
  1461. // Also, if both operands are undef, we can return undef for int comparison.
  1462. if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
  1463. return UndefValue::get(ResultTy);
  1464. // Otherwise, for integer compare, pick the same value as the non-undef
  1465. // operand, and fold it to true or false.
  1466. if (isIntegerPredicate)
  1467. return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
  1468. // Choosing NaN for the undef will always make unordered comparison succeed
  1469. // and ordered comparison fails.
  1470. return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
  1471. }
  1472. // icmp eq/ne(null,GV) -> false/true
  1473. if (Constant *Folded = constantFoldCompareGlobalToNull(Predicate, C1, C2))
  1474. return Folded;
  1475. // icmp eq/ne(GV,null) -> false/true
  1476. if (Constant *Folded = constantFoldCompareGlobalToNull(Predicate, C2, C1))
  1477. return Folded;
  1478. if (C2->isNullValue()) {
  1479. // The caller is expected to commute the operands if the constant expression
  1480. // is C2.
  1481. // C1 >= 0 --> true
  1482. if (Predicate == ICmpInst::ICMP_UGE)
  1483. return Constant::getAllOnesValue(ResultTy);
  1484. // C1 < 0 --> false
  1485. if (Predicate == ICmpInst::ICMP_ULT)
  1486. return Constant::getNullValue(ResultTy);
  1487. }
  1488. // If the comparison is a comparison between two i1's, simplify it.
  1489. if (C1->getType()->isIntegerTy(1)) {
  1490. switch (Predicate) {
  1491. case ICmpInst::ICMP_EQ:
  1492. if (isa<ConstantInt>(C2))
  1493. return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
  1494. return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
  1495. case ICmpInst::ICMP_NE:
  1496. return ConstantExpr::getXor(C1, C2);
  1497. default:
  1498. break;
  1499. }
  1500. }
  1501. if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
  1502. const APInt &V1 = cast<ConstantInt>(C1)->getValue();
  1503. const APInt &V2 = cast<ConstantInt>(C2)->getValue();
  1504. return ConstantInt::get(ResultTy, ICmpInst::compare(V1, V2, Predicate));
  1505. } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
  1506. const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
  1507. const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
  1508. return ConstantInt::get(ResultTy, FCmpInst::compare(C1V, C2V, Predicate));
  1509. } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
  1510. // Fast path for splatted constants.
  1511. if (Constant *C1Splat = C1->getSplatValue())
  1512. if (Constant *C2Splat = C2->getSplatValue())
  1513. return ConstantVector::getSplat(
  1514. C1VTy->getElementCount(),
  1515. ConstantExpr::getCompare(Predicate, C1Splat, C2Splat));
  1516. // Do not iterate on scalable vector. The number of elements is unknown at
  1517. // compile-time.
  1518. if (isa<ScalableVectorType>(C1VTy))
  1519. return nullptr;
  1520. // If we can constant fold the comparison of each element, constant fold
  1521. // the whole vector comparison.
  1522. SmallVector<Constant*, 4> ResElts;
  1523. Type *Ty = IntegerType::get(C1->getContext(), 32);
  1524. // Compare the elements, producing an i1 result or constant expr.
  1525. for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
  1526. I != E; ++I) {
  1527. Constant *C1E =
  1528. ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I));
  1529. Constant *C2E =
  1530. ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I));
  1531. ResElts.push_back(ConstantExpr::getCompare(Predicate, C1E, C2E));
  1532. }
  1533. return ConstantVector::get(ResElts);
  1534. }
  1535. if (C1->getType()->isFloatingPointTy() &&
  1536. // Only call evaluateFCmpRelation if we have a constant expr to avoid
  1537. // infinite recursive loop
  1538. (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
  1539. int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
  1540. switch (evaluateFCmpRelation(C1, C2)) {
  1541. default: llvm_unreachable("Unknown relation!");
  1542. case FCmpInst::FCMP_UNO:
  1543. case FCmpInst::FCMP_ORD:
  1544. case FCmpInst::FCMP_UNE:
  1545. case FCmpInst::FCMP_ULT:
  1546. case FCmpInst::FCMP_UGT:
  1547. case FCmpInst::FCMP_ULE:
  1548. case FCmpInst::FCMP_UGE:
  1549. case FCmpInst::FCMP_TRUE:
  1550. case FCmpInst::FCMP_FALSE:
  1551. case FCmpInst::BAD_FCMP_PREDICATE:
  1552. break; // Couldn't determine anything about these constants.
  1553. case FCmpInst::FCMP_OEQ: // We know that C1 == C2
  1554. Result =
  1555. (Predicate == FCmpInst::FCMP_UEQ || Predicate == FCmpInst::FCMP_OEQ ||
  1556. Predicate == FCmpInst::FCMP_ULE || Predicate == FCmpInst::FCMP_OLE ||
  1557. Predicate == FCmpInst::FCMP_UGE || Predicate == FCmpInst::FCMP_OGE);
  1558. break;
  1559. case FCmpInst::FCMP_OLT: // We know that C1 < C2
  1560. Result =
  1561. (Predicate == FCmpInst::FCMP_UNE || Predicate == FCmpInst::FCMP_ONE ||
  1562. Predicate == FCmpInst::FCMP_ULT || Predicate == FCmpInst::FCMP_OLT ||
  1563. Predicate == FCmpInst::FCMP_ULE || Predicate == FCmpInst::FCMP_OLE);
  1564. break;
  1565. case FCmpInst::FCMP_OGT: // We know that C1 > C2
  1566. Result =
  1567. (Predicate == FCmpInst::FCMP_UNE || Predicate == FCmpInst::FCMP_ONE ||
  1568. Predicate == FCmpInst::FCMP_UGT || Predicate == FCmpInst::FCMP_OGT ||
  1569. Predicate == FCmpInst::FCMP_UGE || Predicate == FCmpInst::FCMP_OGE);
  1570. break;
  1571. case FCmpInst::FCMP_OLE: // We know that C1 <= C2
  1572. // We can only partially decide this relation.
  1573. if (Predicate == FCmpInst::FCMP_UGT || Predicate == FCmpInst::FCMP_OGT)
  1574. Result = 0;
  1575. else if (Predicate == FCmpInst::FCMP_ULT ||
  1576. Predicate == FCmpInst::FCMP_OLT)
  1577. Result = 1;
  1578. break;
  1579. case FCmpInst::FCMP_OGE: // We known that C1 >= C2
  1580. // We can only partially decide this relation.
  1581. if (Predicate == FCmpInst::FCMP_ULT || Predicate == FCmpInst::FCMP_OLT)
  1582. Result = 0;
  1583. else if (Predicate == FCmpInst::FCMP_UGT ||
  1584. Predicate == FCmpInst::FCMP_OGT)
  1585. Result = 1;
  1586. break;
  1587. case FCmpInst::FCMP_ONE: // We know that C1 != C2
  1588. // We can only partially decide this relation.
  1589. if (Predicate == FCmpInst::FCMP_OEQ || Predicate == FCmpInst::FCMP_UEQ)
  1590. Result = 0;
  1591. else if (Predicate == FCmpInst::FCMP_ONE ||
  1592. Predicate == FCmpInst::FCMP_UNE)
  1593. Result = 1;
  1594. break;
  1595. case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2).
  1596. // We can only partially decide this relation.
  1597. if (Predicate == FCmpInst::FCMP_ONE)
  1598. Result = 0;
  1599. else if (Predicate == FCmpInst::FCMP_UEQ)
  1600. Result = 1;
  1601. break;
  1602. }
  1603. // If we evaluated the result, return it now.
  1604. if (Result != -1)
  1605. return ConstantInt::get(ResultTy, Result);
  1606. } else {
  1607. // Evaluate the relation between the two constants, per the predicate.
  1608. int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
  1609. switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(Predicate))) {
  1610. default: llvm_unreachable("Unknown relational!");
  1611. case ICmpInst::BAD_ICMP_PREDICATE:
  1612. break; // Couldn't determine anything about these constants.
  1613. case ICmpInst::ICMP_EQ: // We know the constants are equal!
  1614. // If we know the constants are equal, we can decide the result of this
  1615. // computation precisely.
  1616. Result = ICmpInst::isTrueWhenEqual(Predicate);
  1617. break;
  1618. case ICmpInst::ICMP_ULT:
  1619. switch (Predicate) {
  1620. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
  1621. Result = 1; break;
  1622. case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
  1623. Result = 0; break;
  1624. default:
  1625. break;
  1626. }
  1627. break;
  1628. case ICmpInst::ICMP_SLT:
  1629. switch (Predicate) {
  1630. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
  1631. Result = 1; break;
  1632. case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
  1633. Result = 0; break;
  1634. default:
  1635. break;
  1636. }
  1637. break;
  1638. case ICmpInst::ICMP_UGT:
  1639. switch (Predicate) {
  1640. case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
  1641. Result = 1; break;
  1642. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
  1643. Result = 0; break;
  1644. default:
  1645. break;
  1646. }
  1647. break;
  1648. case ICmpInst::ICMP_SGT:
  1649. switch (Predicate) {
  1650. case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
  1651. Result = 1; break;
  1652. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
  1653. Result = 0; break;
  1654. default:
  1655. break;
  1656. }
  1657. break;
  1658. case ICmpInst::ICMP_ULE:
  1659. if (Predicate == ICmpInst::ICMP_UGT)
  1660. Result = 0;
  1661. if (Predicate == ICmpInst::ICMP_ULT || Predicate == ICmpInst::ICMP_ULE)
  1662. Result = 1;
  1663. break;
  1664. case ICmpInst::ICMP_SLE:
  1665. if (Predicate == ICmpInst::ICMP_SGT)
  1666. Result = 0;
  1667. if (Predicate == ICmpInst::ICMP_SLT || Predicate == ICmpInst::ICMP_SLE)
  1668. Result = 1;
  1669. break;
  1670. case ICmpInst::ICMP_UGE:
  1671. if (Predicate == ICmpInst::ICMP_ULT)
  1672. Result = 0;
  1673. if (Predicate == ICmpInst::ICMP_UGT || Predicate == ICmpInst::ICMP_UGE)
  1674. Result = 1;
  1675. break;
  1676. case ICmpInst::ICMP_SGE:
  1677. if (Predicate == ICmpInst::ICMP_SLT)
  1678. Result = 0;
  1679. if (Predicate == ICmpInst::ICMP_SGT || Predicate == ICmpInst::ICMP_SGE)
  1680. Result = 1;
  1681. break;
  1682. case ICmpInst::ICMP_NE:
  1683. if (Predicate == ICmpInst::ICMP_EQ)
  1684. Result = 0;
  1685. if (Predicate == ICmpInst::ICMP_NE)
  1686. Result = 1;
  1687. break;
  1688. }
  1689. // If we evaluated the result, return it now.
  1690. if (Result != -1)
  1691. return ConstantInt::get(ResultTy, Result);
  1692. // If the right hand side is a bitcast, try using its inverse to simplify
  1693. // it by moving it to the left hand side. We can't do this if it would turn
  1694. // a vector compare into a scalar compare or visa versa, or if it would turn
  1695. // the operands into FP values.
  1696. if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
  1697. Constant *CE2Op0 = CE2->getOperand(0);
  1698. if (CE2->getOpcode() == Instruction::BitCast &&
  1699. CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() &&
  1700. !CE2Op0->getType()->isFPOrFPVectorTy()) {
  1701. Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
  1702. return ConstantExpr::getICmp(Predicate, Inverse, CE2Op0);
  1703. }
  1704. }
  1705. // If the left hand side is an extension, try eliminating it.
  1706. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1707. if ((CE1->getOpcode() == Instruction::SExt &&
  1708. ICmpInst::isSigned(Predicate)) ||
  1709. (CE1->getOpcode() == Instruction::ZExt &&
  1710. !ICmpInst::isSigned(Predicate))) {
  1711. Constant *CE1Op0 = CE1->getOperand(0);
  1712. Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
  1713. if (CE1Inverse == CE1Op0) {
  1714. // Check whether we can safely truncate the right hand side.
  1715. Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
  1716. if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
  1717. C2->getType()) == C2)
  1718. return ConstantExpr::getICmp(Predicate, CE1Inverse, C2Inverse);
  1719. }
  1720. }
  1721. }
  1722. if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
  1723. (C1->isNullValue() && !C2->isNullValue())) {
  1724. // If C2 is a constant expr and C1 isn't, flip them around and fold the
  1725. // other way if possible.
  1726. // Also, if C1 is null and C2 isn't, flip them around.
  1727. Predicate = ICmpInst::getSwappedPredicate(Predicate);
  1728. return ConstantExpr::getICmp(Predicate, C2, C1);
  1729. }
  1730. }
  1731. return nullptr;
  1732. }
  1733. /// Test whether the given sequence of *normalized* indices is "inbounds".
  1734. template<typename IndexTy>
  1735. static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
  1736. // No indices means nothing that could be out of bounds.
  1737. if (Idxs.empty()) return true;
  1738. // If the first index is zero, it's in bounds.
  1739. if (cast<Constant>(Idxs[0])->isNullValue()) return true;
  1740. // If the first index is one and all the rest are zero, it's in bounds,
  1741. // by the one-past-the-end rule.
  1742. if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) {
  1743. if (!CI->isOne())
  1744. return false;
  1745. } else {
  1746. auto *CV = cast<ConstantDataVector>(Idxs[0]);
  1747. CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
  1748. if (!CI || !CI->isOne())
  1749. return false;
  1750. }
  1751. for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
  1752. if (!cast<Constant>(Idxs[i])->isNullValue())
  1753. return false;
  1754. return true;
  1755. }
  1756. /// Test whether a given ConstantInt is in-range for a SequentialType.
  1757. static bool isIndexInRangeOfArrayType(uint64_t NumElements,
  1758. const ConstantInt *CI) {
  1759. // We cannot bounds check the index if it doesn't fit in an int64_t.
  1760. if (CI->getValue().getMinSignedBits() > 64)
  1761. return false;
  1762. // A negative index or an index past the end of our sequential type is
  1763. // considered out-of-range.
  1764. int64_t IndexVal = CI->getSExtValue();
  1765. if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
  1766. return false;
  1767. // Otherwise, it is in-range.
  1768. return true;
  1769. }
  1770. // Combine Indices - If the source pointer to this getelementptr instruction
  1771. // is a getelementptr instruction, combine the indices of the two
  1772. // getelementptr instructions into a single instruction.
  1773. static Constant *foldGEPOfGEP(GEPOperator *GEP, Type *PointeeTy, bool InBounds,
  1774. ArrayRef<Value *> Idxs) {
  1775. if (PointeeTy != GEP->getResultElementType())
  1776. return nullptr;
  1777. Constant *Idx0 = cast<Constant>(Idxs[0]);
  1778. if (Idx0->isNullValue()) {
  1779. // Handle the simple case of a zero index.
  1780. SmallVector<Value*, 16> NewIndices;
  1781. NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
  1782. NewIndices.append(GEP->idx_begin(), GEP->idx_end());
  1783. NewIndices.append(Idxs.begin() + 1, Idxs.end());
  1784. return ConstantExpr::getGetElementPtr(
  1785. GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
  1786. NewIndices, InBounds && GEP->isInBounds(), GEP->getInRangeIndex());
  1787. }
  1788. gep_type_iterator LastI = gep_type_end(GEP);
  1789. for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
  1790. I != E; ++I)
  1791. LastI = I;
  1792. // We can't combine GEPs if the last index is a struct type.
  1793. if (!LastI.isSequential())
  1794. return nullptr;
  1795. // We could perform the transform with non-constant index, but prefer leaving
  1796. // it as GEP of GEP rather than GEP of add for now.
  1797. ConstantInt *CI = dyn_cast<ConstantInt>(Idx0);
  1798. if (!CI)
  1799. return nullptr;
  1800. // TODO: This code may be extended to handle vectors as well.
  1801. auto *LastIdx = cast<Constant>(GEP->getOperand(GEP->getNumOperands()-1));
  1802. Type *LastIdxTy = LastIdx->getType();
  1803. if (LastIdxTy->isVectorTy())
  1804. return nullptr;
  1805. SmallVector<Value*, 16> NewIndices;
  1806. NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
  1807. NewIndices.append(GEP->idx_begin(), GEP->idx_end() - 1);
  1808. // Add the last index of the source with the first index of the new GEP.
  1809. // Make sure to handle the case when they are actually different types.
  1810. if (LastIdxTy != Idx0->getType()) {
  1811. unsigned CommonExtendedWidth =
  1812. std::max(LastIdxTy->getIntegerBitWidth(),
  1813. Idx0->getType()->getIntegerBitWidth());
  1814. CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
  1815. Type *CommonTy =
  1816. Type::getIntNTy(LastIdxTy->getContext(), CommonExtendedWidth);
  1817. Idx0 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
  1818. LastIdx = ConstantExpr::getSExtOrBitCast(LastIdx, CommonTy);
  1819. }
  1820. NewIndices.push_back(ConstantExpr::get(Instruction::Add, Idx0, LastIdx));
  1821. NewIndices.append(Idxs.begin() + 1, Idxs.end());
  1822. // The combined GEP normally inherits its index inrange attribute from
  1823. // the inner GEP, but if the inner GEP's last index was adjusted by the
  1824. // outer GEP, any inbounds attribute on that index is invalidated.
  1825. std::optional<unsigned> IRIndex = GEP->getInRangeIndex();
  1826. if (IRIndex && *IRIndex == GEP->getNumIndices() - 1)
  1827. IRIndex = std::nullopt;
  1828. return ConstantExpr::getGetElementPtr(
  1829. GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
  1830. NewIndices, InBounds && GEP->isInBounds(), IRIndex);
  1831. }
  1832. Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
  1833. bool InBounds,
  1834. std::optional<unsigned> InRangeIndex,
  1835. ArrayRef<Value *> Idxs) {
  1836. if (Idxs.empty()) return C;
  1837. Type *GEPTy = GetElementPtrInst::getGEPReturnType(
  1838. PointeeTy, C, ArrayRef((Value *const *)Idxs.data(), Idxs.size()));
  1839. if (isa<PoisonValue>(C))
  1840. return PoisonValue::get(GEPTy);
  1841. if (isa<UndefValue>(C))
  1842. // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
  1843. return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
  1844. auto IsNoOp = [&]() {
  1845. // For non-opaque pointers having multiple indices will change the result
  1846. // type of the GEP.
  1847. if (!C->getType()->getScalarType()->isOpaquePointerTy() && Idxs.size() != 1)
  1848. return false;
  1849. // Avoid losing inrange information.
  1850. if (InRangeIndex)
  1851. return false;
  1852. return all_of(Idxs, [](Value *Idx) {
  1853. Constant *IdxC = cast<Constant>(Idx);
  1854. return IdxC->isNullValue() || isa<UndefValue>(IdxC);
  1855. });
  1856. };
  1857. if (IsNoOp())
  1858. return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
  1859. ? ConstantVector::getSplat(
  1860. cast<VectorType>(GEPTy)->getElementCount(), C)
  1861. : C;
  1862. if (C->isNullValue()) {
  1863. bool isNull = true;
  1864. for (Value *Idx : Idxs)
  1865. if (!isa<UndefValue>(Idx) && !cast<Constant>(Idx)->isNullValue()) {
  1866. isNull = false;
  1867. break;
  1868. }
  1869. if (isNull) {
  1870. PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType());
  1871. Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs);
  1872. assert(Ty && "Invalid indices for GEP!");
  1873. Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
  1874. Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
  1875. if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
  1876. GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
  1877. // The GEP returns a vector of pointers when one of more of
  1878. // its arguments is a vector.
  1879. for (Value *Idx : Idxs) {
  1880. if (auto *VT = dyn_cast<VectorType>(Idx->getType())) {
  1881. assert((!isa<VectorType>(GEPTy) || isa<ScalableVectorType>(GEPTy) ==
  1882. isa<ScalableVectorType>(VT)) &&
  1883. "Mismatched GEPTy vector types");
  1884. GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
  1885. break;
  1886. }
  1887. }
  1888. return Constant::getNullValue(GEPTy);
  1889. }
  1890. }
  1891. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1892. if (auto *GEP = dyn_cast<GEPOperator>(CE))
  1893. if (Constant *C = foldGEPOfGEP(GEP, PointeeTy, InBounds, Idxs))
  1894. return C;
  1895. // Attempt to fold casts to the same type away. For example, folding:
  1896. //
  1897. // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
  1898. // i64 0, i64 0)
  1899. // into:
  1900. //
  1901. // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
  1902. //
  1903. // Don't fold if the cast is changing address spaces.
  1904. Constant *Idx0 = cast<Constant>(Idxs[0]);
  1905. if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
  1906. PointerType *SrcPtrTy =
  1907. dyn_cast<PointerType>(CE->getOperand(0)->getType());
  1908. PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
  1909. if (SrcPtrTy && DstPtrTy && !SrcPtrTy->isOpaque() &&
  1910. !DstPtrTy->isOpaque()) {
  1911. ArrayType *SrcArrayTy =
  1912. dyn_cast<ArrayType>(SrcPtrTy->getNonOpaquePointerElementType());
  1913. ArrayType *DstArrayTy =
  1914. dyn_cast<ArrayType>(DstPtrTy->getNonOpaquePointerElementType());
  1915. if (SrcArrayTy && DstArrayTy
  1916. && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
  1917. && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
  1918. return ConstantExpr::getGetElementPtr(SrcArrayTy,
  1919. (Constant *)CE->getOperand(0),
  1920. Idxs, InBounds, InRangeIndex);
  1921. }
  1922. }
  1923. }
  1924. // Check to see if any array indices are not within the corresponding
  1925. // notional array or vector bounds. If so, try to determine if they can be
  1926. // factored out into preceding dimensions.
  1927. SmallVector<Constant *, 8> NewIdxs;
  1928. Type *Ty = PointeeTy;
  1929. Type *Prev = C->getType();
  1930. auto GEPIter = gep_type_begin(PointeeTy, Idxs);
  1931. bool Unknown =
  1932. !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]);
  1933. for (unsigned i = 1, e = Idxs.size(); i != e;
  1934. Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) {
  1935. if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) {
  1936. // We don't know if it's in range or not.
  1937. Unknown = true;
  1938. continue;
  1939. }
  1940. if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1]))
  1941. // Skip if the type of the previous index is not supported.
  1942. continue;
  1943. if (InRangeIndex && i == *InRangeIndex + 1) {
  1944. // If an index is marked inrange, we cannot apply this canonicalization to
  1945. // the following index, as that will cause the inrange index to point to
  1946. // the wrong element.
  1947. continue;
  1948. }
  1949. if (isa<StructType>(Ty)) {
  1950. // The verify makes sure that GEPs into a struct are in range.
  1951. continue;
  1952. }
  1953. if (isa<VectorType>(Ty)) {
  1954. // There can be awkward padding in after a non-power of two vector.
  1955. Unknown = true;
  1956. continue;
  1957. }
  1958. auto *STy = cast<ArrayType>(Ty);
  1959. if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
  1960. if (isIndexInRangeOfArrayType(STy->getNumElements(), CI))
  1961. // It's in range, skip to the next index.
  1962. continue;
  1963. if (CI->isNegative()) {
  1964. // It's out of range and negative, don't try to factor it.
  1965. Unknown = true;
  1966. continue;
  1967. }
  1968. } else {
  1969. auto *CV = cast<ConstantDataVector>(Idxs[i]);
  1970. bool InRange = true;
  1971. for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
  1972. auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I));
  1973. InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI);
  1974. if (CI->isNegative()) {
  1975. Unknown = true;
  1976. break;
  1977. }
  1978. }
  1979. if (InRange || Unknown)
  1980. // It's in range, skip to the next index.
  1981. // It's out of range and negative, don't try to factor it.
  1982. continue;
  1983. }
  1984. if (isa<StructType>(Prev)) {
  1985. // It's out of range, but the prior dimension is a struct
  1986. // so we can't do anything about it.
  1987. Unknown = true;
  1988. continue;
  1989. }
  1990. // It's out of range, but we can factor it into the prior
  1991. // dimension.
  1992. NewIdxs.resize(Idxs.size());
  1993. // Determine the number of elements in our sequential type.
  1994. uint64_t NumElements = STy->getArrayNumElements();
  1995. // Expand the current index or the previous index to a vector from a scalar
  1996. // if necessary.
  1997. Constant *CurrIdx = cast<Constant>(Idxs[i]);
  1998. auto *PrevIdx =
  1999. NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]);
  2000. bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy();
  2001. bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy();
  2002. bool UseVector = IsCurrIdxVector || IsPrevIdxVector;
  2003. if (!IsCurrIdxVector && IsPrevIdxVector)
  2004. CurrIdx = ConstantDataVector::getSplat(
  2005. cast<FixedVectorType>(PrevIdx->getType())->getNumElements(), CurrIdx);
  2006. if (!IsPrevIdxVector && IsCurrIdxVector)
  2007. PrevIdx = ConstantDataVector::getSplat(
  2008. cast<FixedVectorType>(CurrIdx->getType())->getNumElements(), PrevIdx);
  2009. Constant *Factor =
  2010. ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements);
  2011. if (UseVector)
  2012. Factor = ConstantDataVector::getSplat(
  2013. IsPrevIdxVector
  2014. ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
  2015. : cast<FixedVectorType>(CurrIdx->getType())->getNumElements(),
  2016. Factor);
  2017. NewIdxs[i] =
  2018. ConstantFoldBinaryInstruction(Instruction::SRem, CurrIdx, Factor);
  2019. Constant *Div =
  2020. ConstantFoldBinaryInstruction(Instruction::SDiv, CurrIdx, Factor);
  2021. // We're working on either ConstantInt or vectors of ConstantInt,
  2022. // so these should always fold.
  2023. assert(NewIdxs[i] != nullptr && Div != nullptr && "Should have folded");
  2024. unsigned CommonExtendedWidth =
  2025. std::max(PrevIdx->getType()->getScalarSizeInBits(),
  2026. Div->getType()->getScalarSizeInBits());
  2027. CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
  2028. // Before adding, extend both operands to i64 to avoid
  2029. // overflow trouble.
  2030. Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth);
  2031. if (UseVector)
  2032. ExtendedTy = FixedVectorType::get(
  2033. ExtendedTy,
  2034. IsPrevIdxVector
  2035. ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
  2036. : cast<FixedVectorType>(CurrIdx->getType())->getNumElements());
  2037. if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
  2038. PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy);
  2039. if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
  2040. Div = ConstantExpr::getSExt(Div, ExtendedTy);
  2041. NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div);
  2042. }
  2043. // If we did any factoring, start over with the adjusted indices.
  2044. if (!NewIdxs.empty()) {
  2045. for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
  2046. if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
  2047. return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds,
  2048. InRangeIndex);
  2049. }
  2050. // If all indices are known integers and normalized, we can do a simple
  2051. // check for the "inbounds" property.
  2052. if (!Unknown && !InBounds)
  2053. if (auto *GV = dyn_cast<GlobalVariable>(C))
  2054. if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
  2055. return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs,
  2056. /*InBounds=*/true, InRangeIndex);
  2057. return nullptr;
  2058. }