Constants.cpp 115 KB

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