Constants.cpp 108 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047
  1. //===-- Constants.cpp - Implement Constant nodes --------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Constant* classes.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/IR/Constants.h"
  13. #include "ConstantFold.h"
  14. #include "LLVMContextImpl.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/StringMap.h"
  18. #include "llvm/IR/DerivedTypes.h"
  19. #include "llvm/IR/GetElementPtrTypeIterator.h"
  20. #include "llvm/IR/GlobalValue.h"
  21. #include "llvm/IR/Instructions.h"
  22. #include "llvm/IR/Module.h"
  23. #include "llvm/IR/Operator.h"
  24. #include "llvm/IR/PatternMatch.h"
  25. #include "llvm/Support/Debug.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/ManagedStatic.h"
  28. #include "llvm/Support/MathExtras.h"
  29. #include "llvm/Support/raw_ostream.h"
  30. #include <algorithm>
  31. using namespace llvm;
  32. //===----------------------------------------------------------------------===//
  33. // Constant Class
  34. //===----------------------------------------------------------------------===//
  35. bool Constant::isNegativeZeroValue() const {
  36. // Floating point values have an explicit -0.0 value.
  37. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  38. return CFP->isZero() && CFP->isNegative();
  39. // Equivalent for a vector of -0.0's.
  40. if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
  41. if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
  42. if (CV->getElementAsAPFloat(0).isNegZero())
  43. return true;
  44. if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
  45. if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
  46. if (SplatCFP && SplatCFP->isZero() && SplatCFP->isNegative())
  47. return true;
  48. // We've already handled true FP case; any other FP vectors can't represent -0.0.
  49. if (getType()->isFPOrFPVectorTy())
  50. return false;
  51. // Otherwise, just use +0.0.
  52. return isNullValue();
  53. }
  54. // Return true iff this constant is positive zero (floating point), negative
  55. // zero (floating point), or a null value.
  56. bool Constant::isZeroValue() const {
  57. // Floating point values have an explicit -0.0 value.
  58. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  59. return CFP->isZero();
  60. // Equivalent for a vector of -0.0's.
  61. if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
  62. if (CV->getElementType()->isFloatingPointTy() && CV->isSplat())
  63. if (CV->getElementAsAPFloat(0).isZero())
  64. return true;
  65. if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
  66. if (ConstantFP *SplatCFP = dyn_cast_or_null<ConstantFP>(CV->getSplatValue()))
  67. if (SplatCFP && SplatCFP->isZero())
  68. return true;
  69. // Otherwise, just use +0.0.
  70. return isNullValue();
  71. }
  72. bool Constant::isNullValue() const {
  73. // 0 is null.
  74. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  75. return CI->isZero();
  76. // +0.0 is null.
  77. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  78. return CFP->isZero() && !CFP->isNegative();
  79. // constant zero is zero for aggregates, cpnull is null for pointers, none for
  80. // tokens.
  81. return isa<ConstantAggregateZero>(this) || isa<ConstantPointerNull>(this) ||
  82. isa<ConstantTokenNone>(this);
  83. }
  84. bool Constant::isAllOnesValue() const {
  85. // Check for -1 integers
  86. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  87. return CI->isMinusOne();
  88. // Check for FP which are bitcasted from -1 integers
  89. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  90. return CFP->getValueAPF().bitcastToAPInt().isAllOnesValue();
  91. // Check for constant vectors which are splats of -1 values.
  92. if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
  93. if (Constant *Splat = CV->getSplatValue())
  94. return Splat->isAllOnesValue();
  95. // Check for constant vectors which are splats of -1 values.
  96. if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
  97. if (CV->isSplat()) {
  98. if (CV->getElementType()->isFloatingPointTy())
  99. return CV->getElementAsAPFloat(0).bitcastToAPInt().isAllOnesValue();
  100. return CV->getElementAsAPInt(0).isAllOnesValue();
  101. }
  102. }
  103. return false;
  104. }
  105. bool Constant::isOneValue() const {
  106. // Check for 1 integers
  107. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  108. return CI->isOne();
  109. // Check for FP which are bitcasted from 1 integers
  110. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  111. return CFP->getValueAPF().bitcastToAPInt().isOneValue();
  112. // Check for constant vectors which are splats of 1 values.
  113. if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
  114. if (Constant *Splat = CV->getSplatValue())
  115. return Splat->isOneValue();
  116. // Check for constant vectors which are splats of 1 values.
  117. if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
  118. if (CV->isSplat()) {
  119. if (CV->getElementType()->isFloatingPointTy())
  120. return CV->getElementAsAPFloat(0).bitcastToAPInt().isOneValue();
  121. return CV->getElementAsAPInt(0).isOneValue();
  122. }
  123. }
  124. return false;
  125. }
  126. bool Constant::isMinSignedValue() const {
  127. // Check for INT_MIN integers
  128. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  129. return CI->isMinValue(/*isSigned=*/true);
  130. // Check for FP which are bitcasted from INT_MIN integers
  131. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  132. return CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
  133. // Check for constant vectors which are splats of INT_MIN values.
  134. if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
  135. if (Constant *Splat = CV->getSplatValue())
  136. return Splat->isMinSignedValue();
  137. // Check for constant vectors which are splats of INT_MIN values.
  138. if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this)) {
  139. if (CV->isSplat()) {
  140. if (CV->getElementType()->isFloatingPointTy())
  141. return CV->getElementAsAPFloat(0).bitcastToAPInt().isMinSignedValue();
  142. return CV->getElementAsAPInt(0).isMinSignedValue();
  143. }
  144. }
  145. return false;
  146. }
  147. bool Constant::isNotMinSignedValue() const {
  148. // Check for INT_MIN integers
  149. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  150. return !CI->isMinValue(/*isSigned=*/true);
  151. // Check for FP which are bitcasted from INT_MIN integers
  152. if (const ConstantFP *CFP = dyn_cast<ConstantFP>(this))
  153. return !CFP->getValueAPF().bitcastToAPInt().isMinSignedValue();
  154. // Check that vectors don't contain INT_MIN
  155. if (this->getType()->isVectorTy()) {
  156. unsigned NumElts = this->getType()->getVectorNumElements();
  157. for (unsigned i = 0; i != NumElts; ++i) {
  158. Constant *Elt = this->getAggregateElement(i);
  159. if (!Elt || !Elt->isNotMinSignedValue())
  160. return false;
  161. }
  162. return true;
  163. }
  164. // It *may* contain INT_MIN, we can't tell.
  165. return false;
  166. }
  167. bool Constant::isFiniteNonZeroFP() const {
  168. if (auto *CFP = dyn_cast<ConstantFP>(this))
  169. return CFP->getValueAPF().isFiniteNonZero();
  170. if (!getType()->isVectorTy())
  171. return false;
  172. for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
  173. auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
  174. if (!CFP || !CFP->getValueAPF().isFiniteNonZero())
  175. return false;
  176. }
  177. return true;
  178. }
  179. bool Constant::isNormalFP() const {
  180. if (auto *CFP = dyn_cast<ConstantFP>(this))
  181. return CFP->getValueAPF().isNormal();
  182. if (!getType()->isVectorTy())
  183. return false;
  184. for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
  185. auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
  186. if (!CFP || !CFP->getValueAPF().isNormal())
  187. return false;
  188. }
  189. return true;
  190. }
  191. bool Constant::hasExactInverseFP() const {
  192. if (auto *CFP = dyn_cast<ConstantFP>(this))
  193. return CFP->getValueAPF().getExactInverse(nullptr);
  194. if (!getType()->isVectorTy())
  195. return false;
  196. for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
  197. auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
  198. if (!CFP || !CFP->getValueAPF().getExactInverse(nullptr))
  199. return false;
  200. }
  201. return true;
  202. }
  203. bool Constant::isNaN() const {
  204. if (auto *CFP = dyn_cast<ConstantFP>(this))
  205. return CFP->isNaN();
  206. if (!getType()->isVectorTy())
  207. return false;
  208. for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i) {
  209. auto *CFP = dyn_cast_or_null<ConstantFP>(this->getAggregateElement(i));
  210. if (!CFP || !CFP->isNaN())
  211. return false;
  212. }
  213. return true;
  214. }
  215. bool Constant::isElementWiseEqual(Value *Y) const {
  216. // Are they fully identical?
  217. if (this == Y)
  218. return true;
  219. // They may still be identical element-wise (if they have `undef`s).
  220. auto *Cy = dyn_cast<Constant>(Y);
  221. if (!Cy)
  222. return false;
  223. return PatternMatch::match(ConstantExpr::getICmp(ICmpInst::Predicate::ICMP_EQ,
  224. const_cast<Constant *>(this),
  225. Cy),
  226. PatternMatch::m_One());
  227. }
  228. bool Constant::containsUndefElement() const {
  229. if (!getType()->isVectorTy())
  230. return false;
  231. for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
  232. if (isa<UndefValue>(getAggregateElement(i)))
  233. return true;
  234. return false;
  235. }
  236. bool Constant::containsConstantExpression() const {
  237. if (!getType()->isVectorTy())
  238. return false;
  239. for (unsigned i = 0, e = getType()->getVectorNumElements(); i != e; ++i)
  240. if (isa<ConstantExpr>(getAggregateElement(i)))
  241. return true;
  242. return false;
  243. }
  244. /// Constructor to create a '0' constant of arbitrary type.
  245. Constant *Constant::getNullValue(Type *Ty) {
  246. switch (Ty->getTypeID()) {
  247. case Type::IntegerTyID:
  248. return ConstantInt::get(Ty, 0);
  249. case Type::HalfTyID:
  250. return ConstantFP::get(Ty->getContext(),
  251. APFloat::getZero(APFloat::IEEEhalf()));
  252. case Type::FloatTyID:
  253. return ConstantFP::get(Ty->getContext(),
  254. APFloat::getZero(APFloat::IEEEsingle()));
  255. case Type::DoubleTyID:
  256. return ConstantFP::get(Ty->getContext(),
  257. APFloat::getZero(APFloat::IEEEdouble()));
  258. case Type::X86_FP80TyID:
  259. return ConstantFP::get(Ty->getContext(),
  260. APFloat::getZero(APFloat::x87DoubleExtended()));
  261. case Type::FP128TyID:
  262. return ConstantFP::get(Ty->getContext(),
  263. APFloat::getZero(APFloat::IEEEquad()));
  264. case Type::PPC_FP128TyID:
  265. return ConstantFP::get(Ty->getContext(),
  266. APFloat(APFloat::PPCDoubleDouble(),
  267. APInt::getNullValue(128)));
  268. case Type::PointerTyID:
  269. return ConstantPointerNull::get(cast<PointerType>(Ty));
  270. case Type::StructTyID:
  271. case Type::ArrayTyID:
  272. case Type::VectorTyID:
  273. return ConstantAggregateZero::get(Ty);
  274. case Type::TokenTyID:
  275. return ConstantTokenNone::get(Ty->getContext());
  276. default:
  277. // Function, Label, or Opaque type?
  278. llvm_unreachable("Cannot create a null constant of that type!");
  279. }
  280. }
  281. Constant *Constant::getIntegerValue(Type *Ty, const APInt &V) {
  282. Type *ScalarTy = Ty->getScalarType();
  283. // Create the base integer constant.
  284. Constant *C = ConstantInt::get(Ty->getContext(), V);
  285. // Convert an integer to a pointer, if necessary.
  286. if (PointerType *PTy = dyn_cast<PointerType>(ScalarTy))
  287. C = ConstantExpr::getIntToPtr(C, PTy);
  288. // Broadcast a scalar to a vector, if necessary.
  289. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  290. C = ConstantVector::getSplat(VTy->getNumElements(), C);
  291. return C;
  292. }
  293. Constant *Constant::getAllOnesValue(Type *Ty) {
  294. if (IntegerType *ITy = dyn_cast<IntegerType>(Ty))
  295. return ConstantInt::get(Ty->getContext(),
  296. APInt::getAllOnesValue(ITy->getBitWidth()));
  297. if (Ty->isFloatingPointTy()) {
  298. APFloat FL = APFloat::getAllOnesValue(Ty->getPrimitiveSizeInBits(),
  299. !Ty->isPPC_FP128Ty());
  300. return ConstantFP::get(Ty->getContext(), FL);
  301. }
  302. VectorType *VTy = cast<VectorType>(Ty);
  303. return ConstantVector::getSplat(VTy->getNumElements(),
  304. getAllOnesValue(VTy->getElementType()));
  305. }
  306. Constant *Constant::getAggregateElement(unsigned Elt) const {
  307. if (const ConstantAggregate *CC = dyn_cast<ConstantAggregate>(this))
  308. return Elt < CC->getNumOperands() ? CC->getOperand(Elt) : nullptr;
  309. if (const ConstantAggregateZero *CAZ = dyn_cast<ConstantAggregateZero>(this))
  310. return Elt < CAZ->getNumElements() ? CAZ->getElementValue(Elt) : nullptr;
  311. if (const UndefValue *UV = dyn_cast<UndefValue>(this))
  312. return Elt < UV->getNumElements() ? UV->getElementValue(Elt) : nullptr;
  313. if (const ConstantDataSequential *CDS =dyn_cast<ConstantDataSequential>(this))
  314. return Elt < CDS->getNumElements() ? CDS->getElementAsConstant(Elt)
  315. : nullptr;
  316. return nullptr;
  317. }
  318. Constant *Constant::getAggregateElement(Constant *Elt) const {
  319. assert(isa<IntegerType>(Elt->getType()) && "Index must be an integer");
  320. if (ConstantInt *CI = dyn_cast<ConstantInt>(Elt)) {
  321. // Check if the constant fits into an uint64_t.
  322. if (CI->getValue().getActiveBits() > 64)
  323. return nullptr;
  324. return getAggregateElement(CI->getZExtValue());
  325. }
  326. return nullptr;
  327. }
  328. void Constant::destroyConstant() {
  329. /// First call destroyConstantImpl on the subclass. This gives the subclass
  330. /// a chance to remove the constant from any maps/pools it's contained in.
  331. switch (getValueID()) {
  332. default:
  333. llvm_unreachable("Not a constant!");
  334. #define HANDLE_CONSTANT(Name) \
  335. case Value::Name##Val: \
  336. cast<Name>(this)->destroyConstantImpl(); \
  337. break;
  338. #include "llvm/IR/Value.def"
  339. }
  340. // When a Constant is destroyed, there may be lingering
  341. // references to the constant by other constants in the constant pool. These
  342. // constants are implicitly dependent on the module that is being deleted,
  343. // but they don't know that. Because we only find out when the CPV is
  344. // deleted, we must now notify all of our users (that should only be
  345. // Constants) that they are, in fact, invalid now and should be deleted.
  346. //
  347. while (!use_empty()) {
  348. Value *V = user_back();
  349. #ifndef NDEBUG // Only in -g mode...
  350. if (!isa<Constant>(V)) {
  351. dbgs() << "While deleting: " << *this
  352. << "\n\nUse still stuck around after Def is destroyed: " << *V
  353. << "\n\n";
  354. }
  355. #endif
  356. assert(isa<Constant>(V) && "References remain to Constant being destroyed");
  357. cast<Constant>(V)->destroyConstant();
  358. // The constant should remove itself from our use list...
  359. assert((use_empty() || user_back() != V) && "Constant not removed!");
  360. }
  361. // Value has no outstanding references it is safe to delete it now...
  362. delete this;
  363. }
  364. static bool canTrapImpl(const Constant *C,
  365. SmallPtrSetImpl<const ConstantExpr *> &NonTrappingOps) {
  366. assert(C->getType()->isFirstClassType() && "Cannot evaluate aggregate vals!");
  367. // The only thing that could possibly trap are constant exprs.
  368. const ConstantExpr *CE = dyn_cast<ConstantExpr>(C);
  369. if (!CE)
  370. return false;
  371. // ConstantExpr traps if any operands can trap.
  372. for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
  373. if (ConstantExpr *Op = dyn_cast<ConstantExpr>(CE->getOperand(i))) {
  374. if (NonTrappingOps.insert(Op).second && canTrapImpl(Op, NonTrappingOps))
  375. return true;
  376. }
  377. }
  378. // Otherwise, only specific operations can trap.
  379. switch (CE->getOpcode()) {
  380. default:
  381. return false;
  382. case Instruction::UDiv:
  383. case Instruction::SDiv:
  384. case Instruction::URem:
  385. case Instruction::SRem:
  386. // Div and rem can trap if the RHS is not known to be non-zero.
  387. if (!isa<ConstantInt>(CE->getOperand(1)) ||CE->getOperand(1)->isNullValue())
  388. return true;
  389. return false;
  390. }
  391. }
  392. bool Constant::canTrap() const {
  393. SmallPtrSet<const ConstantExpr *, 4> NonTrappingOps;
  394. return canTrapImpl(this, NonTrappingOps);
  395. }
  396. /// Check if C contains a GlobalValue for which Predicate is true.
  397. static bool
  398. ConstHasGlobalValuePredicate(const Constant *C,
  399. bool (*Predicate)(const GlobalValue *)) {
  400. SmallPtrSet<const Constant *, 8> Visited;
  401. SmallVector<const Constant *, 8> WorkList;
  402. WorkList.push_back(C);
  403. Visited.insert(C);
  404. while (!WorkList.empty()) {
  405. const Constant *WorkItem = WorkList.pop_back_val();
  406. if (const auto *GV = dyn_cast<GlobalValue>(WorkItem))
  407. if (Predicate(GV))
  408. return true;
  409. for (const Value *Op : WorkItem->operands()) {
  410. const Constant *ConstOp = dyn_cast<Constant>(Op);
  411. if (!ConstOp)
  412. continue;
  413. if (Visited.insert(ConstOp).second)
  414. WorkList.push_back(ConstOp);
  415. }
  416. }
  417. return false;
  418. }
  419. bool Constant::isThreadDependent() const {
  420. auto DLLImportPredicate = [](const GlobalValue *GV) {
  421. return GV->isThreadLocal();
  422. };
  423. return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
  424. }
  425. bool Constant::isDLLImportDependent() const {
  426. auto DLLImportPredicate = [](const GlobalValue *GV) {
  427. return GV->hasDLLImportStorageClass();
  428. };
  429. return ConstHasGlobalValuePredicate(this, DLLImportPredicate);
  430. }
  431. bool Constant::isConstantUsed() const {
  432. for (const User *U : users()) {
  433. const Constant *UC = dyn_cast<Constant>(U);
  434. if (!UC || isa<GlobalValue>(UC))
  435. return true;
  436. if (UC->isConstantUsed())
  437. return true;
  438. }
  439. return false;
  440. }
  441. bool Constant::needsRelocation() const {
  442. if (isa<GlobalValue>(this))
  443. return true; // Global reference.
  444. if (const BlockAddress *BA = dyn_cast<BlockAddress>(this))
  445. return BA->getFunction()->needsRelocation();
  446. if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(this)) {
  447. if (CE->getOpcode() == Instruction::Sub) {
  448. ConstantExpr *LHS = dyn_cast<ConstantExpr>(CE->getOperand(0));
  449. ConstantExpr *RHS = dyn_cast<ConstantExpr>(CE->getOperand(1));
  450. if (LHS && RHS && LHS->getOpcode() == Instruction::PtrToInt &&
  451. RHS->getOpcode() == Instruction::PtrToInt) {
  452. Constant *LHSOp0 = LHS->getOperand(0);
  453. Constant *RHSOp0 = RHS->getOperand(0);
  454. // While raw uses of blockaddress need to be relocated, differences
  455. // between two of them don't when they are for labels in the same
  456. // function. This is a common idiom when creating a table for the
  457. // indirect goto extension, so we handle it efficiently here.
  458. if (isa<BlockAddress>(LHSOp0) && isa<BlockAddress>(RHSOp0) &&
  459. cast<BlockAddress>(LHSOp0)->getFunction() ==
  460. cast<BlockAddress>(RHSOp0)->getFunction())
  461. return false;
  462. // Relative pointers do not need to be dynamically relocated.
  463. if (auto *LHSGV = dyn_cast<GlobalValue>(LHSOp0->stripPointerCasts()))
  464. if (auto *RHSGV = dyn_cast<GlobalValue>(RHSOp0->stripPointerCasts()))
  465. if (LHSGV->isDSOLocal() && RHSGV->isDSOLocal())
  466. return false;
  467. }
  468. }
  469. }
  470. bool Result = false;
  471. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  472. Result |= cast<Constant>(getOperand(i))->needsRelocation();
  473. return Result;
  474. }
  475. /// If the specified constantexpr is dead, remove it. This involves recursively
  476. /// eliminating any dead users of the constantexpr.
  477. static bool removeDeadUsersOfConstant(const Constant *C) {
  478. if (isa<GlobalValue>(C)) return false; // Cannot remove this
  479. while (!C->use_empty()) {
  480. const Constant *User = dyn_cast<Constant>(C->user_back());
  481. if (!User) return false; // Non-constant usage;
  482. if (!removeDeadUsersOfConstant(User))
  483. return false; // Constant wasn't dead
  484. }
  485. const_cast<Constant*>(C)->destroyConstant();
  486. return true;
  487. }
  488. void Constant::removeDeadConstantUsers() const {
  489. Value::const_user_iterator I = user_begin(), E = user_end();
  490. Value::const_user_iterator LastNonDeadUser = E;
  491. while (I != E) {
  492. const Constant *User = dyn_cast<Constant>(*I);
  493. if (!User) {
  494. LastNonDeadUser = I;
  495. ++I;
  496. continue;
  497. }
  498. if (!removeDeadUsersOfConstant(User)) {
  499. // If the constant wasn't dead, remember that this was the last live use
  500. // and move on to the next constant.
  501. LastNonDeadUser = I;
  502. ++I;
  503. continue;
  504. }
  505. // If the constant was dead, then the iterator is invalidated.
  506. if (LastNonDeadUser == E)
  507. I = user_begin();
  508. else
  509. I = std::next(LastNonDeadUser);
  510. }
  511. }
  512. //===----------------------------------------------------------------------===//
  513. // ConstantInt
  514. //===----------------------------------------------------------------------===//
  515. ConstantInt::ConstantInt(IntegerType *Ty, const APInt &V)
  516. : ConstantData(Ty, ConstantIntVal), Val(V) {
  517. assert(V.getBitWidth() == Ty->getBitWidth() && "Invalid constant for type");
  518. }
  519. ConstantInt *ConstantInt::getTrue(LLVMContext &Context) {
  520. LLVMContextImpl *pImpl = Context.pImpl;
  521. if (!pImpl->TheTrueVal)
  522. pImpl->TheTrueVal = ConstantInt::get(Type::getInt1Ty(Context), 1);
  523. return pImpl->TheTrueVal;
  524. }
  525. ConstantInt *ConstantInt::getFalse(LLVMContext &Context) {
  526. LLVMContextImpl *pImpl = Context.pImpl;
  527. if (!pImpl->TheFalseVal)
  528. pImpl->TheFalseVal = ConstantInt::get(Type::getInt1Ty(Context), 0);
  529. return pImpl->TheFalseVal;
  530. }
  531. Constant *ConstantInt::getTrue(Type *Ty) {
  532. assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
  533. ConstantInt *TrueC = ConstantInt::getTrue(Ty->getContext());
  534. if (auto *VTy = dyn_cast<VectorType>(Ty))
  535. return ConstantVector::getSplat(VTy->getNumElements(), TrueC);
  536. return TrueC;
  537. }
  538. Constant *ConstantInt::getFalse(Type *Ty) {
  539. assert(Ty->isIntOrIntVectorTy(1) && "Type not i1 or vector of i1.");
  540. ConstantInt *FalseC = ConstantInt::getFalse(Ty->getContext());
  541. if (auto *VTy = dyn_cast<VectorType>(Ty))
  542. return ConstantVector::getSplat(VTy->getNumElements(), FalseC);
  543. return FalseC;
  544. }
  545. // Get a ConstantInt from an APInt.
  546. ConstantInt *ConstantInt::get(LLVMContext &Context, const APInt &V) {
  547. // get an existing value or the insertion position
  548. LLVMContextImpl *pImpl = Context.pImpl;
  549. std::unique_ptr<ConstantInt> &Slot = pImpl->IntConstants[V];
  550. if (!Slot) {
  551. // Get the corresponding integer type for the bit width of the value.
  552. IntegerType *ITy = IntegerType::get(Context, V.getBitWidth());
  553. Slot.reset(new ConstantInt(ITy, V));
  554. }
  555. assert(Slot->getType() == IntegerType::get(Context, V.getBitWidth()));
  556. return Slot.get();
  557. }
  558. Constant *ConstantInt::get(Type *Ty, uint64_t V, bool isSigned) {
  559. Constant *C = get(cast<IntegerType>(Ty->getScalarType()), V, isSigned);
  560. // For vectors, broadcast the value.
  561. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  562. return ConstantVector::getSplat(VTy->getNumElements(), C);
  563. return C;
  564. }
  565. ConstantInt *ConstantInt::get(IntegerType *Ty, uint64_t V, bool isSigned) {
  566. return get(Ty->getContext(), APInt(Ty->getBitWidth(), V, isSigned));
  567. }
  568. ConstantInt *ConstantInt::getSigned(IntegerType *Ty, int64_t V) {
  569. return get(Ty, V, true);
  570. }
  571. Constant *ConstantInt::getSigned(Type *Ty, int64_t V) {
  572. return get(Ty, V, true);
  573. }
  574. Constant *ConstantInt::get(Type *Ty, const APInt& V) {
  575. ConstantInt *C = get(Ty->getContext(), V);
  576. assert(C->getType() == Ty->getScalarType() &&
  577. "ConstantInt type doesn't match the type implied by its value!");
  578. // For vectors, broadcast the value.
  579. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  580. return ConstantVector::getSplat(VTy->getNumElements(), C);
  581. return C;
  582. }
  583. ConstantInt *ConstantInt::get(IntegerType* Ty, StringRef Str, uint8_t radix) {
  584. return get(Ty->getContext(), APInt(Ty->getBitWidth(), Str, radix));
  585. }
  586. /// Remove the constant from the constant table.
  587. void ConstantInt::destroyConstantImpl() {
  588. llvm_unreachable("You can't ConstantInt->destroyConstantImpl()!");
  589. }
  590. //===----------------------------------------------------------------------===//
  591. // ConstantFP
  592. //===----------------------------------------------------------------------===//
  593. static const fltSemantics *TypeToFloatSemantics(Type *Ty) {
  594. if (Ty->isHalfTy())
  595. return &APFloat::IEEEhalf();
  596. if (Ty->isFloatTy())
  597. return &APFloat::IEEEsingle();
  598. if (Ty->isDoubleTy())
  599. return &APFloat::IEEEdouble();
  600. if (Ty->isX86_FP80Ty())
  601. return &APFloat::x87DoubleExtended();
  602. else if (Ty->isFP128Ty())
  603. return &APFloat::IEEEquad();
  604. assert(Ty->isPPC_FP128Ty() && "Unknown FP format");
  605. return &APFloat::PPCDoubleDouble();
  606. }
  607. Constant *ConstantFP::get(Type *Ty, double V) {
  608. LLVMContext &Context = Ty->getContext();
  609. APFloat FV(V);
  610. bool ignored;
  611. FV.convert(*TypeToFloatSemantics(Ty->getScalarType()),
  612. APFloat::rmNearestTiesToEven, &ignored);
  613. Constant *C = get(Context, FV);
  614. // For vectors, broadcast the value.
  615. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  616. return ConstantVector::getSplat(VTy->getNumElements(), C);
  617. return C;
  618. }
  619. Constant *ConstantFP::get(Type *Ty, const APFloat &V) {
  620. ConstantFP *C = get(Ty->getContext(), V);
  621. assert(C->getType() == Ty->getScalarType() &&
  622. "ConstantFP type doesn't match the type implied by its value!");
  623. // For vectors, broadcast the value.
  624. if (auto *VTy = dyn_cast<VectorType>(Ty))
  625. return ConstantVector::getSplat(VTy->getNumElements(), C);
  626. return C;
  627. }
  628. Constant *ConstantFP::get(Type *Ty, StringRef Str) {
  629. LLVMContext &Context = Ty->getContext();
  630. APFloat FV(*TypeToFloatSemantics(Ty->getScalarType()), Str);
  631. Constant *C = get(Context, FV);
  632. // For vectors, broadcast the value.
  633. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  634. return ConstantVector::getSplat(VTy->getNumElements(), C);
  635. return C;
  636. }
  637. Constant *ConstantFP::getNaN(Type *Ty, bool Negative, uint64_t Payload) {
  638. const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
  639. APFloat NaN = APFloat::getNaN(Semantics, Negative, Payload);
  640. Constant *C = get(Ty->getContext(), NaN);
  641. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  642. return ConstantVector::getSplat(VTy->getNumElements(), C);
  643. return C;
  644. }
  645. Constant *ConstantFP::getQNaN(Type *Ty, bool Negative, APInt *Payload) {
  646. const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
  647. APFloat NaN = APFloat::getQNaN(Semantics, Negative, Payload);
  648. Constant *C = get(Ty->getContext(), NaN);
  649. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  650. return ConstantVector::getSplat(VTy->getNumElements(), C);
  651. return C;
  652. }
  653. Constant *ConstantFP::getSNaN(Type *Ty, bool Negative, APInt *Payload) {
  654. const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
  655. APFloat NaN = APFloat::getSNaN(Semantics, Negative, Payload);
  656. Constant *C = get(Ty->getContext(), NaN);
  657. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  658. return ConstantVector::getSplat(VTy->getNumElements(), C);
  659. return C;
  660. }
  661. Constant *ConstantFP::getNegativeZero(Type *Ty) {
  662. const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
  663. APFloat NegZero = APFloat::getZero(Semantics, /*Negative=*/true);
  664. Constant *C = get(Ty->getContext(), NegZero);
  665. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  666. return ConstantVector::getSplat(VTy->getNumElements(), C);
  667. return C;
  668. }
  669. Constant *ConstantFP::getZeroValueForNegation(Type *Ty) {
  670. if (Ty->isFPOrFPVectorTy())
  671. return getNegativeZero(Ty);
  672. return Constant::getNullValue(Ty);
  673. }
  674. // ConstantFP accessors.
  675. ConstantFP* ConstantFP::get(LLVMContext &Context, const APFloat& V) {
  676. LLVMContextImpl* pImpl = Context.pImpl;
  677. std::unique_ptr<ConstantFP> &Slot = pImpl->FPConstants[V];
  678. if (!Slot) {
  679. Type *Ty;
  680. if (&V.getSemantics() == &APFloat::IEEEhalf())
  681. Ty = Type::getHalfTy(Context);
  682. else if (&V.getSemantics() == &APFloat::IEEEsingle())
  683. Ty = Type::getFloatTy(Context);
  684. else if (&V.getSemantics() == &APFloat::IEEEdouble())
  685. Ty = Type::getDoubleTy(Context);
  686. else if (&V.getSemantics() == &APFloat::x87DoubleExtended())
  687. Ty = Type::getX86_FP80Ty(Context);
  688. else if (&V.getSemantics() == &APFloat::IEEEquad())
  689. Ty = Type::getFP128Ty(Context);
  690. else {
  691. assert(&V.getSemantics() == &APFloat::PPCDoubleDouble() &&
  692. "Unknown FP format");
  693. Ty = Type::getPPC_FP128Ty(Context);
  694. }
  695. Slot.reset(new ConstantFP(Ty, V));
  696. }
  697. return Slot.get();
  698. }
  699. Constant *ConstantFP::getInfinity(Type *Ty, bool Negative) {
  700. const fltSemantics &Semantics = *TypeToFloatSemantics(Ty->getScalarType());
  701. Constant *C = get(Ty->getContext(), APFloat::getInf(Semantics, Negative));
  702. if (VectorType *VTy = dyn_cast<VectorType>(Ty))
  703. return ConstantVector::getSplat(VTy->getNumElements(), C);
  704. return C;
  705. }
  706. ConstantFP::ConstantFP(Type *Ty, const APFloat &V)
  707. : ConstantData(Ty, ConstantFPVal), Val(V) {
  708. assert(&V.getSemantics() == TypeToFloatSemantics(Ty) &&
  709. "FP type Mismatch");
  710. }
  711. bool ConstantFP::isExactlyValue(const APFloat &V) const {
  712. return Val.bitwiseIsEqual(V);
  713. }
  714. /// Remove the constant from the constant table.
  715. void ConstantFP::destroyConstantImpl() {
  716. llvm_unreachable("You can't ConstantFP->destroyConstantImpl()!");
  717. }
  718. //===----------------------------------------------------------------------===//
  719. // ConstantAggregateZero Implementation
  720. //===----------------------------------------------------------------------===//
  721. Constant *ConstantAggregateZero::getSequentialElement() const {
  722. return Constant::getNullValue(getType()->getSequentialElementType());
  723. }
  724. Constant *ConstantAggregateZero::getStructElement(unsigned Elt) const {
  725. return Constant::getNullValue(getType()->getStructElementType(Elt));
  726. }
  727. Constant *ConstantAggregateZero::getElementValue(Constant *C) const {
  728. if (isa<SequentialType>(getType()))
  729. return getSequentialElement();
  730. return getStructElement(cast<ConstantInt>(C)->getZExtValue());
  731. }
  732. Constant *ConstantAggregateZero::getElementValue(unsigned Idx) const {
  733. if (isa<SequentialType>(getType()))
  734. return getSequentialElement();
  735. return getStructElement(Idx);
  736. }
  737. unsigned ConstantAggregateZero::getNumElements() const {
  738. Type *Ty = getType();
  739. if (auto *AT = dyn_cast<ArrayType>(Ty))
  740. return AT->getNumElements();
  741. if (auto *VT = dyn_cast<VectorType>(Ty))
  742. return VT->getNumElements();
  743. return Ty->getStructNumElements();
  744. }
  745. //===----------------------------------------------------------------------===//
  746. // UndefValue Implementation
  747. //===----------------------------------------------------------------------===//
  748. UndefValue *UndefValue::getSequentialElement() const {
  749. return UndefValue::get(getType()->getSequentialElementType());
  750. }
  751. UndefValue *UndefValue::getStructElement(unsigned Elt) const {
  752. return UndefValue::get(getType()->getStructElementType(Elt));
  753. }
  754. UndefValue *UndefValue::getElementValue(Constant *C) const {
  755. if (isa<SequentialType>(getType()))
  756. return getSequentialElement();
  757. return getStructElement(cast<ConstantInt>(C)->getZExtValue());
  758. }
  759. UndefValue *UndefValue::getElementValue(unsigned Idx) const {
  760. if (isa<SequentialType>(getType()))
  761. return getSequentialElement();
  762. return getStructElement(Idx);
  763. }
  764. unsigned UndefValue::getNumElements() const {
  765. Type *Ty = getType();
  766. if (auto *ST = dyn_cast<SequentialType>(Ty))
  767. return ST->getNumElements();
  768. return Ty->getStructNumElements();
  769. }
  770. //===----------------------------------------------------------------------===//
  771. // ConstantXXX Classes
  772. //===----------------------------------------------------------------------===//
  773. template <typename ItTy, typename EltTy>
  774. static bool rangeOnlyContains(ItTy Start, ItTy End, EltTy Elt) {
  775. for (; Start != End; ++Start)
  776. if (*Start != Elt)
  777. return false;
  778. return true;
  779. }
  780. template <typename SequentialTy, typename ElementTy>
  781. static Constant *getIntSequenceIfElementsMatch(ArrayRef<Constant *> V) {
  782. assert(!V.empty() && "Cannot get empty int sequence.");
  783. SmallVector<ElementTy, 16> Elts;
  784. for (Constant *C : V)
  785. if (auto *CI = dyn_cast<ConstantInt>(C))
  786. Elts.push_back(CI->getZExtValue());
  787. else
  788. return nullptr;
  789. return SequentialTy::get(V[0]->getContext(), Elts);
  790. }
  791. template <typename SequentialTy, typename ElementTy>
  792. static Constant *getFPSequenceIfElementsMatch(ArrayRef<Constant *> V) {
  793. assert(!V.empty() && "Cannot get empty FP sequence.");
  794. SmallVector<ElementTy, 16> Elts;
  795. for (Constant *C : V)
  796. if (auto *CFP = dyn_cast<ConstantFP>(C))
  797. Elts.push_back(CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  798. else
  799. return nullptr;
  800. return SequentialTy::getFP(V[0]->getContext(), Elts);
  801. }
  802. template <typename SequenceTy>
  803. static Constant *getSequenceIfElementsMatch(Constant *C,
  804. ArrayRef<Constant *> V) {
  805. // We speculatively build the elements here even if it turns out that there is
  806. // a constantexpr or something else weird, since it is so uncommon for that to
  807. // happen.
  808. if (ConstantInt *CI = dyn_cast<ConstantInt>(C)) {
  809. if (CI->getType()->isIntegerTy(8))
  810. return getIntSequenceIfElementsMatch<SequenceTy, uint8_t>(V);
  811. else if (CI->getType()->isIntegerTy(16))
  812. return getIntSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
  813. else if (CI->getType()->isIntegerTy(32))
  814. return getIntSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
  815. else if (CI->getType()->isIntegerTy(64))
  816. return getIntSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
  817. } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(C)) {
  818. if (CFP->getType()->isHalfTy())
  819. return getFPSequenceIfElementsMatch<SequenceTy, uint16_t>(V);
  820. else if (CFP->getType()->isFloatTy())
  821. return getFPSequenceIfElementsMatch<SequenceTy, uint32_t>(V);
  822. else if (CFP->getType()->isDoubleTy())
  823. return getFPSequenceIfElementsMatch<SequenceTy, uint64_t>(V);
  824. }
  825. return nullptr;
  826. }
  827. ConstantAggregate::ConstantAggregate(CompositeType *T, ValueTy VT,
  828. ArrayRef<Constant *> V)
  829. : Constant(T, VT, OperandTraits<ConstantAggregate>::op_end(this) - V.size(),
  830. V.size()) {
  831. llvm::copy(V, op_begin());
  832. // Check that types match, unless this is an opaque struct.
  833. if (auto *ST = dyn_cast<StructType>(T))
  834. if (ST->isOpaque())
  835. return;
  836. for (unsigned I = 0, E = V.size(); I != E; ++I)
  837. assert(V[I]->getType() == T->getTypeAtIndex(I) &&
  838. "Initializer for composite element doesn't match!");
  839. }
  840. ConstantArray::ConstantArray(ArrayType *T, ArrayRef<Constant *> V)
  841. : ConstantAggregate(T, ConstantArrayVal, V) {
  842. assert(V.size() == T->getNumElements() &&
  843. "Invalid initializer for constant array");
  844. }
  845. Constant *ConstantArray::get(ArrayType *Ty, ArrayRef<Constant*> V) {
  846. if (Constant *C = getImpl(Ty, V))
  847. return C;
  848. return Ty->getContext().pImpl->ArrayConstants.getOrCreate(Ty, V);
  849. }
  850. Constant *ConstantArray::getImpl(ArrayType *Ty, ArrayRef<Constant*> V) {
  851. // Empty arrays are canonicalized to ConstantAggregateZero.
  852. if (V.empty())
  853. return ConstantAggregateZero::get(Ty);
  854. for (unsigned i = 0, e = V.size(); i != e; ++i) {
  855. assert(V[i]->getType() == Ty->getElementType() &&
  856. "Wrong type in array element initializer");
  857. }
  858. // If this is an all-zero array, return a ConstantAggregateZero object. If
  859. // all undef, return an UndefValue, if "all simple", then return a
  860. // ConstantDataArray.
  861. Constant *C = V[0];
  862. if (isa<UndefValue>(C) && rangeOnlyContains(V.begin(), V.end(), C))
  863. return UndefValue::get(Ty);
  864. if (C->isNullValue() && rangeOnlyContains(V.begin(), V.end(), C))
  865. return ConstantAggregateZero::get(Ty);
  866. // Check to see if all of the elements are ConstantFP or ConstantInt and if
  867. // the element type is compatible with ConstantDataVector. If so, use it.
  868. if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
  869. return getSequenceIfElementsMatch<ConstantDataArray>(C, V);
  870. // Otherwise, we really do want to create a ConstantArray.
  871. return nullptr;
  872. }
  873. StructType *ConstantStruct::getTypeForElements(LLVMContext &Context,
  874. ArrayRef<Constant*> V,
  875. bool Packed) {
  876. unsigned VecSize = V.size();
  877. SmallVector<Type*, 16> EltTypes(VecSize);
  878. for (unsigned i = 0; i != VecSize; ++i)
  879. EltTypes[i] = V[i]->getType();
  880. return StructType::get(Context, EltTypes, Packed);
  881. }
  882. StructType *ConstantStruct::getTypeForElements(ArrayRef<Constant*> V,
  883. bool Packed) {
  884. assert(!V.empty() &&
  885. "ConstantStruct::getTypeForElements cannot be called on empty list");
  886. return getTypeForElements(V[0]->getContext(), V, Packed);
  887. }
  888. ConstantStruct::ConstantStruct(StructType *T, ArrayRef<Constant *> V)
  889. : ConstantAggregate(T, ConstantStructVal, V) {
  890. assert((T->isOpaque() || V.size() == T->getNumElements()) &&
  891. "Invalid initializer for constant struct");
  892. }
  893. // ConstantStruct accessors.
  894. Constant *ConstantStruct::get(StructType *ST, ArrayRef<Constant*> V) {
  895. assert((ST->isOpaque() || ST->getNumElements() == V.size()) &&
  896. "Incorrect # elements specified to ConstantStruct::get");
  897. // Create a ConstantAggregateZero value if all elements are zeros.
  898. bool isZero = true;
  899. bool isUndef = false;
  900. if (!V.empty()) {
  901. isUndef = isa<UndefValue>(V[0]);
  902. isZero = V[0]->isNullValue();
  903. if (isUndef || isZero) {
  904. for (unsigned i = 0, e = V.size(); i != e; ++i) {
  905. if (!V[i]->isNullValue())
  906. isZero = false;
  907. if (!isa<UndefValue>(V[i]))
  908. isUndef = false;
  909. }
  910. }
  911. }
  912. if (isZero)
  913. return ConstantAggregateZero::get(ST);
  914. if (isUndef)
  915. return UndefValue::get(ST);
  916. return ST->getContext().pImpl->StructConstants.getOrCreate(ST, V);
  917. }
  918. ConstantVector::ConstantVector(VectorType *T, ArrayRef<Constant *> V)
  919. : ConstantAggregate(T, ConstantVectorVal, V) {
  920. assert(V.size() == T->getNumElements() &&
  921. "Invalid initializer for constant vector");
  922. }
  923. // ConstantVector accessors.
  924. Constant *ConstantVector::get(ArrayRef<Constant*> V) {
  925. if (Constant *C = getImpl(V))
  926. return C;
  927. VectorType *Ty = VectorType::get(V.front()->getType(), V.size());
  928. return Ty->getContext().pImpl->VectorConstants.getOrCreate(Ty, V);
  929. }
  930. Constant *ConstantVector::getImpl(ArrayRef<Constant*> V) {
  931. assert(!V.empty() && "Vectors can't be empty");
  932. VectorType *T = VectorType::get(V.front()->getType(), V.size());
  933. // If this is an all-undef or all-zero vector, return a
  934. // ConstantAggregateZero or UndefValue.
  935. Constant *C = V[0];
  936. bool isZero = C->isNullValue();
  937. bool isUndef = isa<UndefValue>(C);
  938. if (isZero || isUndef) {
  939. for (unsigned i = 1, e = V.size(); i != e; ++i)
  940. if (V[i] != C) {
  941. isZero = isUndef = false;
  942. break;
  943. }
  944. }
  945. if (isZero)
  946. return ConstantAggregateZero::get(T);
  947. if (isUndef)
  948. return UndefValue::get(T);
  949. // Check to see if all of the elements are ConstantFP or ConstantInt and if
  950. // the element type is compatible with ConstantDataVector. If so, use it.
  951. if (ConstantDataSequential::isElementTypeCompatible(C->getType()))
  952. return getSequenceIfElementsMatch<ConstantDataVector>(C, V);
  953. // Otherwise, the element type isn't compatible with ConstantDataVector, or
  954. // the operand list contains a ConstantExpr or something else strange.
  955. return nullptr;
  956. }
  957. Constant *ConstantVector::getSplat(unsigned NumElts, Constant *V) {
  958. // If this splat is compatible with ConstantDataVector, use it instead of
  959. // ConstantVector.
  960. if ((isa<ConstantFP>(V) || isa<ConstantInt>(V)) &&
  961. ConstantDataSequential::isElementTypeCompatible(V->getType()))
  962. return ConstantDataVector::getSplat(NumElts, V);
  963. SmallVector<Constant*, 32> Elts(NumElts, V);
  964. return get(Elts);
  965. }
  966. ConstantTokenNone *ConstantTokenNone::get(LLVMContext &Context) {
  967. LLVMContextImpl *pImpl = Context.pImpl;
  968. if (!pImpl->TheNoneToken)
  969. pImpl->TheNoneToken.reset(new ConstantTokenNone(Context));
  970. return pImpl->TheNoneToken.get();
  971. }
  972. /// Remove the constant from the constant table.
  973. void ConstantTokenNone::destroyConstantImpl() {
  974. llvm_unreachable("You can't ConstantTokenNone->destroyConstantImpl()!");
  975. }
  976. // Utility function for determining if a ConstantExpr is a CastOp or not. This
  977. // can't be inline because we don't want to #include Instruction.h into
  978. // Constant.h
  979. bool ConstantExpr::isCast() const {
  980. return Instruction::isCast(getOpcode());
  981. }
  982. bool ConstantExpr::isCompare() const {
  983. return getOpcode() == Instruction::ICmp || getOpcode() == Instruction::FCmp;
  984. }
  985. bool ConstantExpr::isGEPWithNoNotionalOverIndexing() const {
  986. if (getOpcode() != Instruction::GetElementPtr) return false;
  987. gep_type_iterator GEPI = gep_type_begin(this), E = gep_type_end(this);
  988. User::const_op_iterator OI = std::next(this->op_begin());
  989. // The remaining indices may be compile-time known integers within the bounds
  990. // of the corresponding notional static array types.
  991. for (; GEPI != E; ++GEPI, ++OI) {
  992. if (isa<UndefValue>(*OI))
  993. continue;
  994. auto *CI = dyn_cast<ConstantInt>(*OI);
  995. if (!CI || (GEPI.isBoundedSequential() &&
  996. (CI->getValue().getActiveBits() > 64 ||
  997. CI->getZExtValue() >= GEPI.getSequentialNumElements())))
  998. return false;
  999. }
  1000. // All the indices checked out.
  1001. return true;
  1002. }
  1003. bool ConstantExpr::hasIndices() const {
  1004. return getOpcode() == Instruction::ExtractValue ||
  1005. getOpcode() == Instruction::InsertValue;
  1006. }
  1007. ArrayRef<unsigned> ConstantExpr::getIndices() const {
  1008. if (const ExtractValueConstantExpr *EVCE =
  1009. dyn_cast<ExtractValueConstantExpr>(this))
  1010. return EVCE->Indices;
  1011. return cast<InsertValueConstantExpr>(this)->Indices;
  1012. }
  1013. unsigned ConstantExpr::getPredicate() const {
  1014. return cast<CompareConstantExpr>(this)->predicate;
  1015. }
  1016. Constant *
  1017. ConstantExpr::getWithOperandReplaced(unsigned OpNo, Constant *Op) const {
  1018. assert(Op->getType() == getOperand(OpNo)->getType() &&
  1019. "Replacing operand with value of different type!");
  1020. if (getOperand(OpNo) == Op)
  1021. return const_cast<ConstantExpr*>(this);
  1022. SmallVector<Constant*, 8> NewOps;
  1023. for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
  1024. NewOps.push_back(i == OpNo ? Op : getOperand(i));
  1025. return getWithOperands(NewOps);
  1026. }
  1027. Constant *ConstantExpr::getWithOperands(ArrayRef<Constant *> Ops, Type *Ty,
  1028. bool OnlyIfReduced, Type *SrcTy) const {
  1029. assert(Ops.size() == getNumOperands() && "Operand count mismatch!");
  1030. // If no operands changed return self.
  1031. if (Ty == getType() && std::equal(Ops.begin(), Ops.end(), op_begin()))
  1032. return const_cast<ConstantExpr*>(this);
  1033. Type *OnlyIfReducedTy = OnlyIfReduced ? Ty : nullptr;
  1034. switch (getOpcode()) {
  1035. case Instruction::Trunc:
  1036. case Instruction::ZExt:
  1037. case Instruction::SExt:
  1038. case Instruction::FPTrunc:
  1039. case Instruction::FPExt:
  1040. case Instruction::UIToFP:
  1041. case Instruction::SIToFP:
  1042. case Instruction::FPToUI:
  1043. case Instruction::FPToSI:
  1044. case Instruction::PtrToInt:
  1045. case Instruction::IntToPtr:
  1046. case Instruction::BitCast:
  1047. case Instruction::AddrSpaceCast:
  1048. return ConstantExpr::getCast(getOpcode(), Ops[0], Ty, OnlyIfReduced);
  1049. case Instruction::Select:
  1050. return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2], OnlyIfReducedTy);
  1051. case Instruction::InsertElement:
  1052. return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2],
  1053. OnlyIfReducedTy);
  1054. case Instruction::ExtractElement:
  1055. return ConstantExpr::getExtractElement(Ops[0], Ops[1], OnlyIfReducedTy);
  1056. case Instruction::InsertValue:
  1057. return ConstantExpr::getInsertValue(Ops[0], Ops[1], getIndices(),
  1058. OnlyIfReducedTy);
  1059. case Instruction::ExtractValue:
  1060. return ConstantExpr::getExtractValue(Ops[0], getIndices(), OnlyIfReducedTy);
  1061. case Instruction::ShuffleVector:
  1062. return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2],
  1063. OnlyIfReducedTy);
  1064. case Instruction::GetElementPtr: {
  1065. auto *GEPO = cast<GEPOperator>(this);
  1066. assert(SrcTy || (Ops[0]->getType() == getOperand(0)->getType()));
  1067. return ConstantExpr::getGetElementPtr(
  1068. SrcTy ? SrcTy : GEPO->getSourceElementType(), Ops[0], Ops.slice(1),
  1069. GEPO->isInBounds(), GEPO->getInRangeIndex(), OnlyIfReducedTy);
  1070. }
  1071. case Instruction::ICmp:
  1072. case Instruction::FCmp:
  1073. return ConstantExpr::getCompare(getPredicate(), Ops[0], Ops[1],
  1074. OnlyIfReducedTy);
  1075. default:
  1076. assert(getNumOperands() == 2 && "Must be binary operator?");
  1077. return ConstantExpr::get(getOpcode(), Ops[0], Ops[1], SubclassOptionalData,
  1078. OnlyIfReducedTy);
  1079. }
  1080. }
  1081. //===----------------------------------------------------------------------===//
  1082. // isValueValidForType implementations
  1083. bool ConstantInt::isValueValidForType(Type *Ty, uint64_t Val) {
  1084. unsigned NumBits = Ty->getIntegerBitWidth(); // assert okay
  1085. if (Ty->isIntegerTy(1))
  1086. return Val == 0 || Val == 1;
  1087. return isUIntN(NumBits, Val);
  1088. }
  1089. bool ConstantInt::isValueValidForType(Type *Ty, int64_t Val) {
  1090. unsigned NumBits = Ty->getIntegerBitWidth();
  1091. if (Ty->isIntegerTy(1))
  1092. return Val == 0 || Val == 1 || Val == -1;
  1093. return isIntN(NumBits, Val);
  1094. }
  1095. bool ConstantFP::isValueValidForType(Type *Ty, const APFloat& Val) {
  1096. // convert modifies in place, so make a copy.
  1097. APFloat Val2 = APFloat(Val);
  1098. bool losesInfo;
  1099. switch (Ty->getTypeID()) {
  1100. default:
  1101. return false; // These can't be represented as floating point!
  1102. // FIXME rounding mode needs to be more flexible
  1103. case Type::HalfTyID: {
  1104. if (&Val2.getSemantics() == &APFloat::IEEEhalf())
  1105. return true;
  1106. Val2.convert(APFloat::IEEEhalf(), APFloat::rmNearestTiesToEven, &losesInfo);
  1107. return !losesInfo;
  1108. }
  1109. case Type::FloatTyID: {
  1110. if (&Val2.getSemantics() == &APFloat::IEEEsingle())
  1111. return true;
  1112. Val2.convert(APFloat::IEEEsingle(), APFloat::rmNearestTiesToEven, &losesInfo);
  1113. return !losesInfo;
  1114. }
  1115. case Type::DoubleTyID: {
  1116. if (&Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1117. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1118. &Val2.getSemantics() == &APFloat::IEEEdouble())
  1119. return true;
  1120. Val2.convert(APFloat::IEEEdouble(), APFloat::rmNearestTiesToEven, &losesInfo);
  1121. return !losesInfo;
  1122. }
  1123. case Type::X86_FP80TyID:
  1124. return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1125. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1126. &Val2.getSemantics() == &APFloat::IEEEdouble() ||
  1127. &Val2.getSemantics() == &APFloat::x87DoubleExtended();
  1128. case Type::FP128TyID:
  1129. return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1130. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1131. &Val2.getSemantics() == &APFloat::IEEEdouble() ||
  1132. &Val2.getSemantics() == &APFloat::IEEEquad();
  1133. case Type::PPC_FP128TyID:
  1134. return &Val2.getSemantics() == &APFloat::IEEEhalf() ||
  1135. &Val2.getSemantics() == &APFloat::IEEEsingle() ||
  1136. &Val2.getSemantics() == &APFloat::IEEEdouble() ||
  1137. &Val2.getSemantics() == &APFloat::PPCDoubleDouble();
  1138. }
  1139. }
  1140. //===----------------------------------------------------------------------===//
  1141. // Factory Function Implementation
  1142. ConstantAggregateZero *ConstantAggregateZero::get(Type *Ty) {
  1143. assert((Ty->isStructTy() || Ty->isArrayTy() || Ty->isVectorTy()) &&
  1144. "Cannot create an aggregate zero of non-aggregate type!");
  1145. std::unique_ptr<ConstantAggregateZero> &Entry =
  1146. Ty->getContext().pImpl->CAZConstants[Ty];
  1147. if (!Entry)
  1148. Entry.reset(new ConstantAggregateZero(Ty));
  1149. return Entry.get();
  1150. }
  1151. /// Remove the constant from the constant table.
  1152. void ConstantAggregateZero::destroyConstantImpl() {
  1153. getContext().pImpl->CAZConstants.erase(getType());
  1154. }
  1155. /// Remove the constant from the constant table.
  1156. void ConstantArray::destroyConstantImpl() {
  1157. getType()->getContext().pImpl->ArrayConstants.remove(this);
  1158. }
  1159. //---- ConstantStruct::get() implementation...
  1160. //
  1161. /// Remove the constant from the constant table.
  1162. void ConstantStruct::destroyConstantImpl() {
  1163. getType()->getContext().pImpl->StructConstants.remove(this);
  1164. }
  1165. /// Remove the constant from the constant table.
  1166. void ConstantVector::destroyConstantImpl() {
  1167. getType()->getContext().pImpl->VectorConstants.remove(this);
  1168. }
  1169. Constant *Constant::getSplatValue() const {
  1170. assert(this->getType()->isVectorTy() && "Only valid for vectors!");
  1171. if (isa<ConstantAggregateZero>(this))
  1172. return getNullValue(this->getType()->getVectorElementType());
  1173. if (const ConstantDataVector *CV = dyn_cast<ConstantDataVector>(this))
  1174. return CV->getSplatValue();
  1175. if (const ConstantVector *CV = dyn_cast<ConstantVector>(this))
  1176. return CV->getSplatValue();
  1177. return nullptr;
  1178. }
  1179. Constant *ConstantVector::getSplatValue() const {
  1180. // Check out first element.
  1181. Constant *Elt = getOperand(0);
  1182. // Then make sure all remaining elements point to the same value.
  1183. for (unsigned I = 1, E = getNumOperands(); I < E; ++I)
  1184. if (getOperand(I) != Elt)
  1185. return nullptr;
  1186. return Elt;
  1187. }
  1188. const APInt &Constant::getUniqueInteger() const {
  1189. if (const ConstantInt *CI = dyn_cast<ConstantInt>(this))
  1190. return CI->getValue();
  1191. assert(this->getSplatValue() && "Doesn't contain a unique integer!");
  1192. const Constant *C = this->getAggregateElement(0U);
  1193. assert(C && isa<ConstantInt>(C) && "Not a vector of numbers!");
  1194. return cast<ConstantInt>(C)->getValue();
  1195. }
  1196. //---- ConstantPointerNull::get() implementation.
  1197. //
  1198. ConstantPointerNull *ConstantPointerNull::get(PointerType *Ty) {
  1199. std::unique_ptr<ConstantPointerNull> &Entry =
  1200. Ty->getContext().pImpl->CPNConstants[Ty];
  1201. if (!Entry)
  1202. Entry.reset(new ConstantPointerNull(Ty));
  1203. return Entry.get();
  1204. }
  1205. /// Remove the constant from the constant table.
  1206. void ConstantPointerNull::destroyConstantImpl() {
  1207. getContext().pImpl->CPNConstants.erase(getType());
  1208. }
  1209. UndefValue *UndefValue::get(Type *Ty) {
  1210. std::unique_ptr<UndefValue> &Entry = Ty->getContext().pImpl->UVConstants[Ty];
  1211. if (!Entry)
  1212. Entry.reset(new UndefValue(Ty));
  1213. return Entry.get();
  1214. }
  1215. /// Remove the constant from the constant table.
  1216. void UndefValue::destroyConstantImpl() {
  1217. // Free the constant and any dangling references to it.
  1218. getContext().pImpl->UVConstants.erase(getType());
  1219. }
  1220. BlockAddress *BlockAddress::get(BasicBlock *BB) {
  1221. assert(BB->getParent() && "Block must have a parent");
  1222. return get(BB->getParent(), BB);
  1223. }
  1224. BlockAddress *BlockAddress::get(Function *F, BasicBlock *BB) {
  1225. BlockAddress *&BA =
  1226. F->getContext().pImpl->BlockAddresses[std::make_pair(F, BB)];
  1227. if (!BA)
  1228. BA = new BlockAddress(F, BB);
  1229. assert(BA->getFunction() == F && "Basic block moved between functions");
  1230. return BA;
  1231. }
  1232. BlockAddress::BlockAddress(Function *F, BasicBlock *BB)
  1233. : Constant(Type::getInt8PtrTy(F->getContext()), Value::BlockAddressVal,
  1234. &Op<0>(), 2) {
  1235. setOperand(0, F);
  1236. setOperand(1, BB);
  1237. BB->AdjustBlockAddressRefCount(1);
  1238. }
  1239. BlockAddress *BlockAddress::lookup(const BasicBlock *BB) {
  1240. if (!BB->hasAddressTaken())
  1241. return nullptr;
  1242. const Function *F = BB->getParent();
  1243. assert(F && "Block must have a parent");
  1244. BlockAddress *BA =
  1245. F->getContext().pImpl->BlockAddresses.lookup(std::make_pair(F, BB));
  1246. assert(BA && "Refcount and block address map disagree!");
  1247. return BA;
  1248. }
  1249. /// Remove the constant from the constant table.
  1250. void BlockAddress::destroyConstantImpl() {
  1251. getFunction()->getType()->getContext().pImpl
  1252. ->BlockAddresses.erase(std::make_pair(getFunction(), getBasicBlock()));
  1253. getBasicBlock()->AdjustBlockAddressRefCount(-1);
  1254. }
  1255. Value *BlockAddress::handleOperandChangeImpl(Value *From, Value *To) {
  1256. // This could be replacing either the Basic Block or the Function. In either
  1257. // case, we have to remove the map entry.
  1258. Function *NewF = getFunction();
  1259. BasicBlock *NewBB = getBasicBlock();
  1260. if (From == NewF)
  1261. NewF = cast<Function>(To->stripPointerCasts());
  1262. else {
  1263. assert(From == NewBB && "From does not match any operand");
  1264. NewBB = cast<BasicBlock>(To);
  1265. }
  1266. // See if the 'new' entry already exists, if not, just update this in place
  1267. // and return early.
  1268. BlockAddress *&NewBA =
  1269. getContext().pImpl->BlockAddresses[std::make_pair(NewF, NewBB)];
  1270. if (NewBA)
  1271. return NewBA;
  1272. getBasicBlock()->AdjustBlockAddressRefCount(-1);
  1273. // Remove the old entry, this can't cause the map to rehash (just a
  1274. // tombstone will get added).
  1275. getContext().pImpl->BlockAddresses.erase(std::make_pair(getFunction(),
  1276. getBasicBlock()));
  1277. NewBA = this;
  1278. setOperand(0, NewF);
  1279. setOperand(1, NewBB);
  1280. getBasicBlock()->AdjustBlockAddressRefCount(1);
  1281. // If we just want to keep the existing value, then return null.
  1282. // Callers know that this means we shouldn't delete this value.
  1283. return nullptr;
  1284. }
  1285. //---- ConstantExpr::get() implementations.
  1286. //
  1287. /// This is a utility function to handle folding of casts and lookup of the
  1288. /// cast in the ExprConstants map. It is used by the various get* methods below.
  1289. static Constant *getFoldedCast(Instruction::CastOps opc, Constant *C, Type *Ty,
  1290. bool OnlyIfReduced = false) {
  1291. assert(Ty->isFirstClassType() && "Cannot cast to an aggregate type!");
  1292. // Fold a few common cases
  1293. if (Constant *FC = ConstantFoldCastInstruction(opc, C, Ty))
  1294. return FC;
  1295. if (OnlyIfReduced)
  1296. return nullptr;
  1297. LLVMContextImpl *pImpl = Ty->getContext().pImpl;
  1298. // Look up the constant in the table first to ensure uniqueness.
  1299. ConstantExprKeyType Key(opc, C);
  1300. return pImpl->ExprConstants.getOrCreate(Ty, Key);
  1301. }
  1302. Constant *ConstantExpr::getCast(unsigned oc, Constant *C, Type *Ty,
  1303. bool OnlyIfReduced) {
  1304. Instruction::CastOps opc = Instruction::CastOps(oc);
  1305. assert(Instruction::isCast(opc) && "opcode out of range");
  1306. assert(C && Ty && "Null arguments to getCast");
  1307. assert(CastInst::castIsValid(opc, C, Ty) && "Invalid constantexpr cast!");
  1308. switch (opc) {
  1309. default:
  1310. llvm_unreachable("Invalid cast opcode");
  1311. case Instruction::Trunc:
  1312. return getTrunc(C, Ty, OnlyIfReduced);
  1313. case Instruction::ZExt:
  1314. return getZExt(C, Ty, OnlyIfReduced);
  1315. case Instruction::SExt:
  1316. return getSExt(C, Ty, OnlyIfReduced);
  1317. case Instruction::FPTrunc:
  1318. return getFPTrunc(C, Ty, OnlyIfReduced);
  1319. case Instruction::FPExt:
  1320. return getFPExtend(C, Ty, OnlyIfReduced);
  1321. case Instruction::UIToFP:
  1322. return getUIToFP(C, Ty, OnlyIfReduced);
  1323. case Instruction::SIToFP:
  1324. return getSIToFP(C, Ty, OnlyIfReduced);
  1325. case Instruction::FPToUI:
  1326. return getFPToUI(C, Ty, OnlyIfReduced);
  1327. case Instruction::FPToSI:
  1328. return getFPToSI(C, Ty, OnlyIfReduced);
  1329. case Instruction::PtrToInt:
  1330. return getPtrToInt(C, Ty, OnlyIfReduced);
  1331. case Instruction::IntToPtr:
  1332. return getIntToPtr(C, Ty, OnlyIfReduced);
  1333. case Instruction::BitCast:
  1334. return getBitCast(C, Ty, OnlyIfReduced);
  1335. case Instruction::AddrSpaceCast:
  1336. return getAddrSpaceCast(C, Ty, OnlyIfReduced);
  1337. }
  1338. }
  1339. Constant *ConstantExpr::getZExtOrBitCast(Constant *C, Type *Ty) {
  1340. if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  1341. return getBitCast(C, Ty);
  1342. return getZExt(C, Ty);
  1343. }
  1344. Constant *ConstantExpr::getSExtOrBitCast(Constant *C, Type *Ty) {
  1345. if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  1346. return getBitCast(C, Ty);
  1347. return getSExt(C, Ty);
  1348. }
  1349. Constant *ConstantExpr::getTruncOrBitCast(Constant *C, Type *Ty) {
  1350. if (C->getType()->getScalarSizeInBits() == Ty->getScalarSizeInBits())
  1351. return getBitCast(C, Ty);
  1352. return getTrunc(C, Ty);
  1353. }
  1354. Constant *ConstantExpr::getPointerCast(Constant *S, Type *Ty) {
  1355. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  1356. assert((Ty->isIntOrIntVectorTy() || Ty->isPtrOrPtrVectorTy()) &&
  1357. "Invalid cast");
  1358. if (Ty->isIntOrIntVectorTy())
  1359. return getPtrToInt(S, Ty);
  1360. unsigned SrcAS = S->getType()->getPointerAddressSpace();
  1361. if (Ty->isPtrOrPtrVectorTy() && SrcAS != Ty->getPointerAddressSpace())
  1362. return getAddrSpaceCast(S, Ty);
  1363. return getBitCast(S, Ty);
  1364. }
  1365. Constant *ConstantExpr::getPointerBitCastOrAddrSpaceCast(Constant *S,
  1366. Type *Ty) {
  1367. assert(S->getType()->isPtrOrPtrVectorTy() && "Invalid cast");
  1368. assert(Ty->isPtrOrPtrVectorTy() && "Invalid cast");
  1369. if (S->getType()->getPointerAddressSpace() != Ty->getPointerAddressSpace())
  1370. return getAddrSpaceCast(S, Ty);
  1371. return getBitCast(S, Ty);
  1372. }
  1373. Constant *ConstantExpr::getIntegerCast(Constant *C, Type *Ty, bool isSigned) {
  1374. assert(C->getType()->isIntOrIntVectorTy() &&
  1375. Ty->isIntOrIntVectorTy() && "Invalid cast");
  1376. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  1377. unsigned DstBits = Ty->getScalarSizeInBits();
  1378. Instruction::CastOps opcode =
  1379. (SrcBits == DstBits ? Instruction::BitCast :
  1380. (SrcBits > DstBits ? Instruction::Trunc :
  1381. (isSigned ? Instruction::SExt : Instruction::ZExt)));
  1382. return getCast(opcode, C, Ty);
  1383. }
  1384. Constant *ConstantExpr::getFPCast(Constant *C, Type *Ty) {
  1385. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  1386. "Invalid cast");
  1387. unsigned SrcBits = C->getType()->getScalarSizeInBits();
  1388. unsigned DstBits = Ty->getScalarSizeInBits();
  1389. if (SrcBits == DstBits)
  1390. return C; // Avoid a useless cast
  1391. Instruction::CastOps opcode =
  1392. (SrcBits > DstBits ? Instruction::FPTrunc : Instruction::FPExt);
  1393. return getCast(opcode, C, Ty);
  1394. }
  1395. Constant *ConstantExpr::getTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1396. #ifndef NDEBUG
  1397. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1398. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1399. #endif
  1400. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1401. assert(C->getType()->isIntOrIntVectorTy() && "Trunc operand must be integer");
  1402. assert(Ty->isIntOrIntVectorTy() && "Trunc produces only integral");
  1403. assert(C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
  1404. "SrcTy must be larger than DestTy for Trunc!");
  1405. return getFoldedCast(Instruction::Trunc, C, Ty, OnlyIfReduced);
  1406. }
  1407. Constant *ConstantExpr::getSExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1408. #ifndef NDEBUG
  1409. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1410. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1411. #endif
  1412. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1413. assert(C->getType()->isIntOrIntVectorTy() && "SExt operand must be integral");
  1414. assert(Ty->isIntOrIntVectorTy() && "SExt produces only integer");
  1415. assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
  1416. "SrcTy must be smaller than DestTy for SExt!");
  1417. return getFoldedCast(Instruction::SExt, C, Ty, OnlyIfReduced);
  1418. }
  1419. Constant *ConstantExpr::getZExt(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1420. #ifndef NDEBUG
  1421. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1422. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1423. #endif
  1424. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1425. assert(C->getType()->isIntOrIntVectorTy() && "ZEXt operand must be integral");
  1426. assert(Ty->isIntOrIntVectorTy() && "ZExt produces only integer");
  1427. assert(C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
  1428. "SrcTy must be smaller than DestTy for ZExt!");
  1429. return getFoldedCast(Instruction::ZExt, C, Ty, OnlyIfReduced);
  1430. }
  1431. Constant *ConstantExpr::getFPTrunc(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1432. #ifndef NDEBUG
  1433. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1434. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1435. #endif
  1436. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1437. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  1438. C->getType()->getScalarSizeInBits() > Ty->getScalarSizeInBits()&&
  1439. "This is an illegal floating point truncation!");
  1440. return getFoldedCast(Instruction::FPTrunc, C, Ty, OnlyIfReduced);
  1441. }
  1442. Constant *ConstantExpr::getFPExtend(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1443. #ifndef NDEBUG
  1444. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1445. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1446. #endif
  1447. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1448. assert(C->getType()->isFPOrFPVectorTy() && Ty->isFPOrFPVectorTy() &&
  1449. C->getType()->getScalarSizeInBits() < Ty->getScalarSizeInBits()&&
  1450. "This is an illegal floating point extension!");
  1451. return getFoldedCast(Instruction::FPExt, C, Ty, OnlyIfReduced);
  1452. }
  1453. Constant *ConstantExpr::getUIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1454. #ifndef NDEBUG
  1455. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1456. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1457. #endif
  1458. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1459. assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
  1460. "This is an illegal uint to floating point cast!");
  1461. return getFoldedCast(Instruction::UIToFP, C, Ty, OnlyIfReduced);
  1462. }
  1463. Constant *ConstantExpr::getSIToFP(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1464. #ifndef NDEBUG
  1465. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1466. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1467. #endif
  1468. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1469. assert(C->getType()->isIntOrIntVectorTy() && Ty->isFPOrFPVectorTy() &&
  1470. "This is an illegal sint to floating point cast!");
  1471. return getFoldedCast(Instruction::SIToFP, C, Ty, OnlyIfReduced);
  1472. }
  1473. Constant *ConstantExpr::getFPToUI(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1474. #ifndef NDEBUG
  1475. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1476. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1477. #endif
  1478. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1479. assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
  1480. "This is an illegal floating point to uint cast!");
  1481. return getFoldedCast(Instruction::FPToUI, C, Ty, OnlyIfReduced);
  1482. }
  1483. Constant *ConstantExpr::getFPToSI(Constant *C, Type *Ty, bool OnlyIfReduced) {
  1484. #ifndef NDEBUG
  1485. bool fromVec = C->getType()->getTypeID() == Type::VectorTyID;
  1486. bool toVec = Ty->getTypeID() == Type::VectorTyID;
  1487. #endif
  1488. assert((fromVec == toVec) && "Cannot convert from scalar to/from vector");
  1489. assert(C->getType()->isFPOrFPVectorTy() && Ty->isIntOrIntVectorTy() &&
  1490. "This is an illegal floating point to sint cast!");
  1491. return getFoldedCast(Instruction::FPToSI, C, Ty, OnlyIfReduced);
  1492. }
  1493. Constant *ConstantExpr::getPtrToInt(Constant *C, Type *DstTy,
  1494. bool OnlyIfReduced) {
  1495. assert(C->getType()->isPtrOrPtrVectorTy() &&
  1496. "PtrToInt source must be pointer or pointer vector");
  1497. assert(DstTy->isIntOrIntVectorTy() &&
  1498. "PtrToInt destination must be integer or integer vector");
  1499. assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
  1500. if (isa<VectorType>(C->getType()))
  1501. assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
  1502. "Invalid cast between a different number of vector elements");
  1503. return getFoldedCast(Instruction::PtrToInt, C, DstTy, OnlyIfReduced);
  1504. }
  1505. Constant *ConstantExpr::getIntToPtr(Constant *C, Type *DstTy,
  1506. bool OnlyIfReduced) {
  1507. assert(C->getType()->isIntOrIntVectorTy() &&
  1508. "IntToPtr source must be integer or integer vector");
  1509. assert(DstTy->isPtrOrPtrVectorTy() &&
  1510. "IntToPtr destination must be a pointer or pointer vector");
  1511. assert(isa<VectorType>(C->getType()) == isa<VectorType>(DstTy));
  1512. if (isa<VectorType>(C->getType()))
  1513. assert(C->getType()->getVectorNumElements()==DstTy->getVectorNumElements()&&
  1514. "Invalid cast between a different number of vector elements");
  1515. return getFoldedCast(Instruction::IntToPtr, C, DstTy, OnlyIfReduced);
  1516. }
  1517. Constant *ConstantExpr::getBitCast(Constant *C, Type *DstTy,
  1518. bool OnlyIfReduced) {
  1519. assert(CastInst::castIsValid(Instruction::BitCast, C, DstTy) &&
  1520. "Invalid constantexpr bitcast!");
  1521. // It is common to ask for a bitcast of a value to its own type, handle this
  1522. // speedily.
  1523. if (C->getType() == DstTy) return C;
  1524. return getFoldedCast(Instruction::BitCast, C, DstTy, OnlyIfReduced);
  1525. }
  1526. Constant *ConstantExpr::getAddrSpaceCast(Constant *C, Type *DstTy,
  1527. bool OnlyIfReduced) {
  1528. assert(CastInst::castIsValid(Instruction::AddrSpaceCast, C, DstTy) &&
  1529. "Invalid constantexpr addrspacecast!");
  1530. // Canonicalize addrspacecasts between different pointer types by first
  1531. // bitcasting the pointer type and then converting the address space.
  1532. PointerType *SrcScalarTy = cast<PointerType>(C->getType()->getScalarType());
  1533. PointerType *DstScalarTy = cast<PointerType>(DstTy->getScalarType());
  1534. Type *DstElemTy = DstScalarTy->getElementType();
  1535. if (SrcScalarTy->getElementType() != DstElemTy) {
  1536. Type *MidTy = PointerType::get(DstElemTy, SrcScalarTy->getAddressSpace());
  1537. if (VectorType *VT = dyn_cast<VectorType>(DstTy)) {
  1538. // Handle vectors of pointers.
  1539. MidTy = VectorType::get(MidTy, VT->getNumElements());
  1540. }
  1541. C = getBitCast(C, MidTy);
  1542. }
  1543. return getFoldedCast(Instruction::AddrSpaceCast, C, DstTy, OnlyIfReduced);
  1544. }
  1545. Constant *ConstantExpr::get(unsigned Opcode, Constant *C, unsigned Flags,
  1546. Type *OnlyIfReducedTy) {
  1547. // Check the operands for consistency first.
  1548. assert(Instruction::isUnaryOp(Opcode) &&
  1549. "Invalid opcode in unary constant expression");
  1550. #ifndef NDEBUG
  1551. switch (Opcode) {
  1552. case Instruction::FNeg:
  1553. assert(C->getType()->isFPOrFPVectorTy() &&
  1554. "Tried to create a floating-point operation on a "
  1555. "non-floating-point type!");
  1556. break;
  1557. default:
  1558. break;
  1559. }
  1560. #endif
  1561. if (Constant *FC = ConstantFoldUnaryInstruction(Opcode, C))
  1562. return FC;
  1563. if (OnlyIfReducedTy == C->getType())
  1564. return nullptr;
  1565. Constant *ArgVec[] = { C };
  1566. ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
  1567. LLVMContextImpl *pImpl = C->getContext().pImpl;
  1568. return pImpl->ExprConstants.getOrCreate(C->getType(), Key);
  1569. }
  1570. Constant *ConstantExpr::get(unsigned Opcode, Constant *C1, Constant *C2,
  1571. unsigned Flags, Type *OnlyIfReducedTy) {
  1572. // Check the operands for consistency first.
  1573. assert(Instruction::isBinaryOp(Opcode) &&
  1574. "Invalid opcode in binary constant expression");
  1575. assert(C1->getType() == C2->getType() &&
  1576. "Operand types in binary constant expression should match");
  1577. #ifndef NDEBUG
  1578. switch (Opcode) {
  1579. case Instruction::Add:
  1580. case Instruction::Sub:
  1581. case Instruction::Mul:
  1582. case Instruction::UDiv:
  1583. case Instruction::SDiv:
  1584. case Instruction::URem:
  1585. case Instruction::SRem:
  1586. assert(C1->getType()->isIntOrIntVectorTy() &&
  1587. "Tried to create an integer operation on a non-integer type!");
  1588. break;
  1589. case Instruction::FAdd:
  1590. case Instruction::FSub:
  1591. case Instruction::FMul:
  1592. case Instruction::FDiv:
  1593. case Instruction::FRem:
  1594. assert(C1->getType()->isFPOrFPVectorTy() &&
  1595. "Tried to create a floating-point operation on a "
  1596. "non-floating-point type!");
  1597. break;
  1598. case Instruction::And:
  1599. case Instruction::Or:
  1600. case Instruction::Xor:
  1601. assert(C1->getType()->isIntOrIntVectorTy() &&
  1602. "Tried to create a logical operation on a non-integral type!");
  1603. break;
  1604. case Instruction::Shl:
  1605. case Instruction::LShr:
  1606. case Instruction::AShr:
  1607. assert(C1->getType()->isIntOrIntVectorTy() &&
  1608. "Tried to create a shift operation on a non-integer type!");
  1609. break;
  1610. default:
  1611. break;
  1612. }
  1613. #endif
  1614. if (Constant *FC = ConstantFoldBinaryInstruction(Opcode, C1, C2))
  1615. return FC;
  1616. if (OnlyIfReducedTy == C1->getType())
  1617. return nullptr;
  1618. Constant *ArgVec[] = { C1, C2 };
  1619. ConstantExprKeyType Key(Opcode, ArgVec, 0, Flags);
  1620. LLVMContextImpl *pImpl = C1->getContext().pImpl;
  1621. return pImpl->ExprConstants.getOrCreate(C1->getType(), Key);
  1622. }
  1623. Constant *ConstantExpr::getSizeOf(Type* Ty) {
  1624. // sizeof is implemented as: (i64) gep (Ty*)null, 1
  1625. // Note that a non-inbounds gep is used, as null isn't within any object.
  1626. Constant *GEPIdx = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
  1627. Constant *GEP = getGetElementPtr(
  1628. Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
  1629. return getPtrToInt(GEP,
  1630. Type::getInt64Ty(Ty->getContext()));
  1631. }
  1632. Constant *ConstantExpr::getAlignOf(Type* Ty) {
  1633. // alignof is implemented as: (i64) gep ({i1,Ty}*)null, 0, 1
  1634. // Note that a non-inbounds gep is used, as null isn't within any object.
  1635. Type *AligningTy = StructType::get(Type::getInt1Ty(Ty->getContext()), Ty);
  1636. Constant *NullPtr = Constant::getNullValue(AligningTy->getPointerTo(0));
  1637. Constant *Zero = ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0);
  1638. Constant *One = ConstantInt::get(Type::getInt32Ty(Ty->getContext()), 1);
  1639. Constant *Indices[2] = { Zero, One };
  1640. Constant *GEP = getGetElementPtr(AligningTy, NullPtr, Indices);
  1641. return getPtrToInt(GEP,
  1642. Type::getInt64Ty(Ty->getContext()));
  1643. }
  1644. Constant *ConstantExpr::getOffsetOf(StructType* STy, unsigned FieldNo) {
  1645. return getOffsetOf(STy, ConstantInt::get(Type::getInt32Ty(STy->getContext()),
  1646. FieldNo));
  1647. }
  1648. Constant *ConstantExpr::getOffsetOf(Type* Ty, Constant *FieldNo) {
  1649. // offsetof is implemented as: (i64) gep (Ty*)null, 0, FieldNo
  1650. // Note that a non-inbounds gep is used, as null isn't within any object.
  1651. Constant *GEPIdx[] = {
  1652. ConstantInt::get(Type::getInt64Ty(Ty->getContext()), 0),
  1653. FieldNo
  1654. };
  1655. Constant *GEP = getGetElementPtr(
  1656. Ty, Constant::getNullValue(PointerType::getUnqual(Ty)), GEPIdx);
  1657. return getPtrToInt(GEP,
  1658. Type::getInt64Ty(Ty->getContext()));
  1659. }
  1660. Constant *ConstantExpr::getCompare(unsigned short Predicate, Constant *C1,
  1661. Constant *C2, bool OnlyIfReduced) {
  1662. assert(C1->getType() == C2->getType() && "Op types should be identical!");
  1663. switch (Predicate) {
  1664. default: llvm_unreachable("Invalid CmpInst predicate");
  1665. case CmpInst::FCMP_FALSE: case CmpInst::FCMP_OEQ: case CmpInst::FCMP_OGT:
  1666. case CmpInst::FCMP_OGE: case CmpInst::FCMP_OLT: case CmpInst::FCMP_OLE:
  1667. case CmpInst::FCMP_ONE: case CmpInst::FCMP_ORD: case CmpInst::FCMP_UNO:
  1668. case CmpInst::FCMP_UEQ: case CmpInst::FCMP_UGT: case CmpInst::FCMP_UGE:
  1669. case CmpInst::FCMP_ULT: case CmpInst::FCMP_ULE: case CmpInst::FCMP_UNE:
  1670. case CmpInst::FCMP_TRUE:
  1671. return getFCmp(Predicate, C1, C2, OnlyIfReduced);
  1672. case CmpInst::ICMP_EQ: case CmpInst::ICMP_NE: case CmpInst::ICMP_UGT:
  1673. case CmpInst::ICMP_UGE: case CmpInst::ICMP_ULT: case CmpInst::ICMP_ULE:
  1674. case CmpInst::ICMP_SGT: case CmpInst::ICMP_SGE: case CmpInst::ICMP_SLT:
  1675. case CmpInst::ICMP_SLE:
  1676. return getICmp(Predicate, C1, C2, OnlyIfReduced);
  1677. }
  1678. }
  1679. Constant *ConstantExpr::getSelect(Constant *C, Constant *V1, Constant *V2,
  1680. Type *OnlyIfReducedTy) {
  1681. assert(!SelectInst::areInvalidOperands(C, V1, V2)&&"Invalid select operands");
  1682. if (Constant *SC = ConstantFoldSelectInstruction(C, V1, V2))
  1683. return SC; // Fold common cases
  1684. if (OnlyIfReducedTy == V1->getType())
  1685. return nullptr;
  1686. Constant *ArgVec[] = { C, V1, V2 };
  1687. ConstantExprKeyType Key(Instruction::Select, ArgVec);
  1688. LLVMContextImpl *pImpl = C->getContext().pImpl;
  1689. return pImpl->ExprConstants.getOrCreate(V1->getType(), Key);
  1690. }
  1691. Constant *ConstantExpr::getGetElementPtr(Type *Ty, Constant *C,
  1692. ArrayRef<Value *> Idxs, bool InBounds,
  1693. Optional<unsigned> InRangeIndex,
  1694. Type *OnlyIfReducedTy) {
  1695. if (!Ty)
  1696. Ty = cast<PointerType>(C->getType()->getScalarType())->getElementType();
  1697. else
  1698. assert(Ty ==
  1699. cast<PointerType>(C->getType()->getScalarType())->getElementType());
  1700. if (Constant *FC =
  1701. ConstantFoldGetElementPtr(Ty, C, InBounds, InRangeIndex, Idxs))
  1702. return FC; // Fold a few common cases.
  1703. // Get the result type of the getelementptr!
  1704. Type *DestTy = GetElementPtrInst::getIndexedType(Ty, Idxs);
  1705. assert(DestTy && "GEP indices invalid!");
  1706. unsigned AS = C->getType()->getPointerAddressSpace();
  1707. Type *ReqTy = DestTy->getPointerTo(AS);
  1708. unsigned NumVecElts = 0;
  1709. if (C->getType()->isVectorTy())
  1710. NumVecElts = C->getType()->getVectorNumElements();
  1711. else for (auto Idx : Idxs)
  1712. if (Idx->getType()->isVectorTy())
  1713. NumVecElts = Idx->getType()->getVectorNumElements();
  1714. if (NumVecElts)
  1715. ReqTy = VectorType::get(ReqTy, NumVecElts);
  1716. if (OnlyIfReducedTy == ReqTy)
  1717. return nullptr;
  1718. // Look up the constant in the table first to ensure uniqueness
  1719. std::vector<Constant*> ArgVec;
  1720. ArgVec.reserve(1 + Idxs.size());
  1721. ArgVec.push_back(C);
  1722. for (unsigned i = 0, e = Idxs.size(); i != e; ++i) {
  1723. assert((!Idxs[i]->getType()->isVectorTy() ||
  1724. Idxs[i]->getType()->getVectorNumElements() == NumVecElts) &&
  1725. "getelementptr index type missmatch");
  1726. Constant *Idx = cast<Constant>(Idxs[i]);
  1727. if (NumVecElts && !Idxs[i]->getType()->isVectorTy())
  1728. Idx = ConstantVector::getSplat(NumVecElts, Idx);
  1729. ArgVec.push_back(Idx);
  1730. }
  1731. unsigned SubClassOptionalData = InBounds ? GEPOperator::IsInBounds : 0;
  1732. if (InRangeIndex && *InRangeIndex < 63)
  1733. SubClassOptionalData |= (*InRangeIndex + 1) << 1;
  1734. const ConstantExprKeyType Key(Instruction::GetElementPtr, ArgVec, 0,
  1735. SubClassOptionalData, None, Ty);
  1736. LLVMContextImpl *pImpl = C->getContext().pImpl;
  1737. return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
  1738. }
  1739. Constant *ConstantExpr::getICmp(unsigned short pred, Constant *LHS,
  1740. Constant *RHS, bool OnlyIfReduced) {
  1741. assert(LHS->getType() == RHS->getType());
  1742. assert(CmpInst::isIntPredicate((CmpInst::Predicate)pred) &&
  1743. "Invalid ICmp Predicate");
  1744. if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
  1745. return FC; // Fold a few common cases...
  1746. if (OnlyIfReduced)
  1747. return nullptr;
  1748. // Look up the constant in the table first to ensure uniqueness
  1749. Constant *ArgVec[] = { LHS, RHS };
  1750. // Get the key type with both the opcode and predicate
  1751. const ConstantExprKeyType Key(Instruction::ICmp, ArgVec, pred);
  1752. Type *ResultTy = Type::getInt1Ty(LHS->getContext());
  1753. if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
  1754. ResultTy = VectorType::get(ResultTy, VT->getNumElements());
  1755. LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
  1756. return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
  1757. }
  1758. Constant *ConstantExpr::getFCmp(unsigned short pred, Constant *LHS,
  1759. Constant *RHS, bool OnlyIfReduced) {
  1760. assert(LHS->getType() == RHS->getType());
  1761. assert(CmpInst::isFPPredicate((CmpInst::Predicate)pred) &&
  1762. "Invalid FCmp Predicate");
  1763. if (Constant *FC = ConstantFoldCompareInstruction(pred, LHS, RHS))
  1764. return FC; // Fold a few common cases...
  1765. if (OnlyIfReduced)
  1766. return nullptr;
  1767. // Look up the constant in the table first to ensure uniqueness
  1768. Constant *ArgVec[] = { LHS, RHS };
  1769. // Get the key type with both the opcode and predicate
  1770. const ConstantExprKeyType Key(Instruction::FCmp, ArgVec, pred);
  1771. Type *ResultTy = Type::getInt1Ty(LHS->getContext());
  1772. if (VectorType *VT = dyn_cast<VectorType>(LHS->getType()))
  1773. ResultTy = VectorType::get(ResultTy, VT->getNumElements());
  1774. LLVMContextImpl *pImpl = LHS->getType()->getContext().pImpl;
  1775. return pImpl->ExprConstants.getOrCreate(ResultTy, Key);
  1776. }
  1777. Constant *ConstantExpr::getExtractElement(Constant *Val, Constant *Idx,
  1778. Type *OnlyIfReducedTy) {
  1779. assert(Val->getType()->isVectorTy() &&
  1780. "Tried to create extractelement operation on non-vector type!");
  1781. assert(Idx->getType()->isIntegerTy() &&
  1782. "Extractelement index must be an integer type!");
  1783. if (Constant *FC = ConstantFoldExtractElementInstruction(Val, Idx))
  1784. return FC; // Fold a few common cases.
  1785. Type *ReqTy = Val->getType()->getVectorElementType();
  1786. if (OnlyIfReducedTy == ReqTy)
  1787. return nullptr;
  1788. // Look up the constant in the table first to ensure uniqueness
  1789. Constant *ArgVec[] = { Val, Idx };
  1790. const ConstantExprKeyType Key(Instruction::ExtractElement, ArgVec);
  1791. LLVMContextImpl *pImpl = Val->getContext().pImpl;
  1792. return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
  1793. }
  1794. Constant *ConstantExpr::getInsertElement(Constant *Val, Constant *Elt,
  1795. Constant *Idx, Type *OnlyIfReducedTy) {
  1796. assert(Val->getType()->isVectorTy() &&
  1797. "Tried to create insertelement operation on non-vector type!");
  1798. assert(Elt->getType() == Val->getType()->getVectorElementType() &&
  1799. "Insertelement types must match!");
  1800. assert(Idx->getType()->isIntegerTy() &&
  1801. "Insertelement index must be i32 type!");
  1802. if (Constant *FC = ConstantFoldInsertElementInstruction(Val, Elt, Idx))
  1803. return FC; // Fold a few common cases.
  1804. if (OnlyIfReducedTy == Val->getType())
  1805. return nullptr;
  1806. // Look up the constant in the table first to ensure uniqueness
  1807. Constant *ArgVec[] = { Val, Elt, Idx };
  1808. const ConstantExprKeyType Key(Instruction::InsertElement, ArgVec);
  1809. LLVMContextImpl *pImpl = Val->getContext().pImpl;
  1810. return pImpl->ExprConstants.getOrCreate(Val->getType(), Key);
  1811. }
  1812. Constant *ConstantExpr::getShuffleVector(Constant *V1, Constant *V2,
  1813. Constant *Mask, Type *OnlyIfReducedTy) {
  1814. assert(ShuffleVectorInst::isValidOperands(V1, V2, Mask) &&
  1815. "Invalid shuffle vector constant expr operands!");
  1816. if (Constant *FC = ConstantFoldShuffleVectorInstruction(V1, V2, Mask))
  1817. return FC; // Fold a few common cases.
  1818. unsigned NElts = Mask->getType()->getVectorNumElements();
  1819. Type *EltTy = V1->getType()->getVectorElementType();
  1820. Type *ShufTy = VectorType::get(EltTy, NElts);
  1821. if (OnlyIfReducedTy == ShufTy)
  1822. return nullptr;
  1823. // Look up the constant in the table first to ensure uniqueness
  1824. Constant *ArgVec[] = { V1, V2, Mask };
  1825. const ConstantExprKeyType Key(Instruction::ShuffleVector, ArgVec);
  1826. LLVMContextImpl *pImpl = ShufTy->getContext().pImpl;
  1827. return pImpl->ExprConstants.getOrCreate(ShufTy, Key);
  1828. }
  1829. Constant *ConstantExpr::getInsertValue(Constant *Agg, Constant *Val,
  1830. ArrayRef<unsigned> Idxs,
  1831. Type *OnlyIfReducedTy) {
  1832. assert(Agg->getType()->isFirstClassType() &&
  1833. "Non-first-class type for constant insertvalue expression");
  1834. assert(ExtractValueInst::getIndexedType(Agg->getType(),
  1835. Idxs) == Val->getType() &&
  1836. "insertvalue indices invalid!");
  1837. Type *ReqTy = Val->getType();
  1838. if (Constant *FC = ConstantFoldInsertValueInstruction(Agg, Val, Idxs))
  1839. return FC;
  1840. if (OnlyIfReducedTy == ReqTy)
  1841. return nullptr;
  1842. Constant *ArgVec[] = { Agg, Val };
  1843. const ConstantExprKeyType Key(Instruction::InsertValue, ArgVec, 0, 0, Idxs);
  1844. LLVMContextImpl *pImpl = Agg->getContext().pImpl;
  1845. return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
  1846. }
  1847. Constant *ConstantExpr::getExtractValue(Constant *Agg, ArrayRef<unsigned> Idxs,
  1848. Type *OnlyIfReducedTy) {
  1849. assert(Agg->getType()->isFirstClassType() &&
  1850. "Tried to create extractelement operation on non-first-class type!");
  1851. Type *ReqTy = ExtractValueInst::getIndexedType(Agg->getType(), Idxs);
  1852. (void)ReqTy;
  1853. assert(ReqTy && "extractvalue indices invalid!");
  1854. assert(Agg->getType()->isFirstClassType() &&
  1855. "Non-first-class type for constant extractvalue expression");
  1856. if (Constant *FC = ConstantFoldExtractValueInstruction(Agg, Idxs))
  1857. return FC;
  1858. if (OnlyIfReducedTy == ReqTy)
  1859. return nullptr;
  1860. Constant *ArgVec[] = { Agg };
  1861. const ConstantExprKeyType Key(Instruction::ExtractValue, ArgVec, 0, 0, Idxs);
  1862. LLVMContextImpl *pImpl = Agg->getContext().pImpl;
  1863. return pImpl->ExprConstants.getOrCreate(ReqTy, Key);
  1864. }
  1865. Constant *ConstantExpr::getNeg(Constant *C, bool HasNUW, bool HasNSW) {
  1866. assert(C->getType()->isIntOrIntVectorTy() &&
  1867. "Cannot NEG a nonintegral value!");
  1868. return getSub(ConstantFP::getZeroValueForNegation(C->getType()),
  1869. C, HasNUW, HasNSW);
  1870. }
  1871. Constant *ConstantExpr::getFNeg(Constant *C) {
  1872. assert(C->getType()->isFPOrFPVectorTy() &&
  1873. "Cannot FNEG a non-floating-point value!");
  1874. return get(Instruction::FNeg, C);
  1875. }
  1876. Constant *ConstantExpr::getNot(Constant *C) {
  1877. assert(C->getType()->isIntOrIntVectorTy() &&
  1878. "Cannot NOT a nonintegral value!");
  1879. return get(Instruction::Xor, C, Constant::getAllOnesValue(C->getType()));
  1880. }
  1881. Constant *ConstantExpr::getAdd(Constant *C1, Constant *C2,
  1882. bool HasNUW, bool HasNSW) {
  1883. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  1884. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  1885. return get(Instruction::Add, C1, C2, Flags);
  1886. }
  1887. Constant *ConstantExpr::getFAdd(Constant *C1, Constant *C2) {
  1888. return get(Instruction::FAdd, C1, C2);
  1889. }
  1890. Constant *ConstantExpr::getSub(Constant *C1, Constant *C2,
  1891. bool HasNUW, bool HasNSW) {
  1892. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  1893. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  1894. return get(Instruction::Sub, C1, C2, Flags);
  1895. }
  1896. Constant *ConstantExpr::getFSub(Constant *C1, Constant *C2) {
  1897. return get(Instruction::FSub, C1, C2);
  1898. }
  1899. Constant *ConstantExpr::getMul(Constant *C1, Constant *C2,
  1900. bool HasNUW, bool HasNSW) {
  1901. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  1902. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  1903. return get(Instruction::Mul, C1, C2, Flags);
  1904. }
  1905. Constant *ConstantExpr::getFMul(Constant *C1, Constant *C2) {
  1906. return get(Instruction::FMul, C1, C2);
  1907. }
  1908. Constant *ConstantExpr::getUDiv(Constant *C1, Constant *C2, bool isExact) {
  1909. return get(Instruction::UDiv, C1, C2,
  1910. isExact ? PossiblyExactOperator::IsExact : 0);
  1911. }
  1912. Constant *ConstantExpr::getSDiv(Constant *C1, Constant *C2, bool isExact) {
  1913. return get(Instruction::SDiv, C1, C2,
  1914. isExact ? PossiblyExactOperator::IsExact : 0);
  1915. }
  1916. Constant *ConstantExpr::getFDiv(Constant *C1, Constant *C2) {
  1917. return get(Instruction::FDiv, C1, C2);
  1918. }
  1919. Constant *ConstantExpr::getURem(Constant *C1, Constant *C2) {
  1920. return get(Instruction::URem, C1, C2);
  1921. }
  1922. Constant *ConstantExpr::getSRem(Constant *C1, Constant *C2) {
  1923. return get(Instruction::SRem, C1, C2);
  1924. }
  1925. Constant *ConstantExpr::getFRem(Constant *C1, Constant *C2) {
  1926. return get(Instruction::FRem, C1, C2);
  1927. }
  1928. Constant *ConstantExpr::getAnd(Constant *C1, Constant *C2) {
  1929. return get(Instruction::And, C1, C2);
  1930. }
  1931. Constant *ConstantExpr::getOr(Constant *C1, Constant *C2) {
  1932. return get(Instruction::Or, C1, C2);
  1933. }
  1934. Constant *ConstantExpr::getXor(Constant *C1, Constant *C2) {
  1935. return get(Instruction::Xor, C1, C2);
  1936. }
  1937. Constant *ConstantExpr::getShl(Constant *C1, Constant *C2,
  1938. bool HasNUW, bool HasNSW) {
  1939. unsigned Flags = (HasNUW ? OverflowingBinaryOperator::NoUnsignedWrap : 0) |
  1940. (HasNSW ? OverflowingBinaryOperator::NoSignedWrap : 0);
  1941. return get(Instruction::Shl, C1, C2, Flags);
  1942. }
  1943. Constant *ConstantExpr::getLShr(Constant *C1, Constant *C2, bool isExact) {
  1944. return get(Instruction::LShr, C1, C2,
  1945. isExact ? PossiblyExactOperator::IsExact : 0);
  1946. }
  1947. Constant *ConstantExpr::getAShr(Constant *C1, Constant *C2, bool isExact) {
  1948. return get(Instruction::AShr, C1, C2,
  1949. isExact ? PossiblyExactOperator::IsExact : 0);
  1950. }
  1951. Constant *ConstantExpr::getBinOpIdentity(unsigned Opcode, Type *Ty,
  1952. bool AllowRHSConstant) {
  1953. assert(Instruction::isBinaryOp(Opcode) && "Only binops allowed");
  1954. // Commutative opcodes: it does not matter if AllowRHSConstant is set.
  1955. if (Instruction::isCommutative(Opcode)) {
  1956. switch (Opcode) {
  1957. case Instruction::Add: // X + 0 = X
  1958. case Instruction::Or: // X | 0 = X
  1959. case Instruction::Xor: // X ^ 0 = X
  1960. return Constant::getNullValue(Ty);
  1961. case Instruction::Mul: // X * 1 = X
  1962. return ConstantInt::get(Ty, 1);
  1963. case Instruction::And: // X & -1 = X
  1964. return Constant::getAllOnesValue(Ty);
  1965. case Instruction::FAdd: // X + -0.0 = X
  1966. // TODO: If the fadd has 'nsz', should we return +0.0?
  1967. return ConstantFP::getNegativeZero(Ty);
  1968. case Instruction::FMul: // X * 1.0 = X
  1969. return ConstantFP::get(Ty, 1.0);
  1970. default:
  1971. llvm_unreachable("Every commutative binop has an identity constant");
  1972. }
  1973. }
  1974. // Non-commutative opcodes: AllowRHSConstant must be set.
  1975. if (!AllowRHSConstant)
  1976. return nullptr;
  1977. switch (Opcode) {
  1978. case Instruction::Sub: // X - 0 = X
  1979. case Instruction::Shl: // X << 0 = X
  1980. case Instruction::LShr: // X >>u 0 = X
  1981. case Instruction::AShr: // X >> 0 = X
  1982. case Instruction::FSub: // X - 0.0 = X
  1983. return Constant::getNullValue(Ty);
  1984. case Instruction::SDiv: // X / 1 = X
  1985. case Instruction::UDiv: // X /u 1 = X
  1986. return ConstantInt::get(Ty, 1);
  1987. case Instruction::FDiv: // X / 1.0 = X
  1988. return ConstantFP::get(Ty, 1.0);
  1989. default:
  1990. return nullptr;
  1991. }
  1992. }
  1993. Constant *ConstantExpr::getBinOpAbsorber(unsigned Opcode, Type *Ty) {
  1994. switch (Opcode) {
  1995. default:
  1996. // Doesn't have an absorber.
  1997. return nullptr;
  1998. case Instruction::Or:
  1999. return Constant::getAllOnesValue(Ty);
  2000. case Instruction::And:
  2001. case Instruction::Mul:
  2002. return Constant::getNullValue(Ty);
  2003. }
  2004. }
  2005. /// Remove the constant from the constant table.
  2006. void ConstantExpr::destroyConstantImpl() {
  2007. getType()->getContext().pImpl->ExprConstants.remove(this);
  2008. }
  2009. const char *ConstantExpr::getOpcodeName() const {
  2010. return Instruction::getOpcodeName(getOpcode());
  2011. }
  2012. GetElementPtrConstantExpr::GetElementPtrConstantExpr(
  2013. Type *SrcElementTy, Constant *C, ArrayRef<Constant *> IdxList, Type *DestTy)
  2014. : ConstantExpr(DestTy, Instruction::GetElementPtr,
  2015. OperandTraits<GetElementPtrConstantExpr>::op_end(this) -
  2016. (IdxList.size() + 1),
  2017. IdxList.size() + 1),
  2018. SrcElementTy(SrcElementTy),
  2019. ResElementTy(GetElementPtrInst::getIndexedType(SrcElementTy, IdxList)) {
  2020. Op<0>() = C;
  2021. Use *OperandList = getOperandList();
  2022. for (unsigned i = 0, E = IdxList.size(); i != E; ++i)
  2023. OperandList[i+1] = IdxList[i];
  2024. }
  2025. Type *GetElementPtrConstantExpr::getSourceElementType() const {
  2026. return SrcElementTy;
  2027. }
  2028. Type *GetElementPtrConstantExpr::getResultElementType() const {
  2029. return ResElementTy;
  2030. }
  2031. //===----------------------------------------------------------------------===//
  2032. // ConstantData* implementations
  2033. Type *ConstantDataSequential::getElementType() const {
  2034. return getType()->getElementType();
  2035. }
  2036. StringRef ConstantDataSequential::getRawDataValues() const {
  2037. return StringRef(DataElements, getNumElements()*getElementByteSize());
  2038. }
  2039. bool ConstantDataSequential::isElementTypeCompatible(Type *Ty) {
  2040. if (Ty->isHalfTy() || Ty->isFloatTy() || Ty->isDoubleTy()) return true;
  2041. if (auto *IT = dyn_cast<IntegerType>(Ty)) {
  2042. switch (IT->getBitWidth()) {
  2043. case 8:
  2044. case 16:
  2045. case 32:
  2046. case 64:
  2047. return true;
  2048. default: break;
  2049. }
  2050. }
  2051. return false;
  2052. }
  2053. unsigned ConstantDataSequential::getNumElements() const {
  2054. if (ArrayType *AT = dyn_cast<ArrayType>(getType()))
  2055. return AT->getNumElements();
  2056. return getType()->getVectorNumElements();
  2057. }
  2058. uint64_t ConstantDataSequential::getElementByteSize() const {
  2059. return getElementType()->getPrimitiveSizeInBits()/8;
  2060. }
  2061. /// Return the start of the specified element.
  2062. const char *ConstantDataSequential::getElementPointer(unsigned Elt) const {
  2063. assert(Elt < getNumElements() && "Invalid Elt");
  2064. return DataElements+Elt*getElementByteSize();
  2065. }
  2066. /// Return true if the array is empty or all zeros.
  2067. static bool isAllZeros(StringRef Arr) {
  2068. for (char I : Arr)
  2069. if (I != 0)
  2070. return false;
  2071. return true;
  2072. }
  2073. /// This is the underlying implementation of all of the
  2074. /// ConstantDataSequential::get methods. They all thunk down to here, providing
  2075. /// the correct element type. We take the bytes in as a StringRef because
  2076. /// we *want* an underlying "char*" to avoid TBAA type punning violations.
  2077. Constant *ConstantDataSequential::getImpl(StringRef Elements, Type *Ty) {
  2078. assert(isElementTypeCompatible(Ty->getSequentialElementType()));
  2079. // If the elements are all zero or there are no elements, return a CAZ, which
  2080. // is more dense and canonical.
  2081. if (isAllZeros(Elements))
  2082. return ConstantAggregateZero::get(Ty);
  2083. // Do a lookup to see if we have already formed one of these.
  2084. auto &Slot =
  2085. *Ty->getContext()
  2086. .pImpl->CDSConstants.insert(std::make_pair(Elements, nullptr))
  2087. .first;
  2088. // The bucket can point to a linked list of different CDS's that have the same
  2089. // body but different types. For example, 0,0,0,1 could be a 4 element array
  2090. // of i8, or a 1-element array of i32. They'll both end up in the same
  2091. /// StringMap bucket, linked up by their Next pointers. Walk the list.
  2092. ConstantDataSequential **Entry = &Slot.second;
  2093. for (ConstantDataSequential *Node = *Entry; Node;
  2094. Entry = &Node->Next, Node = *Entry)
  2095. if (Node->getType() == Ty)
  2096. return Node;
  2097. // Okay, we didn't get a hit. Create a node of the right class, link it in,
  2098. // and return it.
  2099. if (isa<ArrayType>(Ty))
  2100. return *Entry = new ConstantDataArray(Ty, Slot.first().data());
  2101. assert(isa<VectorType>(Ty));
  2102. return *Entry = new ConstantDataVector(Ty, Slot.first().data());
  2103. }
  2104. void ConstantDataSequential::destroyConstantImpl() {
  2105. // Remove the constant from the StringMap.
  2106. StringMap<ConstantDataSequential*> &CDSConstants =
  2107. getType()->getContext().pImpl->CDSConstants;
  2108. StringMap<ConstantDataSequential*>::iterator Slot =
  2109. CDSConstants.find(getRawDataValues());
  2110. assert(Slot != CDSConstants.end() && "CDS not found in uniquing table");
  2111. ConstantDataSequential **Entry = &Slot->getValue();
  2112. // Remove the entry from the hash table.
  2113. if (!(*Entry)->Next) {
  2114. // If there is only one value in the bucket (common case) it must be this
  2115. // entry, and removing the entry should remove the bucket completely.
  2116. assert((*Entry) == this && "Hash mismatch in ConstantDataSequential");
  2117. getContext().pImpl->CDSConstants.erase(Slot);
  2118. } else {
  2119. // Otherwise, there are multiple entries linked off the bucket, unlink the
  2120. // node we care about but keep the bucket around.
  2121. for (ConstantDataSequential *Node = *Entry; ;
  2122. Entry = &Node->Next, Node = *Entry) {
  2123. assert(Node && "Didn't find entry in its uniquing hash table!");
  2124. // If we found our entry, unlink it from the list and we're done.
  2125. if (Node == this) {
  2126. *Entry = Node->Next;
  2127. break;
  2128. }
  2129. }
  2130. }
  2131. // If we were part of a list, make sure that we don't delete the list that is
  2132. // still owned by the uniquing map.
  2133. Next = nullptr;
  2134. }
  2135. /// getFP() constructors - Return a constant with array type with an element
  2136. /// count and element type of float with precision matching the number of
  2137. /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
  2138. /// double for 64bits) Note that this can return a ConstantAggregateZero
  2139. /// object.
  2140. Constant *ConstantDataArray::getFP(LLVMContext &Context,
  2141. ArrayRef<uint16_t> Elts) {
  2142. Type *Ty = ArrayType::get(Type::getHalfTy(Context), Elts.size());
  2143. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2144. return getImpl(StringRef(Data, Elts.size() * 2), Ty);
  2145. }
  2146. Constant *ConstantDataArray::getFP(LLVMContext &Context,
  2147. ArrayRef<uint32_t> Elts) {
  2148. Type *Ty = ArrayType::get(Type::getFloatTy(Context), Elts.size());
  2149. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2150. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2151. }
  2152. Constant *ConstantDataArray::getFP(LLVMContext &Context,
  2153. ArrayRef<uint64_t> Elts) {
  2154. Type *Ty = ArrayType::get(Type::getDoubleTy(Context), Elts.size());
  2155. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2156. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2157. }
  2158. Constant *ConstantDataArray::getString(LLVMContext &Context,
  2159. StringRef Str, bool AddNull) {
  2160. if (!AddNull) {
  2161. const uint8_t *Data = Str.bytes_begin();
  2162. return get(Context, makeArrayRef(Data, Str.size()));
  2163. }
  2164. SmallVector<uint8_t, 64> ElementVals;
  2165. ElementVals.append(Str.begin(), Str.end());
  2166. ElementVals.push_back(0);
  2167. return get(Context, ElementVals);
  2168. }
  2169. /// get() constructors - Return a constant with vector type with an element
  2170. /// count and element type matching the ArrayRef passed in. Note that this
  2171. /// can return a ConstantAggregateZero object.
  2172. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint8_t> Elts){
  2173. Type *Ty = VectorType::get(Type::getInt8Ty(Context), Elts.size());
  2174. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2175. return getImpl(StringRef(Data, Elts.size() * 1), Ty);
  2176. }
  2177. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint16_t> Elts){
  2178. Type *Ty = VectorType::get(Type::getInt16Ty(Context), Elts.size());
  2179. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2180. return getImpl(StringRef(Data, Elts.size() * 2), Ty);
  2181. }
  2182. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint32_t> Elts){
  2183. Type *Ty = VectorType::get(Type::getInt32Ty(Context), Elts.size());
  2184. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2185. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2186. }
  2187. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<uint64_t> Elts){
  2188. Type *Ty = VectorType::get(Type::getInt64Ty(Context), Elts.size());
  2189. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2190. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2191. }
  2192. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<float> Elts) {
  2193. Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
  2194. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2195. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2196. }
  2197. Constant *ConstantDataVector::get(LLVMContext &Context, ArrayRef<double> Elts) {
  2198. Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
  2199. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2200. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2201. }
  2202. /// getFP() constructors - Return a constant with vector type with an element
  2203. /// count and element type of float with the precision matching the number of
  2204. /// bits in the ArrayRef passed in. (i.e. half for 16bits, float for 32bits,
  2205. /// double for 64bits) Note that this can return a ConstantAggregateZero
  2206. /// object.
  2207. Constant *ConstantDataVector::getFP(LLVMContext &Context,
  2208. ArrayRef<uint16_t> Elts) {
  2209. Type *Ty = VectorType::get(Type::getHalfTy(Context), Elts.size());
  2210. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2211. return getImpl(StringRef(Data, Elts.size() * 2), Ty);
  2212. }
  2213. Constant *ConstantDataVector::getFP(LLVMContext &Context,
  2214. ArrayRef<uint32_t> Elts) {
  2215. Type *Ty = VectorType::get(Type::getFloatTy(Context), Elts.size());
  2216. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2217. return getImpl(StringRef(Data, Elts.size() * 4), Ty);
  2218. }
  2219. Constant *ConstantDataVector::getFP(LLVMContext &Context,
  2220. ArrayRef<uint64_t> Elts) {
  2221. Type *Ty = VectorType::get(Type::getDoubleTy(Context), Elts.size());
  2222. const char *Data = reinterpret_cast<const char *>(Elts.data());
  2223. return getImpl(StringRef(Data, Elts.size() * 8), Ty);
  2224. }
  2225. Constant *ConstantDataVector::getSplat(unsigned NumElts, Constant *V) {
  2226. assert(isElementTypeCompatible(V->getType()) &&
  2227. "Element type not compatible with ConstantData");
  2228. if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
  2229. if (CI->getType()->isIntegerTy(8)) {
  2230. SmallVector<uint8_t, 16> Elts(NumElts, CI->getZExtValue());
  2231. return get(V->getContext(), Elts);
  2232. }
  2233. if (CI->getType()->isIntegerTy(16)) {
  2234. SmallVector<uint16_t, 16> Elts(NumElts, CI->getZExtValue());
  2235. return get(V->getContext(), Elts);
  2236. }
  2237. if (CI->getType()->isIntegerTy(32)) {
  2238. SmallVector<uint32_t, 16> Elts(NumElts, CI->getZExtValue());
  2239. return get(V->getContext(), Elts);
  2240. }
  2241. assert(CI->getType()->isIntegerTy(64) && "Unsupported ConstantData type");
  2242. SmallVector<uint64_t, 16> Elts(NumElts, CI->getZExtValue());
  2243. return get(V->getContext(), Elts);
  2244. }
  2245. if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
  2246. if (CFP->getType()->isHalfTy()) {
  2247. SmallVector<uint16_t, 16> Elts(
  2248. NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  2249. return getFP(V->getContext(), Elts);
  2250. }
  2251. if (CFP->getType()->isFloatTy()) {
  2252. SmallVector<uint32_t, 16> Elts(
  2253. NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  2254. return getFP(V->getContext(), Elts);
  2255. }
  2256. if (CFP->getType()->isDoubleTy()) {
  2257. SmallVector<uint64_t, 16> Elts(
  2258. NumElts, CFP->getValueAPF().bitcastToAPInt().getLimitedValue());
  2259. return getFP(V->getContext(), Elts);
  2260. }
  2261. }
  2262. return ConstantVector::getSplat(NumElts, V);
  2263. }
  2264. uint64_t ConstantDataSequential::getElementAsInteger(unsigned Elt) const {
  2265. assert(isa<IntegerType>(getElementType()) &&
  2266. "Accessor can only be used when element is an integer");
  2267. const char *EltPtr = getElementPointer(Elt);
  2268. // The data is stored in host byte order, make sure to cast back to the right
  2269. // type to load with the right endianness.
  2270. switch (getElementType()->getIntegerBitWidth()) {
  2271. default: llvm_unreachable("Invalid bitwidth for CDS");
  2272. case 8:
  2273. return *reinterpret_cast<const uint8_t *>(EltPtr);
  2274. case 16:
  2275. return *reinterpret_cast<const uint16_t *>(EltPtr);
  2276. case 32:
  2277. return *reinterpret_cast<const uint32_t *>(EltPtr);
  2278. case 64:
  2279. return *reinterpret_cast<const uint64_t *>(EltPtr);
  2280. }
  2281. }
  2282. APInt ConstantDataSequential::getElementAsAPInt(unsigned Elt) const {
  2283. assert(isa<IntegerType>(getElementType()) &&
  2284. "Accessor can only be used when element is an integer");
  2285. const char *EltPtr = getElementPointer(Elt);
  2286. // The data is stored in host byte order, make sure to cast back to the right
  2287. // type to load with the right endianness.
  2288. switch (getElementType()->getIntegerBitWidth()) {
  2289. default: llvm_unreachable("Invalid bitwidth for CDS");
  2290. case 8: {
  2291. auto EltVal = *reinterpret_cast<const uint8_t *>(EltPtr);
  2292. return APInt(8, EltVal);
  2293. }
  2294. case 16: {
  2295. auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
  2296. return APInt(16, EltVal);
  2297. }
  2298. case 32: {
  2299. auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
  2300. return APInt(32, EltVal);
  2301. }
  2302. case 64: {
  2303. auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
  2304. return APInt(64, EltVal);
  2305. }
  2306. }
  2307. }
  2308. APFloat ConstantDataSequential::getElementAsAPFloat(unsigned Elt) const {
  2309. const char *EltPtr = getElementPointer(Elt);
  2310. switch (getElementType()->getTypeID()) {
  2311. default:
  2312. llvm_unreachable("Accessor can only be used when element is float/double!");
  2313. case Type::HalfTyID: {
  2314. auto EltVal = *reinterpret_cast<const uint16_t *>(EltPtr);
  2315. return APFloat(APFloat::IEEEhalf(), APInt(16, EltVal));
  2316. }
  2317. case Type::FloatTyID: {
  2318. auto EltVal = *reinterpret_cast<const uint32_t *>(EltPtr);
  2319. return APFloat(APFloat::IEEEsingle(), APInt(32, EltVal));
  2320. }
  2321. case Type::DoubleTyID: {
  2322. auto EltVal = *reinterpret_cast<const uint64_t *>(EltPtr);
  2323. return APFloat(APFloat::IEEEdouble(), APInt(64, EltVal));
  2324. }
  2325. }
  2326. }
  2327. float ConstantDataSequential::getElementAsFloat(unsigned Elt) const {
  2328. assert(getElementType()->isFloatTy() &&
  2329. "Accessor can only be used when element is a 'float'");
  2330. return *reinterpret_cast<const float *>(getElementPointer(Elt));
  2331. }
  2332. double ConstantDataSequential::getElementAsDouble(unsigned Elt) const {
  2333. assert(getElementType()->isDoubleTy() &&
  2334. "Accessor can only be used when element is a 'float'");
  2335. return *reinterpret_cast<const double *>(getElementPointer(Elt));
  2336. }
  2337. Constant *ConstantDataSequential::getElementAsConstant(unsigned Elt) const {
  2338. if (getElementType()->isHalfTy() || getElementType()->isFloatTy() ||
  2339. getElementType()->isDoubleTy())
  2340. return ConstantFP::get(getContext(), getElementAsAPFloat(Elt));
  2341. return ConstantInt::get(getElementType(), getElementAsInteger(Elt));
  2342. }
  2343. bool ConstantDataSequential::isString(unsigned CharSize) const {
  2344. return isa<ArrayType>(getType()) && getElementType()->isIntegerTy(CharSize);
  2345. }
  2346. bool ConstantDataSequential::isCString() const {
  2347. if (!isString())
  2348. return false;
  2349. StringRef Str = getAsString();
  2350. // The last value must be nul.
  2351. if (Str.back() != 0) return false;
  2352. // Other elements must be non-nul.
  2353. return Str.drop_back().find(0) == StringRef::npos;
  2354. }
  2355. bool ConstantDataVector::isSplat() const {
  2356. const char *Base = getRawDataValues().data();
  2357. // Compare elements 1+ to the 0'th element.
  2358. unsigned EltSize = getElementByteSize();
  2359. for (unsigned i = 1, e = getNumElements(); i != e; ++i)
  2360. if (memcmp(Base, Base+i*EltSize, EltSize))
  2361. return false;
  2362. return true;
  2363. }
  2364. Constant *ConstantDataVector::getSplatValue() const {
  2365. // If they're all the same, return the 0th one as a representative.
  2366. return isSplat() ? getElementAsConstant(0) : nullptr;
  2367. }
  2368. //===----------------------------------------------------------------------===//
  2369. // handleOperandChange implementations
  2370. /// Update this constant array to change uses of
  2371. /// 'From' to be uses of 'To'. This must update the uniquing data structures
  2372. /// etc.
  2373. ///
  2374. /// Note that we intentionally replace all uses of From with To here. Consider
  2375. /// a large array that uses 'From' 1000 times. By handling this case all here,
  2376. /// ConstantArray::handleOperandChange is only invoked once, and that
  2377. /// single invocation handles all 1000 uses. Handling them one at a time would
  2378. /// work, but would be really slow because it would have to unique each updated
  2379. /// array instance.
  2380. ///
  2381. void Constant::handleOperandChange(Value *From, Value *To) {
  2382. Value *Replacement = nullptr;
  2383. switch (getValueID()) {
  2384. default:
  2385. llvm_unreachable("Not a constant!");
  2386. #define HANDLE_CONSTANT(Name) \
  2387. case Value::Name##Val: \
  2388. Replacement = cast<Name>(this)->handleOperandChangeImpl(From, To); \
  2389. break;
  2390. #include "llvm/IR/Value.def"
  2391. }
  2392. // If handleOperandChangeImpl returned nullptr, then it handled
  2393. // replacing itself and we don't want to delete or replace anything else here.
  2394. if (!Replacement)
  2395. return;
  2396. // I do need to replace this with an existing value.
  2397. assert(Replacement != this && "I didn't contain From!");
  2398. // Everyone using this now uses the replacement.
  2399. replaceAllUsesWith(Replacement);
  2400. // Delete the old constant!
  2401. destroyConstant();
  2402. }
  2403. Value *ConstantArray::handleOperandChangeImpl(Value *From, Value *To) {
  2404. assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
  2405. Constant *ToC = cast<Constant>(To);
  2406. SmallVector<Constant*, 8> Values;
  2407. Values.reserve(getNumOperands()); // Build replacement array.
  2408. // Fill values with the modified operands of the constant array. Also,
  2409. // compute whether this turns into an all-zeros array.
  2410. unsigned NumUpdated = 0;
  2411. // Keep track of whether all the values in the array are "ToC".
  2412. bool AllSame = true;
  2413. Use *OperandList = getOperandList();
  2414. unsigned OperandNo = 0;
  2415. for (Use *O = OperandList, *E = OperandList+getNumOperands(); O != E; ++O) {
  2416. Constant *Val = cast<Constant>(O->get());
  2417. if (Val == From) {
  2418. OperandNo = (O - OperandList);
  2419. Val = ToC;
  2420. ++NumUpdated;
  2421. }
  2422. Values.push_back(Val);
  2423. AllSame &= Val == ToC;
  2424. }
  2425. if (AllSame && ToC->isNullValue())
  2426. return ConstantAggregateZero::get(getType());
  2427. if (AllSame && isa<UndefValue>(ToC))
  2428. return UndefValue::get(getType());
  2429. // Check for any other type of constant-folding.
  2430. if (Constant *C = getImpl(getType(), Values))
  2431. return C;
  2432. // Update to the new value.
  2433. return getContext().pImpl->ArrayConstants.replaceOperandsInPlace(
  2434. Values, this, From, ToC, NumUpdated, OperandNo);
  2435. }
  2436. Value *ConstantStruct::handleOperandChangeImpl(Value *From, Value *To) {
  2437. assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
  2438. Constant *ToC = cast<Constant>(To);
  2439. Use *OperandList = getOperandList();
  2440. SmallVector<Constant*, 8> Values;
  2441. Values.reserve(getNumOperands()); // Build replacement struct.
  2442. // Fill values with the modified operands of the constant struct. Also,
  2443. // compute whether this turns into an all-zeros struct.
  2444. unsigned NumUpdated = 0;
  2445. bool AllSame = true;
  2446. unsigned OperandNo = 0;
  2447. for (Use *O = OperandList, *E = OperandList + getNumOperands(); O != E; ++O) {
  2448. Constant *Val = cast<Constant>(O->get());
  2449. if (Val == From) {
  2450. OperandNo = (O - OperandList);
  2451. Val = ToC;
  2452. ++NumUpdated;
  2453. }
  2454. Values.push_back(Val);
  2455. AllSame &= Val == ToC;
  2456. }
  2457. if (AllSame && ToC->isNullValue())
  2458. return ConstantAggregateZero::get(getType());
  2459. if (AllSame && isa<UndefValue>(ToC))
  2460. return UndefValue::get(getType());
  2461. // Update to the new value.
  2462. return getContext().pImpl->StructConstants.replaceOperandsInPlace(
  2463. Values, this, From, ToC, NumUpdated, OperandNo);
  2464. }
  2465. Value *ConstantVector::handleOperandChangeImpl(Value *From, Value *To) {
  2466. assert(isa<Constant>(To) && "Cannot make Constant refer to non-constant!");
  2467. Constant *ToC = cast<Constant>(To);
  2468. SmallVector<Constant*, 8> Values;
  2469. Values.reserve(getNumOperands()); // Build replacement array...
  2470. unsigned NumUpdated = 0;
  2471. unsigned OperandNo = 0;
  2472. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  2473. Constant *Val = getOperand(i);
  2474. if (Val == From) {
  2475. OperandNo = i;
  2476. ++NumUpdated;
  2477. Val = ToC;
  2478. }
  2479. Values.push_back(Val);
  2480. }
  2481. if (Constant *C = getImpl(Values))
  2482. return C;
  2483. // Update to the new value.
  2484. return getContext().pImpl->VectorConstants.replaceOperandsInPlace(
  2485. Values, this, From, ToC, NumUpdated, OperandNo);
  2486. }
  2487. Value *ConstantExpr::handleOperandChangeImpl(Value *From, Value *ToV) {
  2488. assert(isa<Constant>(ToV) && "Cannot make Constant refer to non-constant!");
  2489. Constant *To = cast<Constant>(ToV);
  2490. SmallVector<Constant*, 8> NewOps;
  2491. unsigned NumUpdated = 0;
  2492. unsigned OperandNo = 0;
  2493. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  2494. Constant *Op = getOperand(i);
  2495. if (Op == From) {
  2496. OperandNo = i;
  2497. ++NumUpdated;
  2498. Op = To;
  2499. }
  2500. NewOps.push_back(Op);
  2501. }
  2502. assert(NumUpdated && "I didn't contain From!");
  2503. if (Constant *C = getWithOperands(NewOps, getType(), true))
  2504. return C;
  2505. // Update to the new value.
  2506. return getContext().pImpl->ExprConstants.replaceOperandsInPlace(
  2507. NewOps, this, From, To, NumUpdated, OperandNo);
  2508. }
  2509. Instruction *ConstantExpr::getAsInstruction() {
  2510. SmallVector<Value *, 4> ValueOperands(op_begin(), op_end());
  2511. ArrayRef<Value*> Ops(ValueOperands);
  2512. switch (getOpcode()) {
  2513. case Instruction::Trunc:
  2514. case Instruction::ZExt:
  2515. case Instruction::SExt:
  2516. case Instruction::FPTrunc:
  2517. case Instruction::FPExt:
  2518. case Instruction::UIToFP:
  2519. case Instruction::SIToFP:
  2520. case Instruction::FPToUI:
  2521. case Instruction::FPToSI:
  2522. case Instruction::PtrToInt:
  2523. case Instruction::IntToPtr:
  2524. case Instruction::BitCast:
  2525. case Instruction::AddrSpaceCast:
  2526. return CastInst::Create((Instruction::CastOps)getOpcode(),
  2527. Ops[0], getType());
  2528. case Instruction::Select:
  2529. return SelectInst::Create(Ops[0], Ops[1], Ops[2]);
  2530. case Instruction::InsertElement:
  2531. return InsertElementInst::Create(Ops[0], Ops[1], Ops[2]);
  2532. case Instruction::ExtractElement:
  2533. return ExtractElementInst::Create(Ops[0], Ops[1]);
  2534. case Instruction::InsertValue:
  2535. return InsertValueInst::Create(Ops[0], Ops[1], getIndices());
  2536. case Instruction::ExtractValue:
  2537. return ExtractValueInst::Create(Ops[0], getIndices());
  2538. case Instruction::ShuffleVector:
  2539. return new ShuffleVectorInst(Ops[0], Ops[1], Ops[2]);
  2540. case Instruction::GetElementPtr: {
  2541. const auto *GO = cast<GEPOperator>(this);
  2542. if (GO->isInBounds())
  2543. return GetElementPtrInst::CreateInBounds(GO->getSourceElementType(),
  2544. Ops[0], Ops.slice(1));
  2545. return GetElementPtrInst::Create(GO->getSourceElementType(), Ops[0],
  2546. Ops.slice(1));
  2547. }
  2548. case Instruction::ICmp:
  2549. case Instruction::FCmp:
  2550. return CmpInst::Create((Instruction::OtherOps)getOpcode(),
  2551. (CmpInst::Predicate)getPredicate(), Ops[0], Ops[1]);
  2552. case Instruction::FNeg:
  2553. return UnaryOperator::Create((Instruction::UnaryOps)getOpcode(), Ops[0]);
  2554. default:
  2555. assert(getNumOperands() == 2 && "Must be binary operator?");
  2556. BinaryOperator *BO =
  2557. BinaryOperator::Create((Instruction::BinaryOps)getOpcode(),
  2558. Ops[0], Ops[1]);
  2559. if (isa<OverflowingBinaryOperator>(BO)) {
  2560. BO->setHasNoUnsignedWrap(SubclassOptionalData &
  2561. OverflowingBinaryOperator::NoUnsignedWrap);
  2562. BO->setHasNoSignedWrap(SubclassOptionalData &
  2563. OverflowingBinaryOperator::NoSignedWrap);
  2564. }
  2565. if (isa<PossiblyExactOperator>(BO))
  2566. BO->setIsExact(SubclassOptionalData & PossiblyExactOperator::IsExact);
  2567. return BO;
  2568. }
  2569. }