ConstantFold.cpp 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256
  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 "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().hasValue() &&
  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->isHalfTy() ? APFloat::IEEEhalf() :
  386. DestTy->isFloatTy() ? APFloat::IEEEsingle() :
  387. DestTy->isDoubleTy() ? APFloat::IEEEdouble() :
  388. DestTy->isX86_FP80Ty() ? APFloat::x87DoubleExtended() :
  389. DestTy->isFP128Ty() ? APFloat::IEEEquad() :
  390. DestTy->isPPC_FP128Ty() ? APFloat::PPCDoubleDouble() :
  391. APFloat::Bogus(),
  392. APFloat::rmNearestTiesToEven, &ignored);
  393. return ConstantFP::get(V->getContext(), Val);
  394. }
  395. return nullptr; // Can't fold.
  396. case Instruction::FPToUI:
  397. case Instruction::FPToSI:
  398. if (ConstantFP *FPC = dyn_cast<ConstantFP>(V)) {
  399. const APFloat &V = FPC->getValueAPF();
  400. bool ignored;
  401. uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  402. APSInt IntVal(DestBitWidth, opc == Instruction::FPToUI);
  403. if (APFloat::opInvalidOp ==
  404. V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored)) {
  405. // Undefined behavior invoked - the destination type can't represent
  406. // the input constant.
  407. return PoisonValue::get(DestTy);
  408. }
  409. return ConstantInt::get(FPC->getContext(), IntVal);
  410. }
  411. return nullptr; // Can't fold.
  412. case Instruction::IntToPtr: //always treated as unsigned
  413. if (V->isNullValue()) // Is it an integral null value?
  414. return ConstantPointerNull::get(cast<PointerType>(DestTy));
  415. return nullptr; // Other pointer types cannot be casted
  416. case Instruction::PtrToInt: // always treated as unsigned
  417. // Is it a null pointer value?
  418. if (V->isNullValue())
  419. return ConstantInt::get(DestTy, 0);
  420. // Other pointer types cannot be casted
  421. return nullptr;
  422. case Instruction::UIToFP:
  423. case Instruction::SIToFP:
  424. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  425. const APInt &api = CI->getValue();
  426. APFloat apf(DestTy->getFltSemantics(),
  427. APInt::getZero(DestTy->getPrimitiveSizeInBits()));
  428. apf.convertFromAPInt(api, opc==Instruction::SIToFP,
  429. APFloat::rmNearestTiesToEven);
  430. return ConstantFP::get(V->getContext(), apf);
  431. }
  432. return nullptr;
  433. case Instruction::ZExt:
  434. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  435. uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  436. return ConstantInt::get(V->getContext(),
  437. CI->getValue().zext(BitWidth));
  438. }
  439. return nullptr;
  440. case Instruction::SExt:
  441. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  442. uint32_t BitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  443. return ConstantInt::get(V->getContext(),
  444. CI->getValue().sext(BitWidth));
  445. }
  446. return nullptr;
  447. case Instruction::Trunc: {
  448. if (V->getType()->isVectorTy())
  449. return nullptr;
  450. uint32_t DestBitWidth = cast<IntegerType>(DestTy)->getBitWidth();
  451. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  452. return ConstantInt::get(V->getContext(),
  453. CI->getValue().trunc(DestBitWidth));
  454. }
  455. // The input must be a constantexpr. See if we can simplify this based on
  456. // the bytes we are demanding. Only do this if the source and dest are an
  457. // even multiple of a byte.
  458. if ((DestBitWidth & 7) == 0 &&
  459. (cast<IntegerType>(V->getType())->getBitWidth() & 7) == 0)
  460. if (Constant *Res = ExtractConstantBytes(V, 0, DestBitWidth / 8))
  461. return Res;
  462. return nullptr;
  463. }
  464. case Instruction::BitCast:
  465. return FoldBitCast(V, DestTy);
  466. case Instruction::AddrSpaceCast:
  467. return nullptr;
  468. }
  469. }
  470. Constant *llvm::ConstantFoldSelectInstruction(Constant *Cond,
  471. Constant *V1, Constant *V2) {
  472. // Check for i1 and vector true/false conditions.
  473. if (Cond->isNullValue()) return V2;
  474. if (Cond->isAllOnesValue()) return V1;
  475. // If the condition is a vector constant, fold the result elementwise.
  476. if (ConstantVector *CondV = dyn_cast<ConstantVector>(Cond)) {
  477. auto *V1VTy = CondV->getType();
  478. SmallVector<Constant*, 16> Result;
  479. Type *Ty = IntegerType::get(CondV->getContext(), 32);
  480. for (unsigned i = 0, e = V1VTy->getNumElements(); i != e; ++i) {
  481. Constant *V;
  482. Constant *V1Element = ConstantExpr::getExtractElement(V1,
  483. ConstantInt::get(Ty, i));
  484. Constant *V2Element = ConstantExpr::getExtractElement(V2,
  485. ConstantInt::get(Ty, i));
  486. auto *Cond = cast<Constant>(CondV->getOperand(i));
  487. if (isa<PoisonValue>(Cond)) {
  488. V = PoisonValue::get(V1Element->getType());
  489. } else if (V1Element == V2Element) {
  490. V = V1Element;
  491. } else if (isa<UndefValue>(Cond)) {
  492. V = isa<UndefValue>(V1Element) ? V1Element : V2Element;
  493. } else {
  494. if (!isa<ConstantInt>(Cond)) break;
  495. V = Cond->isNullValue() ? V2Element : V1Element;
  496. }
  497. Result.push_back(V);
  498. }
  499. // If we were able to build the vector, return it.
  500. if (Result.size() == V1VTy->getNumElements())
  501. return ConstantVector::get(Result);
  502. }
  503. if (isa<PoisonValue>(Cond))
  504. return PoisonValue::get(V1->getType());
  505. if (isa<UndefValue>(Cond)) {
  506. if (isa<UndefValue>(V1)) return V1;
  507. return V2;
  508. }
  509. if (V1 == V2) return V1;
  510. if (isa<PoisonValue>(V1))
  511. return V2;
  512. if (isa<PoisonValue>(V2))
  513. return V1;
  514. // If the true or false value is undef, we can fold to the other value as
  515. // long as the other value isn't poison.
  516. auto NotPoison = [](Constant *C) {
  517. if (isa<PoisonValue>(C))
  518. return false;
  519. // TODO: We can analyze ConstExpr by opcode to determine if there is any
  520. // possibility of poison.
  521. if (isa<ConstantExpr>(C))
  522. return false;
  523. if (isa<ConstantInt>(C) || isa<GlobalVariable>(C) || isa<ConstantFP>(C) ||
  524. isa<ConstantPointerNull>(C) || isa<Function>(C))
  525. return true;
  526. if (C->getType()->isVectorTy())
  527. return !C->containsPoisonElement() && !C->containsConstantExpression();
  528. // TODO: Recursively analyze aggregates or other constants.
  529. return false;
  530. };
  531. if (isa<UndefValue>(V1) && NotPoison(V2)) return V2;
  532. if (isa<UndefValue>(V2) && NotPoison(V1)) return V1;
  533. if (ConstantExpr *TrueVal = dyn_cast<ConstantExpr>(V1)) {
  534. if (TrueVal->getOpcode() == Instruction::Select)
  535. if (TrueVal->getOperand(0) == Cond)
  536. return ConstantExpr::getSelect(Cond, TrueVal->getOperand(1), V2);
  537. }
  538. if (ConstantExpr *FalseVal = dyn_cast<ConstantExpr>(V2)) {
  539. if (FalseVal->getOpcode() == Instruction::Select)
  540. if (FalseVal->getOperand(0) == Cond)
  541. return ConstantExpr::getSelect(Cond, V1, FalseVal->getOperand(2));
  542. }
  543. return nullptr;
  544. }
  545. Constant *llvm::ConstantFoldExtractElementInstruction(Constant *Val,
  546. Constant *Idx) {
  547. auto *ValVTy = cast<VectorType>(Val->getType());
  548. // extractelt poison, C -> poison
  549. // extractelt C, undef -> poison
  550. if (isa<PoisonValue>(Val) || isa<UndefValue>(Idx))
  551. return PoisonValue::get(ValVTy->getElementType());
  552. // extractelt undef, C -> undef
  553. if (isa<UndefValue>(Val))
  554. return UndefValue::get(ValVTy->getElementType());
  555. auto *CIdx = dyn_cast<ConstantInt>(Idx);
  556. if (!CIdx)
  557. return nullptr;
  558. if (auto *ValFVTy = dyn_cast<FixedVectorType>(Val->getType())) {
  559. // ee({w,x,y,z}, wrong_value) -> poison
  560. if (CIdx->uge(ValFVTy->getNumElements()))
  561. return PoisonValue::get(ValFVTy->getElementType());
  562. }
  563. // ee (gep (ptr, idx0, ...), idx) -> gep (ee (ptr, idx), ee (idx0, idx), ...)
  564. if (auto *CE = dyn_cast<ConstantExpr>(Val)) {
  565. if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
  566. SmallVector<Constant *, 8> Ops;
  567. Ops.reserve(CE->getNumOperands());
  568. for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i) {
  569. Constant *Op = CE->getOperand(i);
  570. if (Op->getType()->isVectorTy()) {
  571. Constant *ScalarOp = ConstantExpr::getExtractElement(Op, Idx);
  572. if (!ScalarOp)
  573. return nullptr;
  574. Ops.push_back(ScalarOp);
  575. } else
  576. Ops.push_back(Op);
  577. }
  578. return CE->getWithOperands(Ops, ValVTy->getElementType(), false,
  579. GEP->getSourceElementType());
  580. } else if (CE->getOpcode() == Instruction::InsertElement) {
  581. if (const auto *IEIdx = dyn_cast<ConstantInt>(CE->getOperand(2))) {
  582. if (APSInt::isSameValue(APSInt(IEIdx->getValue()),
  583. APSInt(CIdx->getValue()))) {
  584. return CE->getOperand(1);
  585. } else {
  586. return ConstantExpr::getExtractElement(CE->getOperand(0), CIdx);
  587. }
  588. }
  589. }
  590. }
  591. if (Constant *C = Val->getAggregateElement(CIdx))
  592. return C;
  593. // Lane < Splat minimum vector width => extractelt Splat(x), Lane -> x
  594. if (CIdx->getValue().ult(ValVTy->getElementCount().getKnownMinValue())) {
  595. if (Constant *SplatVal = Val->getSplatValue())
  596. return SplatVal;
  597. }
  598. return nullptr;
  599. }
  600. Constant *llvm::ConstantFoldInsertElementInstruction(Constant *Val,
  601. Constant *Elt,
  602. Constant *Idx) {
  603. if (isa<UndefValue>(Idx))
  604. return PoisonValue::get(Val->getType());
  605. ConstantInt *CIdx = dyn_cast<ConstantInt>(Idx);
  606. if (!CIdx) return nullptr;
  607. // Do not iterate on scalable vector. The num of elements is unknown at
  608. // compile-time.
  609. if (isa<ScalableVectorType>(Val->getType()))
  610. return nullptr;
  611. auto *ValTy = cast<FixedVectorType>(Val->getType());
  612. unsigned NumElts = ValTy->getNumElements();
  613. if (CIdx->uge(NumElts))
  614. return PoisonValue::get(Val->getType());
  615. SmallVector<Constant*, 16> Result;
  616. Result.reserve(NumElts);
  617. auto *Ty = Type::getInt32Ty(Val->getContext());
  618. uint64_t IdxVal = CIdx->getZExtValue();
  619. for (unsigned i = 0; i != NumElts; ++i) {
  620. if (i == IdxVal) {
  621. Result.push_back(Elt);
  622. continue;
  623. }
  624. Constant *C = ConstantExpr::getExtractElement(Val, ConstantInt::get(Ty, i));
  625. Result.push_back(C);
  626. }
  627. return ConstantVector::get(Result);
  628. }
  629. Constant *llvm::ConstantFoldShuffleVectorInstruction(Constant *V1, Constant *V2,
  630. ArrayRef<int> Mask) {
  631. auto *V1VTy = cast<VectorType>(V1->getType());
  632. unsigned MaskNumElts = Mask.size();
  633. auto MaskEltCount =
  634. ElementCount::get(MaskNumElts, isa<ScalableVectorType>(V1VTy));
  635. Type *EltTy = V1VTy->getElementType();
  636. // Undefined shuffle mask -> undefined value.
  637. if (all_of(Mask, [](int Elt) { return Elt == UndefMaskElem; })) {
  638. return UndefValue::get(FixedVectorType::get(EltTy, MaskNumElts));
  639. }
  640. // If the mask is all zeros this is a splat, no need to go through all
  641. // elements.
  642. if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
  643. Type *Ty = IntegerType::get(V1->getContext(), 32);
  644. Constant *Elt =
  645. ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, 0));
  646. if (Elt->isNullValue()) {
  647. auto *VTy = VectorType::get(EltTy, MaskEltCount);
  648. return ConstantAggregateZero::get(VTy);
  649. } else if (!MaskEltCount.isScalable())
  650. return ConstantVector::getSplat(MaskEltCount, Elt);
  651. }
  652. // Do not iterate on scalable vector. The num of elements is unknown at
  653. // compile-time.
  654. if (isa<ScalableVectorType>(V1VTy))
  655. return nullptr;
  656. unsigned SrcNumElts = V1VTy->getElementCount().getKnownMinValue();
  657. // Loop over the shuffle mask, evaluating each element.
  658. SmallVector<Constant*, 32> Result;
  659. for (unsigned i = 0; i != MaskNumElts; ++i) {
  660. int Elt = Mask[i];
  661. if (Elt == -1) {
  662. Result.push_back(UndefValue::get(EltTy));
  663. continue;
  664. }
  665. Constant *InElt;
  666. if (unsigned(Elt) >= SrcNumElts*2)
  667. InElt = UndefValue::get(EltTy);
  668. else if (unsigned(Elt) >= SrcNumElts) {
  669. Type *Ty = IntegerType::get(V2->getContext(), 32);
  670. InElt =
  671. ConstantExpr::getExtractElement(V2,
  672. ConstantInt::get(Ty, Elt - SrcNumElts));
  673. } else {
  674. Type *Ty = IntegerType::get(V1->getContext(), 32);
  675. InElt = ConstantExpr::getExtractElement(V1, ConstantInt::get(Ty, Elt));
  676. }
  677. Result.push_back(InElt);
  678. }
  679. return ConstantVector::get(Result);
  680. }
  681. Constant *llvm::ConstantFoldExtractValueInstruction(Constant *Agg,
  682. ArrayRef<unsigned> Idxs) {
  683. // Base case: no indices, so return the entire value.
  684. if (Idxs.empty())
  685. return Agg;
  686. if (Constant *C = Agg->getAggregateElement(Idxs[0]))
  687. return ConstantFoldExtractValueInstruction(C, Idxs.slice(1));
  688. return nullptr;
  689. }
  690. Constant *llvm::ConstantFoldInsertValueInstruction(Constant *Agg,
  691. Constant *Val,
  692. ArrayRef<unsigned> Idxs) {
  693. // Base case: no indices, so replace the entire value.
  694. if (Idxs.empty())
  695. return Val;
  696. unsigned NumElts;
  697. if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
  698. NumElts = ST->getNumElements();
  699. else
  700. NumElts = cast<ArrayType>(Agg->getType())->getNumElements();
  701. SmallVector<Constant*, 32> Result;
  702. for (unsigned i = 0; i != NumElts; ++i) {
  703. Constant *C = Agg->getAggregateElement(i);
  704. if (!C) return nullptr;
  705. if (Idxs[0] == i)
  706. C = ConstantFoldInsertValueInstruction(C, Val, Idxs.slice(1));
  707. Result.push_back(C);
  708. }
  709. if (StructType *ST = dyn_cast<StructType>(Agg->getType()))
  710. return ConstantStruct::get(ST, Result);
  711. return ConstantArray::get(cast<ArrayType>(Agg->getType()), Result);
  712. }
  713. Constant *llvm::ConstantFoldUnaryInstruction(unsigned Opcode, Constant *C) {
  714. assert(Instruction::isUnaryOp(Opcode) && "Non-unary instruction detected");
  715. // Handle scalar UndefValue and scalable vector UndefValue. Fixed-length
  716. // vectors are always evaluated per element.
  717. bool IsScalableVector = isa<ScalableVectorType>(C->getType());
  718. bool HasScalarUndefOrScalableVectorUndef =
  719. (!C->getType()->isVectorTy() || IsScalableVector) && isa<UndefValue>(C);
  720. if (HasScalarUndefOrScalableVectorUndef) {
  721. switch (static_cast<Instruction::UnaryOps>(Opcode)) {
  722. case Instruction::FNeg:
  723. return C; // -undef -> undef
  724. case Instruction::UnaryOpsEnd:
  725. llvm_unreachable("Invalid UnaryOp");
  726. }
  727. }
  728. // Constant should not be UndefValue, unless these are vector constants.
  729. assert(!HasScalarUndefOrScalableVectorUndef && "Unexpected UndefValue");
  730. // We only have FP UnaryOps right now.
  731. assert(!isa<ConstantInt>(C) && "Unexpected Integer UnaryOp");
  732. if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  733. const APFloat &CV = CFP->getValueAPF();
  734. switch (Opcode) {
  735. default:
  736. break;
  737. case Instruction::FNeg:
  738. return ConstantFP::get(C->getContext(), neg(CV));
  739. }
  740. } else if (auto *VTy = dyn_cast<FixedVectorType>(C->getType())) {
  741. Type *Ty = IntegerType::get(VTy->getContext(), 32);
  742. // Fast path for splatted constants.
  743. if (Constant *Splat = C->getSplatValue()) {
  744. Constant *Elt = ConstantExpr::get(Opcode, Splat);
  745. return ConstantVector::getSplat(VTy->getElementCount(), Elt);
  746. }
  747. // Fold each element and create a vector constant from those constants.
  748. SmallVector<Constant *, 16> Result;
  749. for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
  750. Constant *ExtractIdx = ConstantInt::get(Ty, i);
  751. Constant *Elt = ConstantExpr::getExtractElement(C, ExtractIdx);
  752. Result.push_back(ConstantExpr::get(Opcode, Elt));
  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. LLVM_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. LLVM_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 = llvm::None;
  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. return ConstantVector::getSplat(
  1093. VTy->getElementCount(),
  1094. ConstantExpr::get(Opcode, C1Splat, C2Splat));
  1095. }
  1096. }
  1097. if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
  1098. // Fold each element and create a vector constant from those constants.
  1099. SmallVector<Constant*, 16> Result;
  1100. Type *Ty = IntegerType::get(FVTy->getContext(), 32);
  1101. for (unsigned i = 0, e = FVTy->getNumElements(); i != e; ++i) {
  1102. Constant *ExtractIdx = ConstantInt::get(Ty, i);
  1103. Constant *LHS = ConstantExpr::getExtractElement(C1, ExtractIdx);
  1104. Constant *RHS = ConstantExpr::getExtractElement(C2, ExtractIdx);
  1105. // If any element of a divisor vector is zero, the whole op is poison.
  1106. if (Instruction::isIntDivRem(Opcode) && RHS->isNullValue())
  1107. return PoisonValue::get(VTy);
  1108. Result.push_back(ConstantExpr::get(Opcode, LHS, RHS));
  1109. }
  1110. return ConstantVector::get(Result);
  1111. }
  1112. }
  1113. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1114. // There are many possible foldings we could do here. We should probably
  1115. // at least fold add of a pointer with an integer into the appropriate
  1116. // getelementptr. This will improve alias analysis a bit.
  1117. // Given ((a + b) + c), if (b + c) folds to something interesting, return
  1118. // (a + (b + c)).
  1119. if (Instruction::isAssociative(Opcode) && CE1->getOpcode() == Opcode) {
  1120. Constant *T = ConstantExpr::get(Opcode, CE1->getOperand(1), C2);
  1121. if (!isa<ConstantExpr>(T) || cast<ConstantExpr>(T)->getOpcode() != Opcode)
  1122. return ConstantExpr::get(Opcode, CE1->getOperand(0), T);
  1123. }
  1124. } else if (isa<ConstantExpr>(C2)) {
  1125. // If C2 is a constant expr and C1 isn't, flop them around and fold the
  1126. // other way if possible.
  1127. if (Instruction::isCommutative(Opcode))
  1128. return ConstantFoldBinaryInstruction(Opcode, C2, C1);
  1129. }
  1130. // i1 can be simplified in many cases.
  1131. if (C1->getType()->isIntegerTy(1)) {
  1132. switch (Opcode) {
  1133. case Instruction::Add:
  1134. case Instruction::Sub:
  1135. return ConstantExpr::getXor(C1, C2);
  1136. case Instruction::Mul:
  1137. return ConstantExpr::getAnd(C1, C2);
  1138. case Instruction::Shl:
  1139. case Instruction::LShr:
  1140. case Instruction::AShr:
  1141. // We can assume that C2 == 0. If it were one the result would be
  1142. // undefined because the shift value is as large as the bitwidth.
  1143. return C1;
  1144. case Instruction::SDiv:
  1145. case Instruction::UDiv:
  1146. // We can assume that C2 == 1. If it were zero the result would be
  1147. // undefined through division by zero.
  1148. return C1;
  1149. case Instruction::URem:
  1150. case Instruction::SRem:
  1151. // We can assume that C2 == 1. If it were zero the result would be
  1152. // undefined through division by zero.
  1153. return ConstantInt::getFalse(C1->getContext());
  1154. default:
  1155. break;
  1156. }
  1157. }
  1158. // We don't know how to fold this.
  1159. return nullptr;
  1160. }
  1161. /// This function determines if there is anything we can decide about the two
  1162. /// constants provided. This doesn't need to handle simple things like
  1163. /// ConstantFP comparisons, but should instead handle ConstantExprs.
  1164. /// If we can determine that the two constants have a particular relation to
  1165. /// each other, we should return the corresponding FCmpInst predicate,
  1166. /// otherwise return FCmpInst::BAD_FCMP_PREDICATE. This is used below in
  1167. /// ConstantFoldCompareInstruction.
  1168. ///
  1169. /// To simplify this code we canonicalize the relation so that the first
  1170. /// operand is always the most "complex" of the two. We consider ConstantFP
  1171. /// to be the simplest, and ConstantExprs to be the most complex.
  1172. static FCmpInst::Predicate evaluateFCmpRelation(Constant *V1, Constant *V2) {
  1173. assert(V1->getType() == V2->getType() &&
  1174. "Cannot compare values of different types!");
  1175. // We do not know if a constant expression will evaluate to a number or NaN.
  1176. // Therefore, we can only say that the relation is unordered or equal.
  1177. if (V1 == V2) return FCmpInst::FCMP_UEQ;
  1178. if (!isa<ConstantExpr>(V1)) {
  1179. if (!isa<ConstantExpr>(V2)) {
  1180. // Simple case, use the standard constant folder.
  1181. ConstantInt *R = nullptr;
  1182. R = dyn_cast<ConstantInt>(
  1183. ConstantExpr::getFCmp(FCmpInst::FCMP_OEQ, V1, V2));
  1184. if (R && !R->isZero())
  1185. return FCmpInst::FCMP_OEQ;
  1186. R = dyn_cast<ConstantInt>(
  1187. ConstantExpr::getFCmp(FCmpInst::FCMP_OLT, V1, V2));
  1188. if (R && !R->isZero())
  1189. return FCmpInst::FCMP_OLT;
  1190. R = dyn_cast<ConstantInt>(
  1191. ConstantExpr::getFCmp(FCmpInst::FCMP_OGT, V1, V2));
  1192. if (R && !R->isZero())
  1193. return FCmpInst::FCMP_OGT;
  1194. // Nothing more we can do
  1195. return FCmpInst::BAD_FCMP_PREDICATE;
  1196. }
  1197. // If the first operand is simple and second is ConstantExpr, swap operands.
  1198. FCmpInst::Predicate SwappedRelation = evaluateFCmpRelation(V2, V1);
  1199. if (SwappedRelation != FCmpInst::BAD_FCMP_PREDICATE)
  1200. return FCmpInst::getSwappedPredicate(SwappedRelation);
  1201. } else {
  1202. // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
  1203. // constantexpr or a simple constant.
  1204. ConstantExpr *CE1 = cast<ConstantExpr>(V1);
  1205. switch (CE1->getOpcode()) {
  1206. case Instruction::FPTrunc:
  1207. case Instruction::FPExt:
  1208. case Instruction::UIToFP:
  1209. case Instruction::SIToFP:
  1210. // We might be able to do something with these but we don't right now.
  1211. break;
  1212. default:
  1213. break;
  1214. }
  1215. }
  1216. // There are MANY other foldings that we could perform here. They will
  1217. // probably be added on demand, as they seem needed.
  1218. return FCmpInst::BAD_FCMP_PREDICATE;
  1219. }
  1220. static ICmpInst::Predicate areGlobalsPotentiallyEqual(const GlobalValue *GV1,
  1221. const GlobalValue *GV2) {
  1222. auto isGlobalUnsafeForEquality = [](const GlobalValue *GV) {
  1223. if (GV->isInterposable() || GV->hasGlobalUnnamedAddr())
  1224. return true;
  1225. if (const auto *GVar = dyn_cast<GlobalVariable>(GV)) {
  1226. Type *Ty = GVar->getValueType();
  1227. // A global with opaque type might end up being zero sized.
  1228. if (!Ty->isSized())
  1229. return true;
  1230. // A global with an empty type might lie at the address of any other
  1231. // global.
  1232. if (Ty->isEmptyTy())
  1233. return true;
  1234. }
  1235. return false;
  1236. };
  1237. // Don't try to decide equality of aliases.
  1238. if (!isa<GlobalAlias>(GV1) && !isa<GlobalAlias>(GV2))
  1239. if (!isGlobalUnsafeForEquality(GV1) && !isGlobalUnsafeForEquality(GV2))
  1240. return ICmpInst::ICMP_NE;
  1241. return ICmpInst::BAD_ICMP_PREDICATE;
  1242. }
  1243. /// This function determines if there is anything we can decide about the two
  1244. /// constants provided. This doesn't need to handle simple things like integer
  1245. /// comparisons, but should instead handle ConstantExprs and GlobalValues.
  1246. /// If we can determine that the two constants have a particular relation to
  1247. /// each other, we should return the corresponding ICmp predicate, otherwise
  1248. /// return ICmpInst::BAD_ICMP_PREDICATE.
  1249. ///
  1250. /// To simplify this code we canonicalize the relation so that the first
  1251. /// operand is always the most "complex" of the two. We consider simple
  1252. /// constants (like ConstantInt) to be the simplest, followed by
  1253. /// GlobalValues, followed by ConstantExpr's (the most complex).
  1254. ///
  1255. static ICmpInst::Predicate evaluateICmpRelation(Constant *V1, Constant *V2,
  1256. bool isSigned) {
  1257. assert(V1->getType() == V2->getType() &&
  1258. "Cannot compare different types of values!");
  1259. if (V1 == V2) return ICmpInst::ICMP_EQ;
  1260. if (!isa<ConstantExpr>(V1) && !isa<GlobalValue>(V1) &&
  1261. !isa<BlockAddress>(V1)) {
  1262. if (!isa<GlobalValue>(V2) && !isa<ConstantExpr>(V2) &&
  1263. !isa<BlockAddress>(V2)) {
  1264. // We distilled this down to a simple case, use the standard constant
  1265. // folder.
  1266. ConstantInt *R = nullptr;
  1267. ICmpInst::Predicate pred = ICmpInst::ICMP_EQ;
  1268. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1269. if (R && !R->isZero())
  1270. return pred;
  1271. pred = isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  1272. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1273. if (R && !R->isZero())
  1274. return pred;
  1275. pred = isSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  1276. R = dyn_cast<ConstantInt>(ConstantExpr::getICmp(pred, V1, V2));
  1277. if (R && !R->isZero())
  1278. return pred;
  1279. // If we couldn't figure it out, bail.
  1280. return ICmpInst::BAD_ICMP_PREDICATE;
  1281. }
  1282. // If the first operand is simple, swap operands.
  1283. ICmpInst::Predicate SwappedRelation =
  1284. evaluateICmpRelation(V2, V1, isSigned);
  1285. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1286. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1287. } else if (const GlobalValue *GV = dyn_cast<GlobalValue>(V1)) {
  1288. if (isa<ConstantExpr>(V2)) { // Swap as necessary.
  1289. ICmpInst::Predicate SwappedRelation =
  1290. evaluateICmpRelation(V2, V1, isSigned);
  1291. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1292. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1293. return ICmpInst::BAD_ICMP_PREDICATE;
  1294. }
  1295. // Now we know that the RHS is a GlobalValue, BlockAddress or simple
  1296. // constant (which, since the types must match, means that it's a
  1297. // ConstantPointerNull).
  1298. if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
  1299. return areGlobalsPotentiallyEqual(GV, GV2);
  1300. } else if (isa<BlockAddress>(V2)) {
  1301. return ICmpInst::ICMP_NE; // Globals never equal labels.
  1302. } else {
  1303. assert(isa<ConstantPointerNull>(V2) && "Canonicalization guarantee!");
  1304. // GlobalVals can never be null unless they have external weak linkage.
  1305. // We don't try to evaluate aliases here.
  1306. // NOTE: We should not be doing this constant folding if null pointer
  1307. // is considered valid for the function. But currently there is no way to
  1308. // query it from the Constant type.
  1309. if (!GV->hasExternalWeakLinkage() && !isa<GlobalAlias>(GV) &&
  1310. !NullPointerIsDefined(nullptr /* F */,
  1311. GV->getType()->getAddressSpace()))
  1312. return ICmpInst::ICMP_UGT;
  1313. }
  1314. } else if (const BlockAddress *BA = dyn_cast<BlockAddress>(V1)) {
  1315. if (isa<ConstantExpr>(V2)) { // Swap as necessary.
  1316. ICmpInst::Predicate SwappedRelation =
  1317. evaluateICmpRelation(V2, V1, isSigned);
  1318. if (SwappedRelation != ICmpInst::BAD_ICMP_PREDICATE)
  1319. return ICmpInst::getSwappedPredicate(SwappedRelation);
  1320. return ICmpInst::BAD_ICMP_PREDICATE;
  1321. }
  1322. // Now we know that the RHS is a GlobalValue, BlockAddress or simple
  1323. // constant (which, since the types must match, means that it is a
  1324. // ConstantPointerNull).
  1325. if (const BlockAddress *BA2 = dyn_cast<BlockAddress>(V2)) {
  1326. // Block address in another function can't equal this one, but block
  1327. // addresses in the current function might be the same if blocks are
  1328. // empty.
  1329. if (BA2->getFunction() != BA->getFunction())
  1330. return ICmpInst::ICMP_NE;
  1331. } else {
  1332. // Block addresses aren't null, don't equal the address of globals.
  1333. assert((isa<ConstantPointerNull>(V2) || isa<GlobalValue>(V2)) &&
  1334. "Canonicalization guarantee!");
  1335. return ICmpInst::ICMP_NE;
  1336. }
  1337. } else {
  1338. // Ok, the LHS is known to be a constantexpr. The RHS can be any of a
  1339. // constantexpr, a global, block address, or a simple constant.
  1340. ConstantExpr *CE1 = cast<ConstantExpr>(V1);
  1341. Constant *CE1Op0 = CE1->getOperand(0);
  1342. switch (CE1->getOpcode()) {
  1343. case Instruction::Trunc:
  1344. case Instruction::FPTrunc:
  1345. case Instruction::FPExt:
  1346. case Instruction::FPToUI:
  1347. case Instruction::FPToSI:
  1348. break; // We can't evaluate floating point casts or truncations.
  1349. case Instruction::BitCast:
  1350. // If this is a global value cast, check to see if the RHS is also a
  1351. // GlobalValue.
  1352. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0))
  1353. if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2))
  1354. return areGlobalsPotentiallyEqual(GV, GV2);
  1355. LLVM_FALLTHROUGH;
  1356. case Instruction::UIToFP:
  1357. case Instruction::SIToFP:
  1358. case Instruction::ZExt:
  1359. case Instruction::SExt:
  1360. // We can't evaluate floating point casts or truncations.
  1361. if (CE1Op0->getType()->isFPOrFPVectorTy())
  1362. break;
  1363. // If the cast is not actually changing bits, and the second operand is a
  1364. // null pointer, do the comparison with the pre-casted value.
  1365. if (V2->isNullValue() && CE1->getType()->isIntOrPtrTy()) {
  1366. if (CE1->getOpcode() == Instruction::ZExt) isSigned = false;
  1367. if (CE1->getOpcode() == Instruction::SExt) isSigned = true;
  1368. return evaluateICmpRelation(CE1Op0,
  1369. Constant::getNullValue(CE1Op0->getType()),
  1370. isSigned);
  1371. }
  1372. break;
  1373. case Instruction::GetElementPtr: {
  1374. GEPOperator *CE1GEP = cast<GEPOperator>(CE1);
  1375. // Ok, since this is a getelementptr, we know that the constant has a
  1376. // pointer type. Check the various cases.
  1377. if (isa<ConstantPointerNull>(V2)) {
  1378. // If we are comparing a GEP to a null pointer, check to see if the base
  1379. // of the GEP equals the null pointer.
  1380. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
  1381. // If its not weak linkage, the GVal must have a non-zero address
  1382. // so the result is greater-than
  1383. if (!GV->hasExternalWeakLinkage() && CE1GEP->isInBounds())
  1384. return ICmpInst::ICMP_UGT;
  1385. }
  1386. } else if (const GlobalValue *GV2 = dyn_cast<GlobalValue>(V2)) {
  1387. if (const GlobalValue *GV = dyn_cast<GlobalValue>(CE1Op0)) {
  1388. if (GV != GV2) {
  1389. if (CE1GEP->hasAllZeroIndices())
  1390. return areGlobalsPotentiallyEqual(GV, GV2);
  1391. return ICmpInst::BAD_ICMP_PREDICATE;
  1392. }
  1393. }
  1394. } else if (const auto *CE2GEP = dyn_cast<GEPOperator>(V2)) {
  1395. // By far the most common case to handle is when the base pointers are
  1396. // obviously to the same global.
  1397. const Constant *CE2Op0 = cast<Constant>(CE2GEP->getPointerOperand());
  1398. if (isa<GlobalValue>(CE1Op0) && isa<GlobalValue>(CE2Op0)) {
  1399. // Don't know relative ordering, but check for inequality.
  1400. if (CE1Op0 != CE2Op0) {
  1401. if (CE1GEP->hasAllZeroIndices() && CE2GEP->hasAllZeroIndices())
  1402. return areGlobalsPotentiallyEqual(cast<GlobalValue>(CE1Op0),
  1403. cast<GlobalValue>(CE2Op0));
  1404. return ICmpInst::BAD_ICMP_PREDICATE;
  1405. }
  1406. }
  1407. }
  1408. break;
  1409. }
  1410. default:
  1411. break;
  1412. }
  1413. }
  1414. return ICmpInst::BAD_ICMP_PREDICATE;
  1415. }
  1416. Constant *llvm::ConstantFoldCompareInstruction(CmpInst::Predicate Predicate,
  1417. Constant *C1, Constant *C2) {
  1418. Type *ResultTy;
  1419. if (VectorType *VT = dyn_cast<VectorType>(C1->getType()))
  1420. ResultTy = VectorType::get(Type::getInt1Ty(C1->getContext()),
  1421. VT->getElementCount());
  1422. else
  1423. ResultTy = Type::getInt1Ty(C1->getContext());
  1424. // Fold FCMP_FALSE/FCMP_TRUE unconditionally.
  1425. if (Predicate == FCmpInst::FCMP_FALSE)
  1426. return Constant::getNullValue(ResultTy);
  1427. if (Predicate == FCmpInst::FCMP_TRUE)
  1428. return Constant::getAllOnesValue(ResultTy);
  1429. // Handle some degenerate cases first
  1430. if (isa<PoisonValue>(C1) || isa<PoisonValue>(C2))
  1431. return PoisonValue::get(ResultTy);
  1432. if (isa<UndefValue>(C1) || isa<UndefValue>(C2)) {
  1433. bool isIntegerPredicate = ICmpInst::isIntPredicate(Predicate);
  1434. // For EQ and NE, we can always pick a value for the undef to make the
  1435. // predicate pass or fail, so we can return undef.
  1436. // Also, if both operands are undef, we can return undef for int comparison.
  1437. if (ICmpInst::isEquality(Predicate) || (isIntegerPredicate && C1 == C2))
  1438. return UndefValue::get(ResultTy);
  1439. // Otherwise, for integer compare, pick the same value as the non-undef
  1440. // operand, and fold it to true or false.
  1441. if (isIntegerPredicate)
  1442. return ConstantInt::get(ResultTy, CmpInst::isTrueWhenEqual(Predicate));
  1443. // Choosing NaN for the undef will always make unordered comparison succeed
  1444. // and ordered comparison fails.
  1445. return ConstantInt::get(ResultTy, CmpInst::isUnordered(Predicate));
  1446. }
  1447. // icmp eq/ne(null,GV) -> false/true
  1448. if (C1->isNullValue()) {
  1449. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C2))
  1450. // Don't try to evaluate aliases. External weak GV can be null.
  1451. if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
  1452. !NullPointerIsDefined(nullptr /* F */,
  1453. GV->getType()->getAddressSpace())) {
  1454. if (Predicate == ICmpInst::ICMP_EQ)
  1455. return ConstantInt::getFalse(C1->getContext());
  1456. else if (Predicate == ICmpInst::ICMP_NE)
  1457. return ConstantInt::getTrue(C1->getContext());
  1458. }
  1459. // icmp eq/ne(GV,null) -> false/true
  1460. } else if (C2->isNullValue()) {
  1461. if (const GlobalValue *GV = dyn_cast<GlobalValue>(C1)) {
  1462. // Don't try to evaluate aliases. External weak GV can be null.
  1463. if (!isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage() &&
  1464. !NullPointerIsDefined(nullptr /* F */,
  1465. GV->getType()->getAddressSpace())) {
  1466. if (Predicate == ICmpInst::ICMP_EQ)
  1467. return ConstantInt::getFalse(C1->getContext());
  1468. else if (Predicate == ICmpInst::ICMP_NE)
  1469. return ConstantInt::getTrue(C1->getContext());
  1470. }
  1471. }
  1472. // The caller is expected to commute the operands if the constant expression
  1473. // is C2.
  1474. // C1 >= 0 --> true
  1475. if (Predicate == ICmpInst::ICMP_UGE)
  1476. return Constant::getAllOnesValue(ResultTy);
  1477. // C1 < 0 --> false
  1478. if (Predicate == ICmpInst::ICMP_ULT)
  1479. return Constant::getNullValue(ResultTy);
  1480. }
  1481. // If the comparison is a comparison between two i1's, simplify it.
  1482. if (C1->getType()->isIntegerTy(1)) {
  1483. switch (Predicate) {
  1484. case ICmpInst::ICMP_EQ:
  1485. if (isa<ConstantInt>(C2))
  1486. return ConstantExpr::getXor(C1, ConstantExpr::getNot(C2));
  1487. return ConstantExpr::getXor(ConstantExpr::getNot(C1), C2);
  1488. case ICmpInst::ICMP_NE:
  1489. return ConstantExpr::getXor(C1, C2);
  1490. default:
  1491. break;
  1492. }
  1493. }
  1494. if (isa<ConstantInt>(C1) && isa<ConstantInt>(C2)) {
  1495. const APInt &V1 = cast<ConstantInt>(C1)->getValue();
  1496. const APInt &V2 = cast<ConstantInt>(C2)->getValue();
  1497. return ConstantInt::get(ResultTy, ICmpInst::compare(V1, V2, Predicate));
  1498. } else if (isa<ConstantFP>(C1) && isa<ConstantFP>(C2)) {
  1499. const APFloat &C1V = cast<ConstantFP>(C1)->getValueAPF();
  1500. const APFloat &C2V = cast<ConstantFP>(C2)->getValueAPF();
  1501. return ConstantInt::get(ResultTy, FCmpInst::compare(C1V, C2V, Predicate));
  1502. } else if (auto *C1VTy = dyn_cast<VectorType>(C1->getType())) {
  1503. // Fast path for splatted constants.
  1504. if (Constant *C1Splat = C1->getSplatValue())
  1505. if (Constant *C2Splat = C2->getSplatValue())
  1506. return ConstantVector::getSplat(
  1507. C1VTy->getElementCount(),
  1508. ConstantExpr::getCompare(Predicate, C1Splat, C2Splat));
  1509. // Do not iterate on scalable vector. The number of elements is unknown at
  1510. // compile-time.
  1511. if (isa<ScalableVectorType>(C1VTy))
  1512. return nullptr;
  1513. // If we can constant fold the comparison of each element, constant fold
  1514. // the whole vector comparison.
  1515. SmallVector<Constant*, 4> ResElts;
  1516. Type *Ty = IntegerType::get(C1->getContext(), 32);
  1517. // Compare the elements, producing an i1 result or constant expr.
  1518. for (unsigned I = 0, E = C1VTy->getElementCount().getKnownMinValue();
  1519. I != E; ++I) {
  1520. Constant *C1E =
  1521. ConstantExpr::getExtractElement(C1, ConstantInt::get(Ty, I));
  1522. Constant *C2E =
  1523. ConstantExpr::getExtractElement(C2, ConstantInt::get(Ty, I));
  1524. ResElts.push_back(ConstantExpr::getCompare(Predicate, C1E, C2E));
  1525. }
  1526. return ConstantVector::get(ResElts);
  1527. }
  1528. if (C1->getType()->isFloatingPointTy() &&
  1529. // Only call evaluateFCmpRelation if we have a constant expr to avoid
  1530. // infinite recursive loop
  1531. (isa<ConstantExpr>(C1) || isa<ConstantExpr>(C2))) {
  1532. int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
  1533. switch (evaluateFCmpRelation(C1, C2)) {
  1534. default: llvm_unreachable("Unknown relation!");
  1535. case FCmpInst::FCMP_UNO:
  1536. case FCmpInst::FCMP_ORD:
  1537. case FCmpInst::FCMP_UNE:
  1538. case FCmpInst::FCMP_ULT:
  1539. case FCmpInst::FCMP_UGT:
  1540. case FCmpInst::FCMP_ULE:
  1541. case FCmpInst::FCMP_UGE:
  1542. case FCmpInst::FCMP_TRUE:
  1543. case FCmpInst::FCMP_FALSE:
  1544. case FCmpInst::BAD_FCMP_PREDICATE:
  1545. break; // Couldn't determine anything about these constants.
  1546. case FCmpInst::FCMP_OEQ: // We know that C1 == C2
  1547. Result =
  1548. (Predicate == FCmpInst::FCMP_UEQ || Predicate == FCmpInst::FCMP_OEQ ||
  1549. Predicate == FCmpInst::FCMP_ULE || Predicate == FCmpInst::FCMP_OLE ||
  1550. Predicate == FCmpInst::FCMP_UGE || Predicate == FCmpInst::FCMP_OGE);
  1551. break;
  1552. case FCmpInst::FCMP_OLT: // We know that C1 < C2
  1553. Result =
  1554. (Predicate == FCmpInst::FCMP_UNE || Predicate == FCmpInst::FCMP_ONE ||
  1555. Predicate == FCmpInst::FCMP_ULT || Predicate == FCmpInst::FCMP_OLT ||
  1556. Predicate == FCmpInst::FCMP_ULE || Predicate == FCmpInst::FCMP_OLE);
  1557. break;
  1558. case FCmpInst::FCMP_OGT: // We know that C1 > C2
  1559. Result =
  1560. (Predicate == FCmpInst::FCMP_UNE || Predicate == FCmpInst::FCMP_ONE ||
  1561. Predicate == FCmpInst::FCMP_UGT || Predicate == FCmpInst::FCMP_OGT ||
  1562. Predicate == FCmpInst::FCMP_UGE || Predicate == FCmpInst::FCMP_OGE);
  1563. break;
  1564. case FCmpInst::FCMP_OLE: // We know that C1 <= C2
  1565. // We can only partially decide this relation.
  1566. if (Predicate == FCmpInst::FCMP_UGT || Predicate == FCmpInst::FCMP_OGT)
  1567. Result = 0;
  1568. else if (Predicate == FCmpInst::FCMP_ULT ||
  1569. Predicate == FCmpInst::FCMP_OLT)
  1570. Result = 1;
  1571. break;
  1572. case FCmpInst::FCMP_OGE: // We known that C1 >= C2
  1573. // We can only partially decide this relation.
  1574. if (Predicate == FCmpInst::FCMP_ULT || Predicate == FCmpInst::FCMP_OLT)
  1575. Result = 0;
  1576. else if (Predicate == FCmpInst::FCMP_UGT ||
  1577. Predicate == FCmpInst::FCMP_OGT)
  1578. Result = 1;
  1579. break;
  1580. case FCmpInst::FCMP_ONE: // We know that C1 != C2
  1581. // We can only partially decide this relation.
  1582. if (Predicate == FCmpInst::FCMP_OEQ || Predicate == FCmpInst::FCMP_UEQ)
  1583. Result = 0;
  1584. else if (Predicate == FCmpInst::FCMP_ONE ||
  1585. Predicate == FCmpInst::FCMP_UNE)
  1586. Result = 1;
  1587. break;
  1588. case FCmpInst::FCMP_UEQ: // We know that C1 == C2 || isUnordered(C1, C2).
  1589. // We can only partially decide this relation.
  1590. if (Predicate == FCmpInst::FCMP_ONE)
  1591. Result = 0;
  1592. else if (Predicate == FCmpInst::FCMP_UEQ)
  1593. Result = 1;
  1594. break;
  1595. }
  1596. // If we evaluated the result, return it now.
  1597. if (Result != -1)
  1598. return ConstantInt::get(ResultTy, Result);
  1599. } else {
  1600. // Evaluate the relation between the two constants, per the predicate.
  1601. int Result = -1; // -1 = unknown, 0 = known false, 1 = known true.
  1602. switch (evaluateICmpRelation(C1, C2, CmpInst::isSigned(Predicate))) {
  1603. default: llvm_unreachable("Unknown relational!");
  1604. case ICmpInst::BAD_ICMP_PREDICATE:
  1605. break; // Couldn't determine anything about these constants.
  1606. case ICmpInst::ICMP_EQ: // We know the constants are equal!
  1607. // If we know the constants are equal, we can decide the result of this
  1608. // computation precisely.
  1609. Result = ICmpInst::isTrueWhenEqual(Predicate);
  1610. break;
  1611. case ICmpInst::ICMP_ULT:
  1612. switch (Predicate) {
  1613. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_ULE:
  1614. Result = 1; break;
  1615. case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_UGE:
  1616. Result = 0; break;
  1617. default:
  1618. break;
  1619. }
  1620. break;
  1621. case ICmpInst::ICMP_SLT:
  1622. switch (Predicate) {
  1623. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SLE:
  1624. Result = 1; break;
  1625. case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SGE:
  1626. Result = 0; break;
  1627. default:
  1628. break;
  1629. }
  1630. break;
  1631. case ICmpInst::ICMP_UGT:
  1632. switch (Predicate) {
  1633. case ICmpInst::ICMP_UGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_UGE:
  1634. Result = 1; break;
  1635. case ICmpInst::ICMP_ULT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_ULE:
  1636. Result = 0; break;
  1637. default:
  1638. break;
  1639. }
  1640. break;
  1641. case ICmpInst::ICMP_SGT:
  1642. switch (Predicate) {
  1643. case ICmpInst::ICMP_SGT: case ICmpInst::ICMP_NE: case ICmpInst::ICMP_SGE:
  1644. Result = 1; break;
  1645. case ICmpInst::ICMP_SLT: case ICmpInst::ICMP_EQ: case ICmpInst::ICMP_SLE:
  1646. Result = 0; break;
  1647. default:
  1648. break;
  1649. }
  1650. break;
  1651. case ICmpInst::ICMP_ULE:
  1652. if (Predicate == ICmpInst::ICMP_UGT)
  1653. Result = 0;
  1654. if (Predicate == ICmpInst::ICMP_ULT || Predicate == ICmpInst::ICMP_ULE)
  1655. Result = 1;
  1656. break;
  1657. case ICmpInst::ICMP_SLE:
  1658. if (Predicate == ICmpInst::ICMP_SGT)
  1659. Result = 0;
  1660. if (Predicate == ICmpInst::ICMP_SLT || Predicate == ICmpInst::ICMP_SLE)
  1661. Result = 1;
  1662. break;
  1663. case ICmpInst::ICMP_UGE:
  1664. if (Predicate == ICmpInst::ICMP_ULT)
  1665. Result = 0;
  1666. if (Predicate == ICmpInst::ICMP_UGT || Predicate == ICmpInst::ICMP_UGE)
  1667. Result = 1;
  1668. break;
  1669. case ICmpInst::ICMP_SGE:
  1670. if (Predicate == ICmpInst::ICMP_SLT)
  1671. Result = 0;
  1672. if (Predicate == ICmpInst::ICMP_SGT || Predicate == ICmpInst::ICMP_SGE)
  1673. Result = 1;
  1674. break;
  1675. case ICmpInst::ICMP_NE:
  1676. if (Predicate == ICmpInst::ICMP_EQ)
  1677. Result = 0;
  1678. if (Predicate == ICmpInst::ICMP_NE)
  1679. Result = 1;
  1680. break;
  1681. }
  1682. // If we evaluated the result, return it now.
  1683. if (Result != -1)
  1684. return ConstantInt::get(ResultTy, Result);
  1685. // If the right hand side is a bitcast, try using its inverse to simplify
  1686. // it by moving it to the left hand side. We can't do this if it would turn
  1687. // a vector compare into a scalar compare or visa versa, or if it would turn
  1688. // the operands into FP values.
  1689. if (ConstantExpr *CE2 = dyn_cast<ConstantExpr>(C2)) {
  1690. Constant *CE2Op0 = CE2->getOperand(0);
  1691. if (CE2->getOpcode() == Instruction::BitCast &&
  1692. CE2->getType()->isVectorTy() == CE2Op0->getType()->isVectorTy() &&
  1693. !CE2Op0->getType()->isFPOrFPVectorTy()) {
  1694. Constant *Inverse = ConstantExpr::getBitCast(C1, CE2Op0->getType());
  1695. return ConstantExpr::getICmp(Predicate, Inverse, CE2Op0);
  1696. }
  1697. }
  1698. // If the left hand side is an extension, try eliminating it.
  1699. if (ConstantExpr *CE1 = dyn_cast<ConstantExpr>(C1)) {
  1700. if ((CE1->getOpcode() == Instruction::SExt &&
  1701. ICmpInst::isSigned(Predicate)) ||
  1702. (CE1->getOpcode() == Instruction::ZExt &&
  1703. !ICmpInst::isSigned(Predicate))) {
  1704. Constant *CE1Op0 = CE1->getOperand(0);
  1705. Constant *CE1Inverse = ConstantExpr::getTrunc(CE1, CE1Op0->getType());
  1706. if (CE1Inverse == CE1Op0) {
  1707. // Check whether we can safely truncate the right hand side.
  1708. Constant *C2Inverse = ConstantExpr::getTrunc(C2, CE1Op0->getType());
  1709. if (ConstantExpr::getCast(CE1->getOpcode(), C2Inverse,
  1710. C2->getType()) == C2)
  1711. return ConstantExpr::getICmp(Predicate, CE1Inverse, C2Inverse);
  1712. }
  1713. }
  1714. }
  1715. if ((!isa<ConstantExpr>(C1) && isa<ConstantExpr>(C2)) ||
  1716. (C1->isNullValue() && !C2->isNullValue())) {
  1717. // If C2 is a constant expr and C1 isn't, flip them around and fold the
  1718. // other way if possible.
  1719. // Also, if C1 is null and C2 isn't, flip them around.
  1720. Predicate = ICmpInst::getSwappedPredicate(Predicate);
  1721. return ConstantExpr::getICmp(Predicate, C2, C1);
  1722. }
  1723. }
  1724. return nullptr;
  1725. }
  1726. /// Test whether the given sequence of *normalized* indices is "inbounds".
  1727. template<typename IndexTy>
  1728. static bool isInBoundsIndices(ArrayRef<IndexTy> Idxs) {
  1729. // No indices means nothing that could be out of bounds.
  1730. if (Idxs.empty()) return true;
  1731. // If the first index is zero, it's in bounds.
  1732. if (cast<Constant>(Idxs[0])->isNullValue()) return true;
  1733. // If the first index is one and all the rest are zero, it's in bounds,
  1734. // by the one-past-the-end rule.
  1735. if (auto *CI = dyn_cast<ConstantInt>(Idxs[0])) {
  1736. if (!CI->isOne())
  1737. return false;
  1738. } else {
  1739. auto *CV = cast<ConstantDataVector>(Idxs[0]);
  1740. CI = dyn_cast_or_null<ConstantInt>(CV->getSplatValue());
  1741. if (!CI || !CI->isOne())
  1742. return false;
  1743. }
  1744. for (unsigned i = 1, e = Idxs.size(); i != e; ++i)
  1745. if (!cast<Constant>(Idxs[i])->isNullValue())
  1746. return false;
  1747. return true;
  1748. }
  1749. /// Test whether a given ConstantInt is in-range for a SequentialType.
  1750. static bool isIndexInRangeOfArrayType(uint64_t NumElements,
  1751. const ConstantInt *CI) {
  1752. // We cannot bounds check the index if it doesn't fit in an int64_t.
  1753. if (CI->getValue().getMinSignedBits() > 64)
  1754. return false;
  1755. // A negative index or an index past the end of our sequential type is
  1756. // considered out-of-range.
  1757. int64_t IndexVal = CI->getSExtValue();
  1758. if (IndexVal < 0 || (NumElements > 0 && (uint64_t)IndexVal >= NumElements))
  1759. return false;
  1760. // Otherwise, it is in-range.
  1761. return true;
  1762. }
  1763. // Combine Indices - If the source pointer to this getelementptr instruction
  1764. // is a getelementptr instruction, combine the indices of the two
  1765. // getelementptr instructions into a single instruction.
  1766. static Constant *foldGEPOfGEP(GEPOperator *GEP, Type *PointeeTy, bool InBounds,
  1767. ArrayRef<Value *> Idxs) {
  1768. if (PointeeTy != GEP->getResultElementType())
  1769. return nullptr;
  1770. Constant *Idx0 = cast<Constant>(Idxs[0]);
  1771. if (Idx0->isNullValue()) {
  1772. // Handle the simple case of a zero index.
  1773. SmallVector<Value*, 16> NewIndices;
  1774. NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
  1775. NewIndices.append(GEP->idx_begin(), GEP->idx_end());
  1776. NewIndices.append(Idxs.begin() + 1, Idxs.end());
  1777. return ConstantExpr::getGetElementPtr(
  1778. GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
  1779. NewIndices, InBounds && GEP->isInBounds(), GEP->getInRangeIndex());
  1780. }
  1781. gep_type_iterator LastI = gep_type_end(GEP);
  1782. for (gep_type_iterator I = gep_type_begin(GEP), E = gep_type_end(GEP);
  1783. I != E; ++I)
  1784. LastI = I;
  1785. // We can't combine GEPs if the last index is a struct type.
  1786. if (!LastI.isSequential())
  1787. return nullptr;
  1788. // We could perform the transform with non-constant index, but prefer leaving
  1789. // it as GEP of GEP rather than GEP of add for now.
  1790. ConstantInt *CI = dyn_cast<ConstantInt>(Idx0);
  1791. if (!CI)
  1792. return nullptr;
  1793. // TODO: This code may be extended to handle vectors as well.
  1794. auto *LastIdx = cast<Constant>(GEP->getOperand(GEP->getNumOperands()-1));
  1795. Type *LastIdxTy = LastIdx->getType();
  1796. if (LastIdxTy->isVectorTy())
  1797. return nullptr;
  1798. SmallVector<Value*, 16> NewIndices;
  1799. NewIndices.reserve(Idxs.size() + GEP->getNumIndices());
  1800. NewIndices.append(GEP->idx_begin(), GEP->idx_end() - 1);
  1801. // Add the last index of the source with the first index of the new GEP.
  1802. // Make sure to handle the case when they are actually different types.
  1803. if (LastIdxTy != Idx0->getType()) {
  1804. unsigned CommonExtendedWidth =
  1805. std::max(LastIdxTy->getIntegerBitWidth(),
  1806. Idx0->getType()->getIntegerBitWidth());
  1807. CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
  1808. Type *CommonTy =
  1809. Type::getIntNTy(LastIdxTy->getContext(), CommonExtendedWidth);
  1810. Idx0 = ConstantExpr::getSExtOrBitCast(Idx0, CommonTy);
  1811. LastIdx = ConstantExpr::getSExtOrBitCast(LastIdx, CommonTy);
  1812. }
  1813. NewIndices.push_back(ConstantExpr::get(Instruction::Add, Idx0, LastIdx));
  1814. NewIndices.append(Idxs.begin() + 1, Idxs.end());
  1815. // The combined GEP normally inherits its index inrange attribute from
  1816. // the inner GEP, but if the inner GEP's last index was adjusted by the
  1817. // outer GEP, any inbounds attribute on that index is invalidated.
  1818. Optional<unsigned> IRIndex = GEP->getInRangeIndex();
  1819. if (IRIndex && *IRIndex == GEP->getNumIndices() - 1)
  1820. IRIndex = None;
  1821. return ConstantExpr::getGetElementPtr(
  1822. GEP->getSourceElementType(), cast<Constant>(GEP->getPointerOperand()),
  1823. NewIndices, InBounds && GEP->isInBounds(), IRIndex);
  1824. }
  1825. Constant *llvm::ConstantFoldGetElementPtr(Type *PointeeTy, Constant *C,
  1826. bool InBounds,
  1827. Optional<unsigned> InRangeIndex,
  1828. ArrayRef<Value *> Idxs) {
  1829. if (Idxs.empty()) return C;
  1830. Type *GEPTy = GetElementPtrInst::getGEPReturnType(
  1831. PointeeTy, C, makeArrayRef((Value *const *)Idxs.data(), Idxs.size()));
  1832. if (isa<PoisonValue>(C))
  1833. return PoisonValue::get(GEPTy);
  1834. if (isa<UndefValue>(C))
  1835. // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
  1836. return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
  1837. Constant *Idx0 = cast<Constant>(Idxs[0]);
  1838. if (Idxs.size() == 1 && (Idx0->isNullValue() || isa<UndefValue>(Idx0)))
  1839. return GEPTy->isVectorTy() && !C->getType()->isVectorTy()
  1840. ? ConstantVector::getSplat(
  1841. cast<VectorType>(GEPTy)->getElementCount(), C)
  1842. : C;
  1843. if (C->isNullValue()) {
  1844. bool isNull = true;
  1845. for (Value *Idx : Idxs)
  1846. if (!isa<UndefValue>(Idx) && !cast<Constant>(Idx)->isNullValue()) {
  1847. isNull = false;
  1848. break;
  1849. }
  1850. if (isNull) {
  1851. PointerType *PtrTy = cast<PointerType>(C->getType()->getScalarType());
  1852. Type *Ty = GetElementPtrInst::getIndexedType(PointeeTy, Idxs);
  1853. assert(Ty && "Invalid indices for GEP!");
  1854. Type *OrigGEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
  1855. Type *GEPTy = PointerType::get(Ty, PtrTy->getAddressSpace());
  1856. if (VectorType *VT = dyn_cast<VectorType>(C->getType()))
  1857. GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
  1858. // The GEP returns a vector of pointers when one of more of
  1859. // its arguments is a vector.
  1860. for (Value *Idx : Idxs) {
  1861. if (auto *VT = dyn_cast<VectorType>(Idx->getType())) {
  1862. assert((!isa<VectorType>(GEPTy) || isa<ScalableVectorType>(GEPTy) ==
  1863. isa<ScalableVectorType>(VT)) &&
  1864. "Mismatched GEPTy vector types");
  1865. GEPTy = VectorType::get(OrigGEPTy, VT->getElementCount());
  1866. break;
  1867. }
  1868. }
  1869. return Constant::getNullValue(GEPTy);
  1870. }
  1871. }
  1872. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  1873. if (auto *GEP = dyn_cast<GEPOperator>(CE))
  1874. if (Constant *C = foldGEPOfGEP(GEP, PointeeTy, InBounds, Idxs))
  1875. return C;
  1876. // Attempt to fold casts to the same type away. For example, folding:
  1877. //
  1878. // i32* getelementptr ([2 x i32]* bitcast ([3 x i32]* %X to [2 x i32]*),
  1879. // i64 0, i64 0)
  1880. // into:
  1881. //
  1882. // i32* getelementptr ([3 x i32]* %X, i64 0, i64 0)
  1883. //
  1884. // Don't fold if the cast is changing address spaces.
  1885. if (CE->isCast() && Idxs.size() > 1 && Idx0->isNullValue()) {
  1886. PointerType *SrcPtrTy =
  1887. dyn_cast<PointerType>(CE->getOperand(0)->getType());
  1888. PointerType *DstPtrTy = dyn_cast<PointerType>(CE->getType());
  1889. if (SrcPtrTy && DstPtrTy && !SrcPtrTy->isOpaque() &&
  1890. !DstPtrTy->isOpaque()) {
  1891. ArrayType *SrcArrayTy =
  1892. dyn_cast<ArrayType>(SrcPtrTy->getNonOpaquePointerElementType());
  1893. ArrayType *DstArrayTy =
  1894. dyn_cast<ArrayType>(DstPtrTy->getNonOpaquePointerElementType());
  1895. if (SrcArrayTy && DstArrayTy
  1896. && SrcArrayTy->getElementType() == DstArrayTy->getElementType()
  1897. && SrcPtrTy->getAddressSpace() == DstPtrTy->getAddressSpace())
  1898. return ConstantExpr::getGetElementPtr(SrcArrayTy,
  1899. (Constant *)CE->getOperand(0),
  1900. Idxs, InBounds, InRangeIndex);
  1901. }
  1902. }
  1903. }
  1904. // Check to see if any array indices are not within the corresponding
  1905. // notional array or vector bounds. If so, try to determine if they can be
  1906. // factored out into preceding dimensions.
  1907. SmallVector<Constant *, 8> NewIdxs;
  1908. Type *Ty = PointeeTy;
  1909. Type *Prev = C->getType();
  1910. auto GEPIter = gep_type_begin(PointeeTy, Idxs);
  1911. bool Unknown =
  1912. !isa<ConstantInt>(Idxs[0]) && !isa<ConstantDataVector>(Idxs[0]);
  1913. for (unsigned i = 1, e = Idxs.size(); i != e;
  1914. Prev = Ty, Ty = (++GEPIter).getIndexedType(), ++i) {
  1915. if (!isa<ConstantInt>(Idxs[i]) && !isa<ConstantDataVector>(Idxs[i])) {
  1916. // We don't know if it's in range or not.
  1917. Unknown = true;
  1918. continue;
  1919. }
  1920. if (!isa<ConstantInt>(Idxs[i - 1]) && !isa<ConstantDataVector>(Idxs[i - 1]))
  1921. // Skip if the type of the previous index is not supported.
  1922. continue;
  1923. if (InRangeIndex && i == *InRangeIndex + 1) {
  1924. // If an index is marked inrange, we cannot apply this canonicalization to
  1925. // the following index, as that will cause the inrange index to point to
  1926. // the wrong element.
  1927. continue;
  1928. }
  1929. if (isa<StructType>(Ty)) {
  1930. // The verify makes sure that GEPs into a struct are in range.
  1931. continue;
  1932. }
  1933. if (isa<VectorType>(Ty)) {
  1934. // There can be awkward padding in after a non-power of two vector.
  1935. Unknown = true;
  1936. continue;
  1937. }
  1938. auto *STy = cast<ArrayType>(Ty);
  1939. if (ConstantInt *CI = dyn_cast<ConstantInt>(Idxs[i])) {
  1940. if (isIndexInRangeOfArrayType(STy->getNumElements(), CI))
  1941. // It's in range, skip to the next index.
  1942. continue;
  1943. if (CI->isNegative()) {
  1944. // It's out of range and negative, don't try to factor it.
  1945. Unknown = true;
  1946. continue;
  1947. }
  1948. } else {
  1949. auto *CV = cast<ConstantDataVector>(Idxs[i]);
  1950. bool InRange = true;
  1951. for (unsigned I = 0, E = CV->getNumElements(); I != E; ++I) {
  1952. auto *CI = cast<ConstantInt>(CV->getElementAsConstant(I));
  1953. InRange &= isIndexInRangeOfArrayType(STy->getNumElements(), CI);
  1954. if (CI->isNegative()) {
  1955. Unknown = true;
  1956. break;
  1957. }
  1958. }
  1959. if (InRange || Unknown)
  1960. // It's in range, skip to the next index.
  1961. // It's out of range and negative, don't try to factor it.
  1962. continue;
  1963. }
  1964. if (isa<StructType>(Prev)) {
  1965. // It's out of range, but the prior dimension is a struct
  1966. // so we can't do anything about it.
  1967. Unknown = true;
  1968. continue;
  1969. }
  1970. // It's out of range, but we can factor it into the prior
  1971. // dimension.
  1972. NewIdxs.resize(Idxs.size());
  1973. // Determine the number of elements in our sequential type.
  1974. uint64_t NumElements = STy->getArrayNumElements();
  1975. // Expand the current index or the previous index to a vector from a scalar
  1976. // if necessary.
  1977. Constant *CurrIdx = cast<Constant>(Idxs[i]);
  1978. auto *PrevIdx =
  1979. NewIdxs[i - 1] ? NewIdxs[i - 1] : cast<Constant>(Idxs[i - 1]);
  1980. bool IsCurrIdxVector = CurrIdx->getType()->isVectorTy();
  1981. bool IsPrevIdxVector = PrevIdx->getType()->isVectorTy();
  1982. bool UseVector = IsCurrIdxVector || IsPrevIdxVector;
  1983. if (!IsCurrIdxVector && IsPrevIdxVector)
  1984. CurrIdx = ConstantDataVector::getSplat(
  1985. cast<FixedVectorType>(PrevIdx->getType())->getNumElements(), CurrIdx);
  1986. if (!IsPrevIdxVector && IsCurrIdxVector)
  1987. PrevIdx = ConstantDataVector::getSplat(
  1988. cast<FixedVectorType>(CurrIdx->getType())->getNumElements(), PrevIdx);
  1989. Constant *Factor =
  1990. ConstantInt::get(CurrIdx->getType()->getScalarType(), NumElements);
  1991. if (UseVector)
  1992. Factor = ConstantDataVector::getSplat(
  1993. IsPrevIdxVector
  1994. ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
  1995. : cast<FixedVectorType>(CurrIdx->getType())->getNumElements(),
  1996. Factor);
  1997. NewIdxs[i] = ConstantExpr::getSRem(CurrIdx, Factor);
  1998. Constant *Div = ConstantExpr::getSDiv(CurrIdx, Factor);
  1999. unsigned CommonExtendedWidth =
  2000. std::max(PrevIdx->getType()->getScalarSizeInBits(),
  2001. Div->getType()->getScalarSizeInBits());
  2002. CommonExtendedWidth = std::max(CommonExtendedWidth, 64U);
  2003. // Before adding, extend both operands to i64 to avoid
  2004. // overflow trouble.
  2005. Type *ExtendedTy = Type::getIntNTy(Div->getContext(), CommonExtendedWidth);
  2006. if (UseVector)
  2007. ExtendedTy = FixedVectorType::get(
  2008. ExtendedTy,
  2009. IsPrevIdxVector
  2010. ? cast<FixedVectorType>(PrevIdx->getType())->getNumElements()
  2011. : cast<FixedVectorType>(CurrIdx->getType())->getNumElements());
  2012. if (!PrevIdx->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
  2013. PrevIdx = ConstantExpr::getSExt(PrevIdx, ExtendedTy);
  2014. if (!Div->getType()->isIntOrIntVectorTy(CommonExtendedWidth))
  2015. Div = ConstantExpr::getSExt(Div, ExtendedTy);
  2016. NewIdxs[i - 1] = ConstantExpr::getAdd(PrevIdx, Div);
  2017. }
  2018. // If we did any factoring, start over with the adjusted indices.
  2019. if (!NewIdxs.empty()) {
  2020. for (unsigned i = 0, e = Idxs.size(); i != e; ++i)
  2021. if (!NewIdxs[i]) NewIdxs[i] = cast<Constant>(Idxs[i]);
  2022. return ConstantExpr::getGetElementPtr(PointeeTy, C, NewIdxs, InBounds,
  2023. InRangeIndex);
  2024. }
  2025. // If all indices are known integers and normalized, we can do a simple
  2026. // check for the "inbounds" property.
  2027. if (!Unknown && !InBounds)
  2028. if (auto *GV = dyn_cast<GlobalVariable>(C))
  2029. if (!GV->hasExternalWeakLinkage() && isInBoundsIndices(Idxs))
  2030. return ConstantExpr::getGetElementPtr(PointeeTy, C, Idxs,
  2031. /*InBounds=*/true, InRangeIndex);
  2032. return nullptr;
  2033. }