Constants.cpp 126 KB

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