CGExprConstant.cpp 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376
  1. //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This contains code to emit Constant Expr nodes as LLVM code.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "CGCXXABI.h"
  13. #include "CGObjCRuntime.h"
  14. #include "CGRecordLayout.h"
  15. #include "CodeGenFunction.h"
  16. #include "CodeGenModule.h"
  17. #include "ConstantEmitter.h"
  18. #include "TargetInfo.h"
  19. #include "clang/AST/APValue.h"
  20. #include "clang/AST/ASTContext.h"
  21. #include "clang/AST/Attr.h"
  22. #include "clang/AST/RecordLayout.h"
  23. #include "clang/AST/StmtVisitor.h"
  24. #include "clang/Basic/Builtins.h"
  25. #include "llvm/ADT/STLExtras.h"
  26. #include "llvm/ADT/Sequence.h"
  27. #include "llvm/IR/Constants.h"
  28. #include "llvm/IR/DataLayout.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/GlobalVariable.h"
  31. #include <optional>
  32. using namespace clang;
  33. using namespace CodeGen;
  34. //===----------------------------------------------------------------------===//
  35. // ConstantAggregateBuilder
  36. //===----------------------------------------------------------------------===//
  37. namespace {
  38. class ConstExprEmitter;
  39. struct ConstantAggregateBuilderUtils {
  40. CodeGenModule &CGM;
  41. ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
  42. CharUnits getAlignment(const llvm::Constant *C) const {
  43. return CharUnits::fromQuantity(
  44. CGM.getDataLayout().getABITypeAlign(C->getType()));
  45. }
  46. CharUnits getSize(llvm::Type *Ty) const {
  47. return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty));
  48. }
  49. CharUnits getSize(const llvm::Constant *C) const {
  50. return getSize(C->getType());
  51. }
  52. llvm::Constant *getPadding(CharUnits PadSize) const {
  53. llvm::Type *Ty = CGM.CharTy;
  54. if (PadSize > CharUnits::One())
  55. Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
  56. return llvm::UndefValue::get(Ty);
  57. }
  58. llvm::Constant *getZeroes(CharUnits ZeroSize) const {
  59. llvm::Type *Ty = llvm::ArrayType::get(CGM.CharTy, ZeroSize.getQuantity());
  60. return llvm::ConstantAggregateZero::get(Ty);
  61. }
  62. };
  63. /// Incremental builder for an llvm::Constant* holding a struct or array
  64. /// constant.
  65. class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
  66. /// The elements of the constant. These two arrays must have the same size;
  67. /// Offsets[i] describes the offset of Elems[i] within the constant. The
  68. /// elements are kept in increasing offset order, and we ensure that there
  69. /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
  70. ///
  71. /// This may contain explicit padding elements (in order to create a
  72. /// natural layout), but need not. Gaps between elements are implicitly
  73. /// considered to be filled with undef.
  74. llvm::SmallVector<llvm::Constant*, 32> Elems;
  75. llvm::SmallVector<CharUnits, 32> Offsets;
  76. /// The size of the constant (the maximum end offset of any added element).
  77. /// May be larger than the end of Elems.back() if we split the last element
  78. /// and removed some trailing undefs.
  79. CharUnits Size = CharUnits::Zero();
  80. /// This is true only if laying out Elems in order as the elements of a
  81. /// non-packed LLVM struct will give the correct layout.
  82. bool NaturalLayout = true;
  83. bool split(size_t Index, CharUnits Hint);
  84. std::optional<size_t> splitAt(CharUnits Pos);
  85. static llvm::Constant *buildFrom(CodeGenModule &CGM,
  86. ArrayRef<llvm::Constant *> Elems,
  87. ArrayRef<CharUnits> Offsets,
  88. CharUnits StartOffset, CharUnits Size,
  89. bool NaturalLayout, llvm::Type *DesiredTy,
  90. bool AllowOversized);
  91. public:
  92. ConstantAggregateBuilder(CodeGenModule &CGM)
  93. : ConstantAggregateBuilderUtils(CGM) {}
  94. /// Update or overwrite the value starting at \p Offset with \c C.
  95. ///
  96. /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
  97. /// a constant that has already been added. This flag is only used to
  98. /// detect bugs.
  99. bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
  100. /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
  101. bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
  102. /// Attempt to condense the value starting at \p Offset to a constant of type
  103. /// \p DesiredTy.
  104. void condense(CharUnits Offset, llvm::Type *DesiredTy);
  105. /// Produce a constant representing the entire accumulated value, ideally of
  106. /// the specified type. If \p AllowOversized, the constant might be larger
  107. /// than implied by \p DesiredTy (eg, if there is a flexible array member).
  108. /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
  109. /// even if we can't represent it as that type.
  110. llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
  111. return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size,
  112. NaturalLayout, DesiredTy, AllowOversized);
  113. }
  114. };
  115. template<typename Container, typename Range = std::initializer_list<
  116. typename Container::value_type>>
  117. static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
  118. assert(BeginOff <= EndOff && "invalid replacement range");
  119. llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
  120. }
  121. bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
  122. bool AllowOverwrite) {
  123. // Common case: appending to a layout.
  124. if (Offset >= Size) {
  125. CharUnits Align = getAlignment(C);
  126. CharUnits AlignedSize = Size.alignTo(Align);
  127. if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
  128. NaturalLayout = false;
  129. else if (AlignedSize < Offset) {
  130. Elems.push_back(getPadding(Offset - Size));
  131. Offsets.push_back(Size);
  132. }
  133. Elems.push_back(C);
  134. Offsets.push_back(Offset);
  135. Size = Offset + getSize(C);
  136. return true;
  137. }
  138. // Uncommon case: constant overlaps what we've already created.
  139. std::optional<size_t> FirstElemToReplace = splitAt(Offset);
  140. if (!FirstElemToReplace)
  141. return false;
  142. CharUnits CSize = getSize(C);
  143. std::optional<size_t> LastElemToReplace = splitAt(Offset + CSize);
  144. if (!LastElemToReplace)
  145. return false;
  146. assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
  147. "unexpectedly overwriting field");
  148. replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C});
  149. replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset});
  150. Size = std::max(Size, Offset + CSize);
  151. NaturalLayout = false;
  152. return true;
  153. }
  154. bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
  155. bool AllowOverwrite) {
  156. const ASTContext &Context = CGM.getContext();
  157. const uint64_t CharWidth = CGM.getContext().getCharWidth();
  158. // Offset of where we want the first bit to go within the bits of the
  159. // current char.
  160. unsigned OffsetWithinChar = OffsetInBits % CharWidth;
  161. // We split bit-fields up into individual bytes. Walk over the bytes and
  162. // update them.
  163. for (CharUnits OffsetInChars =
  164. Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
  165. /**/; ++OffsetInChars) {
  166. // Number of bits we want to fill in this char.
  167. unsigned WantedBits =
  168. std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar);
  169. // Get a char containing the bits we want in the right places. The other
  170. // bits have unspecified values.
  171. llvm::APInt BitsThisChar = Bits;
  172. if (BitsThisChar.getBitWidth() < CharWidth)
  173. BitsThisChar = BitsThisChar.zext(CharWidth);
  174. if (CGM.getDataLayout().isBigEndian()) {
  175. // Figure out how much to shift by. We may need to left-shift if we have
  176. // less than one byte of Bits left.
  177. int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
  178. if (Shift > 0)
  179. BitsThisChar.lshrInPlace(Shift);
  180. else if (Shift < 0)
  181. BitsThisChar = BitsThisChar.shl(-Shift);
  182. } else {
  183. BitsThisChar = BitsThisChar.shl(OffsetWithinChar);
  184. }
  185. if (BitsThisChar.getBitWidth() > CharWidth)
  186. BitsThisChar = BitsThisChar.trunc(CharWidth);
  187. if (WantedBits == CharWidth) {
  188. // Got a full byte: just add it directly.
  189. add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
  190. OffsetInChars, AllowOverwrite);
  191. } else {
  192. // Partial byte: update the existing integer if there is one. If we
  193. // can't split out a 1-CharUnit range to update, then we can't add
  194. // these bits and fail the entire constant emission.
  195. std::optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars);
  196. if (!FirstElemToUpdate)
  197. return false;
  198. std::optional<size_t> LastElemToUpdate =
  199. splitAt(OffsetInChars + CharUnits::One());
  200. if (!LastElemToUpdate)
  201. return false;
  202. assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
  203. "should have at most one element covering one byte");
  204. // Figure out which bits we want and discard the rest.
  205. llvm::APInt UpdateMask(CharWidth, 0);
  206. if (CGM.getDataLayout().isBigEndian())
  207. UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits,
  208. CharWidth - OffsetWithinChar);
  209. else
  210. UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits);
  211. BitsThisChar &= UpdateMask;
  212. if (*FirstElemToUpdate == *LastElemToUpdate ||
  213. Elems[*FirstElemToUpdate]->isNullValue() ||
  214. isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) {
  215. // All existing bits are either zero or undef.
  216. add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar),
  217. OffsetInChars, /*AllowOverwrite*/ true);
  218. } else {
  219. llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
  220. // In order to perform a partial update, we need the existing bitwise
  221. // value, which we can only extract for a constant int.
  222. auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate);
  223. if (!CI)
  224. return false;
  225. // Because this is a 1-CharUnit range, the constant occupying it must
  226. // be exactly one CharUnit wide.
  227. assert(CI->getBitWidth() == CharWidth && "splitAt failed");
  228. assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
  229. "unexpectedly overwriting bitfield");
  230. BitsThisChar |= (CI->getValue() & ~UpdateMask);
  231. ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar);
  232. }
  233. }
  234. // Stop if we've added all the bits.
  235. if (WantedBits == Bits.getBitWidth())
  236. break;
  237. // Remove the consumed bits from Bits.
  238. if (!CGM.getDataLayout().isBigEndian())
  239. Bits.lshrInPlace(WantedBits);
  240. Bits = Bits.trunc(Bits.getBitWidth() - WantedBits);
  241. // The remanining bits go at the start of the following bytes.
  242. OffsetWithinChar = 0;
  243. }
  244. return true;
  245. }
  246. /// Returns a position within Elems and Offsets such that all elements
  247. /// before the returned index end before Pos and all elements at or after
  248. /// the returned index begin at or after Pos. Splits elements as necessary
  249. /// to ensure this. Returns std::nullopt if we find something we can't split.
  250. std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
  251. if (Pos >= Size)
  252. return Offsets.size();
  253. while (true) {
  254. auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
  255. if (FirstAfterPos == Offsets.begin())
  256. return 0;
  257. // If we already have an element starting at Pos, we're done.
  258. size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
  259. if (Offsets[LastAtOrBeforePosIndex] == Pos)
  260. return LastAtOrBeforePosIndex;
  261. // We found an element starting before Pos. Check for overlap.
  262. if (Offsets[LastAtOrBeforePosIndex] +
  263. getSize(Elems[LastAtOrBeforePosIndex]) <= Pos)
  264. return LastAtOrBeforePosIndex + 1;
  265. // Try to decompose it into smaller constants.
  266. if (!split(LastAtOrBeforePosIndex, Pos))
  267. return std::nullopt;
  268. }
  269. }
  270. /// Split the constant at index Index, if possible. Return true if we did.
  271. /// Hint indicates the location at which we'd like to split, but may be
  272. /// ignored.
  273. bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
  274. NaturalLayout = false;
  275. llvm::Constant *C = Elems[Index];
  276. CharUnits Offset = Offsets[Index];
  277. if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) {
  278. // Expand the sequence into its contained elements.
  279. // FIXME: This assumes vector elements are byte-sized.
  280. replace(Elems, Index, Index + 1,
  281. llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
  282. [&](unsigned Op) { return CA->getOperand(Op); }));
  283. if (isa<llvm::ArrayType>(CA->getType()) ||
  284. isa<llvm::VectorType>(CA->getType())) {
  285. // Array or vector.
  286. llvm::Type *ElemTy =
  287. llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0);
  288. CharUnits ElemSize = getSize(ElemTy);
  289. replace(
  290. Offsets, Index, Index + 1,
  291. llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
  292. [&](unsigned Op) { return Offset + Op * ElemSize; }));
  293. } else {
  294. // Must be a struct.
  295. auto *ST = cast<llvm::StructType>(CA->getType());
  296. const llvm::StructLayout *Layout =
  297. CGM.getDataLayout().getStructLayout(ST);
  298. replace(Offsets, Index, Index + 1,
  299. llvm::map_range(
  300. llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) {
  301. return Offset + CharUnits::fromQuantity(
  302. Layout->getElementOffset(Op));
  303. }));
  304. }
  305. return true;
  306. }
  307. if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) {
  308. // Expand the sequence into its contained elements.
  309. // FIXME: This assumes vector elements are byte-sized.
  310. // FIXME: If possible, split into two ConstantDataSequentials at Hint.
  311. CharUnits ElemSize = getSize(CDS->getElementType());
  312. replace(Elems, Index, Index + 1,
  313. llvm::map_range(llvm::seq(0u, CDS->getNumElements()),
  314. [&](unsigned Elem) {
  315. return CDS->getElementAsConstant(Elem);
  316. }));
  317. replace(Offsets, Index, Index + 1,
  318. llvm::map_range(
  319. llvm::seq(0u, CDS->getNumElements()),
  320. [&](unsigned Elem) { return Offset + Elem * ElemSize; }));
  321. return true;
  322. }
  323. if (isa<llvm::ConstantAggregateZero>(C)) {
  324. // Split into two zeros at the hinted offset.
  325. CharUnits ElemSize = getSize(C);
  326. assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
  327. replace(Elems, Index, Index + 1,
  328. {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)});
  329. replace(Offsets, Index, Index + 1, {Offset, Hint});
  330. return true;
  331. }
  332. if (isa<llvm::UndefValue>(C)) {
  333. // Drop undef; it doesn't contribute to the final layout.
  334. replace(Elems, Index, Index + 1, {});
  335. replace(Offsets, Index, Index + 1, {});
  336. return true;
  337. }
  338. // FIXME: We could split a ConstantInt if the need ever arose.
  339. // We don't need to do this to handle bit-fields because we always eagerly
  340. // split them into 1-byte chunks.
  341. return false;
  342. }
  343. static llvm::Constant *
  344. EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
  345. llvm::Type *CommonElementType, unsigned ArrayBound,
  346. SmallVectorImpl<llvm::Constant *> &Elements,
  347. llvm::Constant *Filler);
  348. llvm::Constant *ConstantAggregateBuilder::buildFrom(
  349. CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
  350. ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
  351. bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
  352. ConstantAggregateBuilderUtils Utils(CGM);
  353. if (Elems.empty())
  354. return llvm::UndefValue::get(DesiredTy);
  355. auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
  356. // If we want an array type, see if all the elements are the same type and
  357. // appropriately spaced.
  358. if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) {
  359. assert(!AllowOversized && "oversized array emission not supported");
  360. bool CanEmitArray = true;
  361. llvm::Type *CommonType = Elems[0]->getType();
  362. llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType);
  363. CharUnits ElemSize = Utils.getSize(ATy->getElementType());
  364. SmallVector<llvm::Constant*, 32> ArrayElements;
  365. for (size_t I = 0; I != Elems.size(); ++I) {
  366. // Skip zeroes; we'll use a zero value as our array filler.
  367. if (Elems[I]->isNullValue())
  368. continue;
  369. // All remaining elements must be the same type.
  370. if (Elems[I]->getType() != CommonType ||
  371. Offset(I) % ElemSize != 0) {
  372. CanEmitArray = false;
  373. break;
  374. }
  375. ArrayElements.resize(Offset(I) / ElemSize + 1, Filler);
  376. ArrayElements.back() = Elems[I];
  377. }
  378. if (CanEmitArray) {
  379. return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(),
  380. ArrayElements, Filler);
  381. }
  382. // Can't emit as an array, carry on to emit as a struct.
  383. }
  384. // The size of the constant we plan to generate. This is usually just
  385. // the size of the initialized type, but in AllowOversized mode (i.e.
  386. // flexible array init), it can be larger.
  387. CharUnits DesiredSize = Utils.getSize(DesiredTy);
  388. if (Size > DesiredSize) {
  389. assert(AllowOversized && "Elems are oversized");
  390. DesiredSize = Size;
  391. }
  392. // The natural alignment of an unpacked LLVM struct with the given elements.
  393. CharUnits Align = CharUnits::One();
  394. for (llvm::Constant *C : Elems)
  395. Align = std::max(Align, Utils.getAlignment(C));
  396. // The natural size of an unpacked LLVM struct with the given elements.
  397. CharUnits AlignedSize = Size.alignTo(Align);
  398. bool Packed = false;
  399. ArrayRef<llvm::Constant*> UnpackedElems = Elems;
  400. llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
  401. if (DesiredSize < AlignedSize || DesiredSize.alignTo(Align) != DesiredSize) {
  402. // The natural layout would be too big; force use of a packed layout.
  403. NaturalLayout = false;
  404. Packed = true;
  405. } else if (DesiredSize > AlignedSize) {
  406. // The natural layout would be too small. Add padding to fix it. (This
  407. // is ignored if we choose a packed layout.)
  408. UnpackedElemStorage.assign(Elems.begin(), Elems.end());
  409. UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
  410. UnpackedElems = UnpackedElemStorage;
  411. }
  412. // If we don't have a natural layout, insert padding as necessary.
  413. // As we go, double-check to see if we can actually just emit Elems
  414. // as a non-packed struct and do so opportunistically if possible.
  415. llvm::SmallVector<llvm::Constant*, 32> PackedElems;
  416. if (!NaturalLayout) {
  417. CharUnits SizeSoFar = CharUnits::Zero();
  418. for (size_t I = 0; I != Elems.size(); ++I) {
  419. CharUnits Align = Utils.getAlignment(Elems[I]);
  420. CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
  421. CharUnits DesiredOffset = Offset(I);
  422. assert(DesiredOffset >= SizeSoFar && "elements out of order");
  423. if (DesiredOffset != NaturalOffset)
  424. Packed = true;
  425. if (DesiredOffset != SizeSoFar)
  426. PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
  427. PackedElems.push_back(Elems[I]);
  428. SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
  429. }
  430. // If we're using the packed layout, pad it out to the desired size if
  431. // necessary.
  432. if (Packed) {
  433. assert(SizeSoFar <= DesiredSize &&
  434. "requested size is too small for contents");
  435. if (SizeSoFar < DesiredSize)
  436. PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
  437. }
  438. }
  439. llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
  440. CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
  441. // Pick the type to use. If the type is layout identical to the desired
  442. // type then use it, otherwise use whatever the builder produced for us.
  443. if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
  444. if (DesiredSTy->isLayoutIdentical(STy))
  445. STy = DesiredSTy;
  446. }
  447. return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
  448. }
  449. void ConstantAggregateBuilder::condense(CharUnits Offset,
  450. llvm::Type *DesiredTy) {
  451. CharUnits Size = getSize(DesiredTy);
  452. std::optional<size_t> FirstElemToReplace = splitAt(Offset);
  453. if (!FirstElemToReplace)
  454. return;
  455. size_t First = *FirstElemToReplace;
  456. std::optional<size_t> LastElemToReplace = splitAt(Offset + Size);
  457. if (!LastElemToReplace)
  458. return;
  459. size_t Last = *LastElemToReplace;
  460. size_t Length = Last - First;
  461. if (Length == 0)
  462. return;
  463. if (Length == 1 && Offsets[First] == Offset &&
  464. getSize(Elems[First]) == Size) {
  465. // Re-wrap single element structs if necessary. Otherwise, leave any single
  466. // element constant of the right size alone even if it has the wrong type.
  467. auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
  468. if (STy && STy->getNumElements() == 1 &&
  469. STy->getElementType(0) == Elems[First]->getType())
  470. Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
  471. return;
  472. }
  473. llvm::Constant *Replacement = buildFrom(
  474. CGM, ArrayRef(Elems).slice(First, Length),
  475. ArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
  476. /*known to have natural layout=*/false, DesiredTy, false);
  477. replace(Elems, First, Last, {Replacement});
  478. replace(Offsets, First, Last, {Offset});
  479. }
  480. //===----------------------------------------------------------------------===//
  481. // ConstStructBuilder
  482. //===----------------------------------------------------------------------===//
  483. class ConstStructBuilder {
  484. CodeGenModule &CGM;
  485. ConstantEmitter &Emitter;
  486. ConstantAggregateBuilder &Builder;
  487. CharUnits StartOffset;
  488. public:
  489. static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
  490. InitListExpr *ILE, QualType StructTy);
  491. static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
  492. const APValue &Value, QualType ValTy);
  493. static bool UpdateStruct(ConstantEmitter &Emitter,
  494. ConstantAggregateBuilder &Const, CharUnits Offset,
  495. InitListExpr *Updater);
  496. private:
  497. ConstStructBuilder(ConstantEmitter &Emitter,
  498. ConstantAggregateBuilder &Builder, CharUnits StartOffset)
  499. : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
  500. StartOffset(StartOffset) {}
  501. bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
  502. llvm::Constant *InitExpr, bool AllowOverwrite = false);
  503. bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
  504. bool AllowOverwrite = false);
  505. bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
  506. llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
  507. bool Build(InitListExpr *ILE, bool AllowOverwrite);
  508. bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
  509. const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
  510. llvm::Constant *Finalize(QualType Ty);
  511. };
  512. bool ConstStructBuilder::AppendField(
  513. const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
  514. bool AllowOverwrite) {
  515. const ASTContext &Context = CGM.getContext();
  516. CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
  517. return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
  518. }
  519. bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
  520. llvm::Constant *InitCst,
  521. bool AllowOverwrite) {
  522. return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
  523. }
  524. bool ConstStructBuilder::AppendBitField(
  525. const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
  526. bool AllowOverwrite) {
  527. const CGRecordLayout &RL =
  528. CGM.getTypes().getCGRecordLayout(Field->getParent());
  529. const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
  530. llvm::APInt FieldValue = CI->getValue();
  531. // Promote the size of FieldValue if necessary
  532. // FIXME: This should never occur, but currently it can because initializer
  533. // constants are cast to bool, and because clang is not enforcing bitfield
  534. // width limits.
  535. if (Info.Size > FieldValue.getBitWidth())
  536. FieldValue = FieldValue.zext(Info.Size);
  537. // Truncate the size of FieldValue to the bit field size.
  538. if (Info.Size < FieldValue.getBitWidth())
  539. FieldValue = FieldValue.trunc(Info.Size);
  540. return Builder.addBits(FieldValue,
  541. CGM.getContext().toBits(StartOffset) + FieldOffset,
  542. AllowOverwrite);
  543. }
  544. static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
  545. ConstantAggregateBuilder &Const,
  546. CharUnits Offset, QualType Type,
  547. InitListExpr *Updater) {
  548. if (Type->isRecordType())
  549. return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
  550. auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
  551. if (!CAT)
  552. return false;
  553. QualType ElemType = CAT->getElementType();
  554. CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
  555. llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
  556. llvm::Constant *FillC = nullptr;
  557. if (Expr *Filler = Updater->getArrayFiller()) {
  558. if (!isa<NoInitExpr>(Filler)) {
  559. FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
  560. if (!FillC)
  561. return false;
  562. }
  563. }
  564. unsigned NumElementsToUpdate =
  565. FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits();
  566. for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
  567. Expr *Init = nullptr;
  568. if (I < Updater->getNumInits())
  569. Init = Updater->getInit(I);
  570. if (!Init && FillC) {
  571. if (!Const.add(FillC, Offset, true))
  572. return false;
  573. } else if (!Init || isa<NoInitExpr>(Init)) {
  574. continue;
  575. } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
  576. if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
  577. ChildILE))
  578. return false;
  579. // Attempt to reduce the array element to a single constant if necessary.
  580. Const.condense(Offset, ElemTy);
  581. } else {
  582. llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
  583. if (!Const.add(Val, Offset, true))
  584. return false;
  585. }
  586. }
  587. return true;
  588. }
  589. bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
  590. RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
  591. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  592. unsigned FieldNo = -1;
  593. unsigned ElementNo = 0;
  594. // Bail out if we have base classes. We could support these, but they only
  595. // arise in C++1z where we will have already constant folded most interesting
  596. // cases. FIXME: There are still a few more cases we can handle this way.
  597. if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
  598. if (CXXRD->getNumBases())
  599. return false;
  600. for (FieldDecl *Field : RD->fields()) {
  601. ++FieldNo;
  602. // If this is a union, skip all the fields that aren't being initialized.
  603. if (RD->isUnion() &&
  604. !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
  605. continue;
  606. // Don't emit anonymous bitfields.
  607. if (Field->isUnnamedBitfield())
  608. continue;
  609. // Get the initializer. A struct can include fields without initializers,
  610. // we just use explicit null values for them.
  611. Expr *Init = nullptr;
  612. if (ElementNo < ILE->getNumInits())
  613. Init = ILE->getInit(ElementNo++);
  614. if (Init && isa<NoInitExpr>(Init))
  615. continue;
  616. // Zero-sized fields are not emitted, but their initializers may still
  617. // prevent emission of this struct as a constant.
  618. if (Field->isZeroSize(CGM.getContext())) {
  619. if (Init->HasSideEffects(CGM.getContext()))
  620. return false;
  621. continue;
  622. }
  623. // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
  624. // represents additional overwriting of our current constant value, and not
  625. // a new constant to emit independently.
  626. if (AllowOverwrite &&
  627. (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
  628. if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
  629. CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
  630. Layout.getFieldOffset(FieldNo));
  631. if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
  632. Field->getType(), SubILE))
  633. return false;
  634. // If we split apart the field's value, try to collapse it down to a
  635. // single value now.
  636. Builder.condense(StartOffset + Offset,
  637. CGM.getTypes().ConvertTypeForMem(Field->getType()));
  638. continue;
  639. }
  640. }
  641. llvm::Constant *EltInit =
  642. Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
  643. : Emitter.emitNullForMemory(Field->getType());
  644. if (!EltInit)
  645. return false;
  646. if (!Field->isBitField()) {
  647. // Handle non-bitfield members.
  648. if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
  649. AllowOverwrite))
  650. return false;
  651. // After emitting a non-empty field with [[no_unique_address]], we may
  652. // need to overwrite its tail padding.
  653. if (Field->hasAttr<NoUniqueAddressAttr>())
  654. AllowOverwrite = true;
  655. } else {
  656. // Otherwise we have a bitfield.
  657. if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
  658. if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
  659. AllowOverwrite))
  660. return false;
  661. } else {
  662. // We are trying to initialize a bitfield with a non-trivial constant,
  663. // this must require run-time code.
  664. return false;
  665. }
  666. }
  667. }
  668. return true;
  669. }
  670. namespace {
  671. struct BaseInfo {
  672. BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
  673. : Decl(Decl), Offset(Offset), Index(Index) {
  674. }
  675. const CXXRecordDecl *Decl;
  676. CharUnits Offset;
  677. unsigned Index;
  678. bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
  679. };
  680. }
  681. bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
  682. bool IsPrimaryBase,
  683. const CXXRecordDecl *VTableClass,
  684. CharUnits Offset) {
  685. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  686. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  687. // Add a vtable pointer, if we need one and it hasn't already been added.
  688. if (Layout.hasOwnVFPtr()) {
  689. llvm::Constant *VTableAddressPoint =
  690. CGM.getCXXABI().getVTableAddressPointForConstExpr(
  691. BaseSubobject(CD, Offset), VTableClass);
  692. if (!AppendBytes(Offset, VTableAddressPoint))
  693. return false;
  694. }
  695. // Accumulate and sort bases, in order to visit them in address order, which
  696. // may not be the same as declaration order.
  697. SmallVector<BaseInfo, 8> Bases;
  698. Bases.reserve(CD->getNumBases());
  699. unsigned BaseNo = 0;
  700. for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
  701. BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
  702. assert(!Base->isVirtual() && "should not have virtual bases here");
  703. const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
  704. CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
  705. Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
  706. }
  707. llvm::stable_sort(Bases);
  708. for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
  709. BaseInfo &Base = Bases[I];
  710. bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
  711. Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
  712. VTableClass, Offset + Base.Offset);
  713. }
  714. }
  715. unsigned FieldNo = 0;
  716. uint64_t OffsetBits = CGM.getContext().toBits(Offset);
  717. bool AllowOverwrite = false;
  718. for (RecordDecl::field_iterator Field = RD->field_begin(),
  719. FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
  720. // If this is a union, skip all the fields that aren't being initialized.
  721. if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
  722. continue;
  723. // Don't emit anonymous bitfields or zero-sized fields.
  724. if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
  725. continue;
  726. // Emit the value of the initializer.
  727. const APValue &FieldValue =
  728. RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
  729. llvm::Constant *EltInit =
  730. Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
  731. if (!EltInit)
  732. return false;
  733. if (!Field->isBitField()) {
  734. // Handle non-bitfield members.
  735. if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
  736. EltInit, AllowOverwrite))
  737. return false;
  738. // After emitting a non-empty field with [[no_unique_address]], we may
  739. // need to overwrite its tail padding.
  740. if (Field->hasAttr<NoUniqueAddressAttr>())
  741. AllowOverwrite = true;
  742. } else {
  743. // Otherwise we have a bitfield.
  744. if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
  745. cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
  746. return false;
  747. }
  748. }
  749. return true;
  750. }
  751. llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
  752. Type = Type.getNonReferenceType();
  753. RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
  754. llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
  755. return Builder.build(ValTy, RD->hasFlexibleArrayMember());
  756. }
  757. llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
  758. InitListExpr *ILE,
  759. QualType ValTy) {
  760. ConstantAggregateBuilder Const(Emitter.CGM);
  761. ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
  762. if (!Builder.Build(ILE, /*AllowOverwrite*/false))
  763. return nullptr;
  764. return Builder.Finalize(ValTy);
  765. }
  766. llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
  767. const APValue &Val,
  768. QualType ValTy) {
  769. ConstantAggregateBuilder Const(Emitter.CGM);
  770. ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
  771. const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
  772. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  773. if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
  774. return nullptr;
  775. return Builder.Finalize(ValTy);
  776. }
  777. bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
  778. ConstantAggregateBuilder &Const,
  779. CharUnits Offset, InitListExpr *Updater) {
  780. return ConstStructBuilder(Emitter, Const, Offset)
  781. .Build(Updater, /*AllowOverwrite*/ true);
  782. }
  783. //===----------------------------------------------------------------------===//
  784. // ConstExprEmitter
  785. //===----------------------------------------------------------------------===//
  786. static ConstantAddress
  787. tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
  788. const CompoundLiteralExpr *E) {
  789. CodeGenModule &CGM = emitter.CGM;
  790. CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
  791. if (llvm::GlobalVariable *Addr =
  792. CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
  793. return ConstantAddress(Addr, Addr->getValueType(), Align);
  794. LangAS addressSpace = E->getType().getAddressSpace();
  795. llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
  796. addressSpace, E->getType());
  797. if (!C) {
  798. assert(!E->isFileScope() &&
  799. "file-scope compound literal did not have constant initializer!");
  800. return ConstantAddress::invalid();
  801. }
  802. auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
  803. CGM.isTypeConstant(E->getType(), true),
  804. llvm::GlobalValue::InternalLinkage,
  805. C, ".compoundliteral", nullptr,
  806. llvm::GlobalVariable::NotThreadLocal,
  807. CGM.getContext().getTargetAddressSpace(addressSpace));
  808. emitter.finalize(GV);
  809. GV->setAlignment(Align.getAsAlign());
  810. CGM.setAddrOfConstantCompoundLiteral(E, GV);
  811. return ConstantAddress(GV, GV->getValueType(), Align);
  812. }
  813. static llvm::Constant *
  814. EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
  815. llvm::Type *CommonElementType, unsigned ArrayBound,
  816. SmallVectorImpl<llvm::Constant *> &Elements,
  817. llvm::Constant *Filler) {
  818. // Figure out how long the initial prefix of non-zero elements is.
  819. unsigned NonzeroLength = ArrayBound;
  820. if (Elements.size() < NonzeroLength && Filler->isNullValue())
  821. NonzeroLength = Elements.size();
  822. if (NonzeroLength == Elements.size()) {
  823. while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
  824. --NonzeroLength;
  825. }
  826. if (NonzeroLength == 0)
  827. return llvm::ConstantAggregateZero::get(DesiredType);
  828. // Add a zeroinitializer array filler if we have lots of trailing zeroes.
  829. unsigned TrailingZeroes = ArrayBound - NonzeroLength;
  830. if (TrailingZeroes >= 8) {
  831. assert(Elements.size() >= NonzeroLength &&
  832. "missing initializer for non-zero element");
  833. // If all the elements had the same type up to the trailing zeroes, emit a
  834. // struct of two arrays (the nonzero data and the zeroinitializer).
  835. if (CommonElementType && NonzeroLength >= 8) {
  836. llvm::Constant *Initial = llvm::ConstantArray::get(
  837. llvm::ArrayType::get(CommonElementType, NonzeroLength),
  838. ArrayRef(Elements).take_front(NonzeroLength));
  839. Elements.resize(2);
  840. Elements[0] = Initial;
  841. } else {
  842. Elements.resize(NonzeroLength + 1);
  843. }
  844. auto *FillerType =
  845. CommonElementType ? CommonElementType : DesiredType->getElementType();
  846. FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
  847. Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
  848. CommonElementType = nullptr;
  849. } else if (Elements.size() != ArrayBound) {
  850. // Otherwise pad to the right size with the filler if necessary.
  851. Elements.resize(ArrayBound, Filler);
  852. if (Filler->getType() != CommonElementType)
  853. CommonElementType = nullptr;
  854. }
  855. // If all elements have the same type, just emit an array constant.
  856. if (CommonElementType)
  857. return llvm::ConstantArray::get(
  858. llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
  859. // We have mixed types. Use a packed struct.
  860. llvm::SmallVector<llvm::Type *, 16> Types;
  861. Types.reserve(Elements.size());
  862. for (llvm::Constant *Elt : Elements)
  863. Types.push_back(Elt->getType());
  864. llvm::StructType *SType =
  865. llvm::StructType::get(CGM.getLLVMContext(), Types, true);
  866. return llvm::ConstantStruct::get(SType, Elements);
  867. }
  868. // This class only needs to handle arrays, structs and unions. Outside C++11
  869. // mode, we don't currently constant fold those types. All other types are
  870. // handled by constant folding.
  871. //
  872. // Constant folding is currently missing support for a few features supported
  873. // here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
  874. class ConstExprEmitter :
  875. public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
  876. CodeGenModule &CGM;
  877. ConstantEmitter &Emitter;
  878. llvm::LLVMContext &VMContext;
  879. public:
  880. ConstExprEmitter(ConstantEmitter &emitter)
  881. : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
  882. }
  883. //===--------------------------------------------------------------------===//
  884. // Visitor Methods
  885. //===--------------------------------------------------------------------===//
  886. llvm::Constant *VisitStmt(Stmt *S, QualType T) {
  887. return nullptr;
  888. }
  889. llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
  890. if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE))
  891. return Result;
  892. return Visit(CE->getSubExpr(), T);
  893. }
  894. llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
  895. return Visit(PE->getSubExpr(), T);
  896. }
  897. llvm::Constant *
  898. VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
  899. QualType T) {
  900. return Visit(PE->getReplacement(), T);
  901. }
  902. llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
  903. QualType T) {
  904. return Visit(GE->getResultExpr(), T);
  905. }
  906. llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
  907. return Visit(CE->getChosenSubExpr(), T);
  908. }
  909. llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
  910. return Visit(E->getInitializer(), T);
  911. }
  912. llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
  913. if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
  914. CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
  915. Expr *subExpr = E->getSubExpr();
  916. switch (E->getCastKind()) {
  917. case CK_ToUnion: {
  918. // GCC cast to union extension
  919. assert(E->getType()->isUnionType() &&
  920. "Destination type is not union type!");
  921. auto field = E->getTargetUnionField();
  922. auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
  923. if (!C) return nullptr;
  924. auto destTy = ConvertType(destType);
  925. if (C->getType() == destTy) return C;
  926. // Build a struct with the union sub-element as the first member,
  927. // and padded to the appropriate size.
  928. SmallVector<llvm::Constant*, 2> Elts;
  929. SmallVector<llvm::Type*, 2> Types;
  930. Elts.push_back(C);
  931. Types.push_back(C->getType());
  932. unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
  933. unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
  934. assert(CurSize <= TotalSize && "Union size mismatch!");
  935. if (unsigned NumPadBytes = TotalSize - CurSize) {
  936. llvm::Type *Ty = CGM.CharTy;
  937. if (NumPadBytes > 1)
  938. Ty = llvm::ArrayType::get(Ty, NumPadBytes);
  939. Elts.push_back(llvm::UndefValue::get(Ty));
  940. Types.push_back(Ty);
  941. }
  942. llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
  943. return llvm::ConstantStruct::get(STy, Elts);
  944. }
  945. case CK_AddressSpaceConversion: {
  946. auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
  947. if (!C) return nullptr;
  948. LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
  949. LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
  950. llvm::Type *destTy = ConvertType(E->getType());
  951. return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
  952. destAS, destTy);
  953. }
  954. case CK_LValueToRValue: {
  955. // We don't really support doing lvalue-to-rvalue conversions here; any
  956. // interesting conversions should be done in Evaluate(). But as a
  957. // special case, allow compound literals to support the gcc extension
  958. // allowing "struct x {int x;} x = (struct x) {};".
  959. if (auto *E = dyn_cast<CompoundLiteralExpr>(subExpr->IgnoreParens()))
  960. return Visit(E->getInitializer(), destType);
  961. return nullptr;
  962. }
  963. case CK_AtomicToNonAtomic:
  964. case CK_NonAtomicToAtomic:
  965. case CK_NoOp:
  966. case CK_ConstructorConversion:
  967. return Visit(subExpr, destType);
  968. case CK_IntToOCLSampler:
  969. llvm_unreachable("global sampler variables are not generated");
  970. case CK_Dependent: llvm_unreachable("saw dependent cast!");
  971. case CK_BuiltinFnToFnPtr:
  972. llvm_unreachable("builtin functions are handled elsewhere");
  973. case CK_ReinterpretMemberPointer:
  974. case CK_DerivedToBaseMemberPointer:
  975. case CK_BaseToDerivedMemberPointer: {
  976. auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
  977. if (!C) return nullptr;
  978. return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
  979. }
  980. // These will never be supported.
  981. case CK_ObjCObjectLValueCast:
  982. case CK_ARCProduceObject:
  983. case CK_ARCConsumeObject:
  984. case CK_ARCReclaimReturnedObject:
  985. case CK_ARCExtendBlockObject:
  986. case CK_CopyAndAutoreleaseBlockObject:
  987. return nullptr;
  988. // These don't need to be handled here because Evaluate knows how to
  989. // evaluate them in the cases where they can be folded.
  990. case CK_BitCast:
  991. case CK_ToVoid:
  992. case CK_Dynamic:
  993. case CK_LValueBitCast:
  994. case CK_LValueToRValueBitCast:
  995. case CK_NullToMemberPointer:
  996. case CK_UserDefinedConversion:
  997. case CK_CPointerToObjCPointerCast:
  998. case CK_BlockPointerToObjCPointerCast:
  999. case CK_AnyPointerToBlockPointerCast:
  1000. case CK_ArrayToPointerDecay:
  1001. case CK_FunctionToPointerDecay:
  1002. case CK_BaseToDerived:
  1003. case CK_DerivedToBase:
  1004. case CK_UncheckedDerivedToBase:
  1005. case CK_MemberPointerToBoolean:
  1006. case CK_VectorSplat:
  1007. case CK_FloatingRealToComplex:
  1008. case CK_FloatingComplexToReal:
  1009. case CK_FloatingComplexToBoolean:
  1010. case CK_FloatingComplexCast:
  1011. case CK_FloatingComplexToIntegralComplex:
  1012. case CK_IntegralRealToComplex:
  1013. case CK_IntegralComplexToReal:
  1014. case CK_IntegralComplexToBoolean:
  1015. case CK_IntegralComplexCast:
  1016. case CK_IntegralComplexToFloatingComplex:
  1017. case CK_PointerToIntegral:
  1018. case CK_PointerToBoolean:
  1019. case CK_NullToPointer:
  1020. case CK_IntegralCast:
  1021. case CK_BooleanToSignedIntegral:
  1022. case CK_IntegralToPointer:
  1023. case CK_IntegralToBoolean:
  1024. case CK_IntegralToFloating:
  1025. case CK_FloatingToIntegral:
  1026. case CK_FloatingToBoolean:
  1027. case CK_FloatingCast:
  1028. case CK_FloatingToFixedPoint:
  1029. case CK_FixedPointToFloating:
  1030. case CK_FixedPointCast:
  1031. case CK_FixedPointToBoolean:
  1032. case CK_FixedPointToIntegral:
  1033. case CK_IntegralToFixedPoint:
  1034. case CK_ZeroToOCLOpaqueType:
  1035. case CK_MatrixCast:
  1036. return nullptr;
  1037. }
  1038. llvm_unreachable("Invalid CastKind");
  1039. }
  1040. llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
  1041. // No need for a DefaultInitExprScope: we don't handle 'this' in a
  1042. // constant expression.
  1043. return Visit(DIE->getExpr(), T);
  1044. }
  1045. llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
  1046. return Visit(E->getSubExpr(), T);
  1047. }
  1048. llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
  1049. QualType T) {
  1050. return Visit(E->getSubExpr(), T);
  1051. }
  1052. llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
  1053. auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
  1054. assert(CAT && "can't emit array init for non-constant-bound array");
  1055. unsigned NumInitElements = ILE->getNumInits();
  1056. unsigned NumElements = CAT->getSize().getZExtValue();
  1057. // Initialising an array requires us to automatically
  1058. // initialise any elements that have not been initialised explicitly
  1059. unsigned NumInitableElts = std::min(NumInitElements, NumElements);
  1060. QualType EltType = CAT->getElementType();
  1061. // Initialize remaining array elements.
  1062. llvm::Constant *fillC = nullptr;
  1063. if (Expr *filler = ILE->getArrayFiller()) {
  1064. fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
  1065. if (!fillC)
  1066. return nullptr;
  1067. }
  1068. // Copy initializer elements.
  1069. SmallVector<llvm::Constant*, 16> Elts;
  1070. if (fillC && fillC->isNullValue())
  1071. Elts.reserve(NumInitableElts + 1);
  1072. else
  1073. Elts.reserve(NumElements);
  1074. llvm::Type *CommonElementType = nullptr;
  1075. for (unsigned i = 0; i < NumInitableElts; ++i) {
  1076. Expr *Init = ILE->getInit(i);
  1077. llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
  1078. if (!C)
  1079. return nullptr;
  1080. if (i == 0)
  1081. CommonElementType = C->getType();
  1082. else if (C->getType() != CommonElementType)
  1083. CommonElementType = nullptr;
  1084. Elts.push_back(C);
  1085. }
  1086. llvm::ArrayType *Desired =
  1087. cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
  1088. return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
  1089. fillC);
  1090. }
  1091. llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
  1092. return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
  1093. }
  1094. llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
  1095. QualType T) {
  1096. return CGM.EmitNullConstant(T);
  1097. }
  1098. llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
  1099. if (ILE->isTransparent())
  1100. return Visit(ILE->getInit(0), T);
  1101. if (ILE->getType()->isArrayType())
  1102. return EmitArrayInitialization(ILE, T);
  1103. if (ILE->getType()->isRecordType())
  1104. return EmitRecordInitialization(ILE, T);
  1105. return nullptr;
  1106. }
  1107. llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
  1108. QualType destType) {
  1109. auto C = Visit(E->getBase(), destType);
  1110. if (!C)
  1111. return nullptr;
  1112. ConstantAggregateBuilder Const(CGM);
  1113. Const.add(C, CharUnits::Zero(), false);
  1114. if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
  1115. E->getUpdater()))
  1116. return nullptr;
  1117. llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
  1118. bool HasFlexibleArray = false;
  1119. if (auto *RT = destType->getAs<RecordType>())
  1120. HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
  1121. return Const.build(ValTy, HasFlexibleArray);
  1122. }
  1123. llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
  1124. if (!E->getConstructor()->isTrivial())
  1125. return nullptr;
  1126. // Only default and copy/move constructors can be trivial.
  1127. if (E->getNumArgs()) {
  1128. assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
  1129. assert(E->getConstructor()->isCopyOrMoveConstructor() &&
  1130. "trivial ctor has argument but isn't a copy/move ctor");
  1131. Expr *Arg = E->getArg(0);
  1132. assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
  1133. "argument to copy ctor is of wrong type");
  1134. return Visit(Arg, Ty);
  1135. }
  1136. return CGM.EmitNullConstant(Ty);
  1137. }
  1138. llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
  1139. // This is a string literal initializing an array in an initializer.
  1140. return CGM.GetConstantArrayFromStringLiteral(E);
  1141. }
  1142. llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
  1143. // This must be an @encode initializing an array in a static initializer.
  1144. // Don't emit it as the address of the string, emit the string data itself
  1145. // as an inline array.
  1146. std::string Str;
  1147. CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  1148. const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
  1149. // Resize the string to the right size, adding zeros at the end, or
  1150. // truncating as needed.
  1151. Str.resize(CAT->getSize().getZExtValue(), '\0');
  1152. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  1153. }
  1154. llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
  1155. return Visit(E->getSubExpr(), T);
  1156. }
  1157. // Utility methods
  1158. llvm::Type *ConvertType(QualType T) {
  1159. return CGM.getTypes().ConvertType(T);
  1160. }
  1161. };
  1162. } // end anonymous namespace.
  1163. llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
  1164. AbstractState saved) {
  1165. Abstract = saved.OldValue;
  1166. assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
  1167. "created a placeholder while doing an abstract emission?");
  1168. // No validation necessary for now.
  1169. // No cleanup to do for now.
  1170. return C;
  1171. }
  1172. llvm::Constant *
  1173. ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
  1174. auto state = pushAbstract();
  1175. auto C = tryEmitPrivateForVarInit(D);
  1176. return validateAndPopAbstract(C, state);
  1177. }
  1178. llvm::Constant *
  1179. ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
  1180. auto state = pushAbstract();
  1181. auto C = tryEmitPrivate(E, destType);
  1182. return validateAndPopAbstract(C, state);
  1183. }
  1184. llvm::Constant *
  1185. ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
  1186. auto state = pushAbstract();
  1187. auto C = tryEmitPrivate(value, destType);
  1188. return validateAndPopAbstract(C, state);
  1189. }
  1190. llvm::Constant *ConstantEmitter::tryEmitConstantExpr(const ConstantExpr *CE) {
  1191. if (!CE->hasAPValueResult())
  1192. return nullptr;
  1193. QualType RetType = CE->getType();
  1194. if (CE->isGLValue())
  1195. RetType = CGM.getContext().getLValueReferenceType(RetType);
  1196. return emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), RetType);
  1197. }
  1198. llvm::Constant *
  1199. ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
  1200. auto state = pushAbstract();
  1201. auto C = tryEmitPrivate(E, destType);
  1202. C = validateAndPopAbstract(C, state);
  1203. if (!C) {
  1204. CGM.Error(E->getExprLoc(),
  1205. "internal error: could not emit constant value \"abstractly\"");
  1206. C = CGM.EmitNullConstant(destType);
  1207. }
  1208. return C;
  1209. }
  1210. llvm::Constant *
  1211. ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
  1212. QualType destType) {
  1213. auto state = pushAbstract();
  1214. auto C = tryEmitPrivate(value, destType);
  1215. C = validateAndPopAbstract(C, state);
  1216. if (!C) {
  1217. CGM.Error(loc,
  1218. "internal error: could not emit constant value \"abstractly\"");
  1219. C = CGM.EmitNullConstant(destType);
  1220. }
  1221. return C;
  1222. }
  1223. llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
  1224. initializeNonAbstract(D.getType().getAddressSpace());
  1225. return markIfFailed(tryEmitPrivateForVarInit(D));
  1226. }
  1227. llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
  1228. LangAS destAddrSpace,
  1229. QualType destType) {
  1230. initializeNonAbstract(destAddrSpace);
  1231. return markIfFailed(tryEmitPrivateForMemory(E, destType));
  1232. }
  1233. llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
  1234. LangAS destAddrSpace,
  1235. QualType destType) {
  1236. initializeNonAbstract(destAddrSpace);
  1237. auto C = tryEmitPrivateForMemory(value, destType);
  1238. assert(C && "couldn't emit constant value non-abstractly?");
  1239. return C;
  1240. }
  1241. llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
  1242. assert(!Abstract && "cannot get current address for abstract constant");
  1243. // Make an obviously ill-formed global that should blow up compilation
  1244. // if it survives.
  1245. auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
  1246. llvm::GlobalValue::PrivateLinkage,
  1247. /*init*/ nullptr,
  1248. /*name*/ "",
  1249. /*before*/ nullptr,
  1250. llvm::GlobalVariable::NotThreadLocal,
  1251. CGM.getContext().getTargetAddressSpace(DestAddressSpace));
  1252. PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
  1253. return global;
  1254. }
  1255. void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
  1256. llvm::GlobalValue *placeholder) {
  1257. assert(!PlaceholderAddresses.empty());
  1258. assert(PlaceholderAddresses.back().first == nullptr);
  1259. assert(PlaceholderAddresses.back().second == placeholder);
  1260. PlaceholderAddresses.back().first = signal;
  1261. }
  1262. namespace {
  1263. struct ReplacePlaceholders {
  1264. CodeGenModule &CGM;
  1265. /// The base address of the global.
  1266. llvm::Constant *Base;
  1267. llvm::Type *BaseValueTy = nullptr;
  1268. /// The placeholder addresses that were registered during emission.
  1269. llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
  1270. /// The locations of the placeholder signals.
  1271. llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
  1272. /// The current index stack. We use a simple unsigned stack because
  1273. /// we assume that placeholders will be relatively sparse in the
  1274. /// initializer, but we cache the index values we find just in case.
  1275. llvm::SmallVector<unsigned, 8> Indices;
  1276. llvm::SmallVector<llvm::Constant*, 8> IndexValues;
  1277. ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
  1278. ArrayRef<std::pair<llvm::Constant*,
  1279. llvm::GlobalVariable*>> addresses)
  1280. : CGM(CGM), Base(base),
  1281. PlaceholderAddresses(addresses.begin(), addresses.end()) {
  1282. }
  1283. void replaceInInitializer(llvm::Constant *init) {
  1284. // Remember the type of the top-most initializer.
  1285. BaseValueTy = init->getType();
  1286. // Initialize the stack.
  1287. Indices.push_back(0);
  1288. IndexValues.push_back(nullptr);
  1289. // Recurse into the initializer.
  1290. findLocations(init);
  1291. // Check invariants.
  1292. assert(IndexValues.size() == Indices.size() && "mismatch");
  1293. assert(Indices.size() == 1 && "didn't pop all indices");
  1294. // Do the replacement; this basically invalidates 'init'.
  1295. assert(Locations.size() == PlaceholderAddresses.size() &&
  1296. "missed a placeholder?");
  1297. // We're iterating over a hashtable, so this would be a source of
  1298. // non-determinism in compiler output *except* that we're just
  1299. // messing around with llvm::Constant structures, which never itself
  1300. // does anything that should be visible in compiler output.
  1301. for (auto &entry : Locations) {
  1302. assert(entry.first->getParent() == nullptr && "not a placeholder!");
  1303. entry.first->replaceAllUsesWith(entry.second);
  1304. entry.first->eraseFromParent();
  1305. }
  1306. }
  1307. private:
  1308. void findLocations(llvm::Constant *init) {
  1309. // Recurse into aggregates.
  1310. if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
  1311. for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
  1312. Indices.push_back(i);
  1313. IndexValues.push_back(nullptr);
  1314. findLocations(agg->getOperand(i));
  1315. IndexValues.pop_back();
  1316. Indices.pop_back();
  1317. }
  1318. return;
  1319. }
  1320. // Otherwise, check for registered constants.
  1321. while (true) {
  1322. auto it = PlaceholderAddresses.find(init);
  1323. if (it != PlaceholderAddresses.end()) {
  1324. setLocation(it->second);
  1325. break;
  1326. }
  1327. // Look through bitcasts or other expressions.
  1328. if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
  1329. init = expr->getOperand(0);
  1330. } else {
  1331. break;
  1332. }
  1333. }
  1334. }
  1335. void setLocation(llvm::GlobalVariable *placeholder) {
  1336. assert(Locations.find(placeholder) == Locations.end() &&
  1337. "already found location for placeholder!");
  1338. // Lazily fill in IndexValues with the values from Indices.
  1339. // We do this in reverse because we should always have a strict
  1340. // prefix of indices from the start.
  1341. assert(Indices.size() == IndexValues.size());
  1342. for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
  1343. if (IndexValues[i]) {
  1344. #ifndef NDEBUG
  1345. for (size_t j = 0; j != i + 1; ++j) {
  1346. assert(IndexValues[j] &&
  1347. isa<llvm::ConstantInt>(IndexValues[j]) &&
  1348. cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
  1349. == Indices[j]);
  1350. }
  1351. #endif
  1352. break;
  1353. }
  1354. IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
  1355. }
  1356. // Form a GEP and then bitcast to the placeholder type so that the
  1357. // replacement will succeed.
  1358. llvm::Constant *location =
  1359. llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
  1360. Base, IndexValues);
  1361. location = llvm::ConstantExpr::getBitCast(location,
  1362. placeholder->getType());
  1363. Locations.insert({placeholder, location});
  1364. }
  1365. };
  1366. }
  1367. void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
  1368. assert(InitializedNonAbstract &&
  1369. "finalizing emitter that was used for abstract emission?");
  1370. assert(!Finalized && "finalizing emitter multiple times");
  1371. assert(global->getInitializer());
  1372. // Note that we might also be Failed.
  1373. Finalized = true;
  1374. if (!PlaceholderAddresses.empty()) {
  1375. ReplacePlaceholders(CGM, global, PlaceholderAddresses)
  1376. .replaceInInitializer(global->getInitializer());
  1377. PlaceholderAddresses.clear(); // satisfy
  1378. }
  1379. }
  1380. ConstantEmitter::~ConstantEmitter() {
  1381. assert((!InitializedNonAbstract || Finalized || Failed) &&
  1382. "not finalized after being initialized for non-abstract emission");
  1383. assert(PlaceholderAddresses.empty() && "unhandled placeholders");
  1384. }
  1385. static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
  1386. if (auto AT = type->getAs<AtomicType>()) {
  1387. return CGM.getContext().getQualifiedType(AT->getValueType(),
  1388. type.getQualifiers());
  1389. }
  1390. return type;
  1391. }
  1392. llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
  1393. // Make a quick check if variable can be default NULL initialized
  1394. // and avoid going through rest of code which may do, for c++11,
  1395. // initialization of memory to all NULLs.
  1396. if (!D.hasLocalStorage()) {
  1397. QualType Ty = CGM.getContext().getBaseElementType(D.getType());
  1398. if (Ty->isRecordType())
  1399. if (const CXXConstructExpr *E =
  1400. dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
  1401. const CXXConstructorDecl *CD = E->getConstructor();
  1402. if (CD->isTrivial() && CD->isDefaultConstructor())
  1403. return CGM.EmitNullConstant(D.getType());
  1404. }
  1405. }
  1406. InConstantContext = D.hasConstantInitialization();
  1407. QualType destType = D.getType();
  1408. // Try to emit the initializer. Note that this can allow some things that
  1409. // are not allowed by tryEmitPrivateForMemory alone.
  1410. if (auto value = D.evaluateValue()) {
  1411. return tryEmitPrivateForMemory(*value, destType);
  1412. }
  1413. // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
  1414. // reference is a constant expression, and the reference binds to a temporary,
  1415. // then constant initialization is performed. ConstExprEmitter will
  1416. // incorrectly emit a prvalue constant in this case, and the calling code
  1417. // interprets that as the (pointer) value of the reference, rather than the
  1418. // desired value of the referee.
  1419. if (destType->isReferenceType())
  1420. return nullptr;
  1421. const Expr *E = D.getInit();
  1422. assert(E && "No initializer to emit");
  1423. auto nonMemoryDestType = getNonMemoryType(CGM, destType);
  1424. auto C =
  1425. ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
  1426. return (C ? emitForMemory(C, destType) : nullptr);
  1427. }
  1428. llvm::Constant *
  1429. ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
  1430. auto nonMemoryDestType = getNonMemoryType(CGM, destType);
  1431. auto C = tryEmitAbstract(E, nonMemoryDestType);
  1432. return (C ? emitForMemory(C, destType) : nullptr);
  1433. }
  1434. llvm::Constant *
  1435. ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
  1436. QualType destType) {
  1437. auto nonMemoryDestType = getNonMemoryType(CGM, destType);
  1438. auto C = tryEmitAbstract(value, nonMemoryDestType);
  1439. return (C ? emitForMemory(C, destType) : nullptr);
  1440. }
  1441. llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
  1442. QualType destType) {
  1443. auto nonMemoryDestType = getNonMemoryType(CGM, destType);
  1444. llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
  1445. return (C ? emitForMemory(C, destType) : nullptr);
  1446. }
  1447. llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
  1448. QualType destType) {
  1449. auto nonMemoryDestType = getNonMemoryType(CGM, destType);
  1450. auto C = tryEmitPrivate(value, nonMemoryDestType);
  1451. return (C ? emitForMemory(C, destType) : nullptr);
  1452. }
  1453. llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
  1454. llvm::Constant *C,
  1455. QualType destType) {
  1456. // For an _Atomic-qualified constant, we may need to add tail padding.
  1457. if (auto AT = destType->getAs<AtomicType>()) {
  1458. QualType destValueType = AT->getValueType();
  1459. C = emitForMemory(CGM, C, destValueType);
  1460. uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
  1461. uint64_t outerSize = CGM.getContext().getTypeSize(destType);
  1462. if (innerSize == outerSize)
  1463. return C;
  1464. assert(innerSize < outerSize && "emitted over-large constant for atomic");
  1465. llvm::Constant *elts[] = {
  1466. C,
  1467. llvm::ConstantAggregateZero::get(
  1468. llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
  1469. };
  1470. return llvm::ConstantStruct::getAnon(elts);
  1471. }
  1472. // Zero-extend bool.
  1473. if (C->getType()->isIntegerTy(1)) {
  1474. llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
  1475. return llvm::ConstantExpr::getZExt(C, boolTy);
  1476. }
  1477. return C;
  1478. }
  1479. llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
  1480. QualType destType) {
  1481. assert(!destType->isVoidType() && "can't emit a void constant");
  1482. Expr::EvalResult Result;
  1483. bool Success = false;
  1484. if (destType->isReferenceType())
  1485. Success = E->EvaluateAsLValue(Result, CGM.getContext());
  1486. else
  1487. Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
  1488. llvm::Constant *C;
  1489. if (Success && !Result.HasSideEffects)
  1490. C = tryEmitPrivate(Result.Val, destType);
  1491. else
  1492. C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
  1493. return C;
  1494. }
  1495. llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
  1496. return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
  1497. }
  1498. namespace {
  1499. /// A struct which can be used to peephole certain kinds of finalization
  1500. /// that normally happen during l-value emission.
  1501. struct ConstantLValue {
  1502. llvm::Constant *Value;
  1503. bool HasOffsetApplied;
  1504. /*implicit*/ ConstantLValue(llvm::Constant *value,
  1505. bool hasOffsetApplied = false)
  1506. : Value(value), HasOffsetApplied(hasOffsetApplied) {}
  1507. /*implicit*/ ConstantLValue(ConstantAddress address)
  1508. : ConstantLValue(address.getPointer()) {}
  1509. };
  1510. /// A helper class for emitting constant l-values.
  1511. class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
  1512. ConstantLValue> {
  1513. CodeGenModule &CGM;
  1514. ConstantEmitter &Emitter;
  1515. const APValue &Value;
  1516. QualType DestType;
  1517. // Befriend StmtVisitorBase so that we don't have to expose Visit*.
  1518. friend StmtVisitorBase;
  1519. public:
  1520. ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
  1521. QualType destType)
  1522. : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
  1523. llvm::Constant *tryEmit();
  1524. private:
  1525. llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
  1526. ConstantLValue tryEmitBase(const APValue::LValueBase &base);
  1527. ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
  1528. ConstantLValue VisitConstantExpr(const ConstantExpr *E);
  1529. ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
  1530. ConstantLValue VisitStringLiteral(const StringLiteral *E);
  1531. ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
  1532. ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
  1533. ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
  1534. ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
  1535. ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
  1536. ConstantLValue VisitCallExpr(const CallExpr *E);
  1537. ConstantLValue VisitBlockExpr(const BlockExpr *E);
  1538. ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
  1539. ConstantLValue VisitMaterializeTemporaryExpr(
  1540. const MaterializeTemporaryExpr *E);
  1541. bool hasNonZeroOffset() const {
  1542. return !Value.getLValueOffset().isZero();
  1543. }
  1544. /// Return the value offset.
  1545. llvm::Constant *getOffset() {
  1546. return llvm::ConstantInt::get(CGM.Int64Ty,
  1547. Value.getLValueOffset().getQuantity());
  1548. }
  1549. /// Apply the value offset to the given constant.
  1550. llvm::Constant *applyOffset(llvm::Constant *C) {
  1551. if (!hasNonZeroOffset())
  1552. return C;
  1553. llvm::Type *origPtrTy = C->getType();
  1554. unsigned AS = origPtrTy->getPointerAddressSpace();
  1555. llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
  1556. C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
  1557. C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
  1558. C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
  1559. return C;
  1560. }
  1561. };
  1562. }
  1563. llvm::Constant *ConstantLValueEmitter::tryEmit() {
  1564. const APValue::LValueBase &base = Value.getLValueBase();
  1565. // The destination type should be a pointer or reference
  1566. // type, but it might also be a cast thereof.
  1567. //
  1568. // FIXME: the chain of casts required should be reflected in the APValue.
  1569. // We need this in order to correctly handle things like a ptrtoint of a
  1570. // non-zero null pointer and addrspace casts that aren't trivially
  1571. // represented in LLVM IR.
  1572. auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
  1573. assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
  1574. // If there's no base at all, this is a null or absolute pointer,
  1575. // possibly cast back to an integer type.
  1576. if (!base) {
  1577. return tryEmitAbsolute(destTy);
  1578. }
  1579. // Otherwise, try to emit the base.
  1580. ConstantLValue result = tryEmitBase(base);
  1581. // If that failed, we're done.
  1582. llvm::Constant *value = result.Value;
  1583. if (!value) return nullptr;
  1584. // Apply the offset if necessary and not already done.
  1585. if (!result.HasOffsetApplied) {
  1586. value = applyOffset(value);
  1587. }
  1588. // Convert to the appropriate type; this could be an lvalue for
  1589. // an integer. FIXME: performAddrSpaceCast
  1590. if (isa<llvm::PointerType>(destTy))
  1591. return llvm::ConstantExpr::getPointerCast(value, destTy);
  1592. return llvm::ConstantExpr::getPtrToInt(value, destTy);
  1593. }
  1594. /// Try to emit an absolute l-value, such as a null pointer or an integer
  1595. /// bitcast to pointer type.
  1596. llvm::Constant *
  1597. ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
  1598. // If we're producing a pointer, this is easy.
  1599. auto destPtrTy = cast<llvm::PointerType>(destTy);
  1600. if (Value.isNullPointer()) {
  1601. // FIXME: integer offsets from non-zero null pointers.
  1602. return CGM.getNullPointer(destPtrTy, DestType);
  1603. }
  1604. // Convert the integer to a pointer-sized integer before converting it
  1605. // to a pointer.
  1606. // FIXME: signedness depends on the original integer type.
  1607. auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
  1608. llvm::Constant *C;
  1609. C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
  1610. /*isSigned*/ false);
  1611. C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
  1612. return C;
  1613. }
  1614. ConstantLValue
  1615. ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
  1616. // Handle values.
  1617. if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
  1618. // The constant always points to the canonical declaration. We want to look
  1619. // at properties of the most recent declaration at the point of emission.
  1620. D = cast<ValueDecl>(D->getMostRecentDecl());
  1621. if (D->hasAttr<WeakRefAttr>())
  1622. return CGM.GetWeakRefReference(D).getPointer();
  1623. if (auto FD = dyn_cast<FunctionDecl>(D))
  1624. return CGM.GetAddrOfFunction(FD);
  1625. if (auto VD = dyn_cast<VarDecl>(D)) {
  1626. // We can never refer to a variable with local storage.
  1627. if (!VD->hasLocalStorage()) {
  1628. if (VD->isFileVarDecl() || VD->hasExternalStorage())
  1629. return CGM.GetAddrOfGlobalVar(VD);
  1630. if (VD->isLocalVarDecl()) {
  1631. return CGM.getOrCreateStaticVarDecl(
  1632. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
  1633. }
  1634. }
  1635. }
  1636. if (auto *GD = dyn_cast<MSGuidDecl>(D))
  1637. return CGM.GetAddrOfMSGuidDecl(GD);
  1638. if (auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(D))
  1639. return CGM.GetAddrOfUnnamedGlobalConstantDecl(GCD);
  1640. if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D))
  1641. return CGM.GetAddrOfTemplateParamObject(TPO);
  1642. return nullptr;
  1643. }
  1644. // Handle typeid(T).
  1645. if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
  1646. llvm::Type *StdTypeInfoPtrTy =
  1647. CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
  1648. llvm::Constant *TypeInfo =
  1649. CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
  1650. if (TypeInfo->getType() != StdTypeInfoPtrTy)
  1651. TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
  1652. return TypeInfo;
  1653. }
  1654. // Otherwise, it must be an expression.
  1655. return Visit(base.get<const Expr*>());
  1656. }
  1657. ConstantLValue
  1658. ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
  1659. if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(E))
  1660. return Result;
  1661. return Visit(E->getSubExpr());
  1662. }
  1663. ConstantLValue
  1664. ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
  1665. ConstantEmitter CompoundLiteralEmitter(CGM, Emitter.CGF);
  1666. CompoundLiteralEmitter.setInConstantContext(Emitter.isInConstantContext());
  1667. return tryEmitGlobalCompoundLiteral(CompoundLiteralEmitter, E);
  1668. }
  1669. ConstantLValue
  1670. ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
  1671. return CGM.GetAddrOfConstantStringFromLiteral(E);
  1672. }
  1673. ConstantLValue
  1674. ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
  1675. return CGM.GetAddrOfConstantStringFromObjCEncode(E);
  1676. }
  1677. static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
  1678. QualType T,
  1679. CodeGenModule &CGM) {
  1680. auto C = CGM.getObjCRuntime().GenerateConstantString(S);
  1681. return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
  1682. }
  1683. ConstantLValue
  1684. ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
  1685. return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
  1686. }
  1687. ConstantLValue
  1688. ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
  1689. assert(E->isExpressibleAsConstantInitializer() &&
  1690. "this boxed expression can't be emitted as a compile-time constant");
  1691. auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
  1692. return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
  1693. }
  1694. ConstantLValue
  1695. ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
  1696. return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
  1697. }
  1698. ConstantLValue
  1699. ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
  1700. assert(Emitter.CGF && "Invalid address of label expression outside function");
  1701. llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
  1702. Ptr = llvm::ConstantExpr::getBitCast(Ptr,
  1703. CGM.getTypes().ConvertType(E->getType()));
  1704. return Ptr;
  1705. }
  1706. ConstantLValue
  1707. ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
  1708. unsigned builtin = E->getBuiltinCallee();
  1709. if (builtin == Builtin::BI__builtin_function_start)
  1710. return CGM.GetFunctionStart(
  1711. E->getArg(0)->getAsBuiltinConstantDeclRef(CGM.getContext()));
  1712. if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
  1713. builtin != Builtin::BI__builtin___NSStringMakeConstantString)
  1714. return nullptr;
  1715. auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
  1716. if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
  1717. return CGM.getObjCRuntime().GenerateConstantString(literal);
  1718. } else {
  1719. // FIXME: need to deal with UCN conversion issues.
  1720. return CGM.GetAddrOfConstantCFString(literal);
  1721. }
  1722. }
  1723. ConstantLValue
  1724. ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
  1725. StringRef functionName;
  1726. if (auto CGF = Emitter.CGF)
  1727. functionName = CGF->CurFn->getName();
  1728. else
  1729. functionName = "global";
  1730. return CGM.GetAddrOfGlobalBlock(E, functionName);
  1731. }
  1732. ConstantLValue
  1733. ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
  1734. QualType T;
  1735. if (E->isTypeOperand())
  1736. T = E->getTypeOperand(CGM.getContext());
  1737. else
  1738. T = E->getExprOperand()->getType();
  1739. return CGM.GetAddrOfRTTIDescriptor(T);
  1740. }
  1741. ConstantLValue
  1742. ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
  1743. const MaterializeTemporaryExpr *E) {
  1744. assert(E->getStorageDuration() == SD_Static);
  1745. SmallVector<const Expr *, 2> CommaLHSs;
  1746. SmallVector<SubobjectAdjustment, 2> Adjustments;
  1747. const Expr *Inner =
  1748. E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  1749. return CGM.GetAddrOfGlobalTemporary(E, Inner);
  1750. }
  1751. llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
  1752. QualType DestType) {
  1753. switch (Value.getKind()) {
  1754. case APValue::None:
  1755. case APValue::Indeterminate:
  1756. // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
  1757. return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
  1758. case APValue::LValue:
  1759. return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
  1760. case APValue::Int:
  1761. return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
  1762. case APValue::FixedPoint:
  1763. return llvm::ConstantInt::get(CGM.getLLVMContext(),
  1764. Value.getFixedPoint().getValue());
  1765. case APValue::ComplexInt: {
  1766. llvm::Constant *Complex[2];
  1767. Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
  1768. Value.getComplexIntReal());
  1769. Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
  1770. Value.getComplexIntImag());
  1771. // FIXME: the target may want to specify that this is packed.
  1772. llvm::StructType *STy =
  1773. llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
  1774. return llvm::ConstantStruct::get(STy, Complex);
  1775. }
  1776. case APValue::Float: {
  1777. const llvm::APFloat &Init = Value.getFloat();
  1778. if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
  1779. !CGM.getContext().getLangOpts().NativeHalfType &&
  1780. CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
  1781. return llvm::ConstantInt::get(CGM.getLLVMContext(),
  1782. Init.bitcastToAPInt());
  1783. else
  1784. return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
  1785. }
  1786. case APValue::ComplexFloat: {
  1787. llvm::Constant *Complex[2];
  1788. Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
  1789. Value.getComplexFloatReal());
  1790. Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
  1791. Value.getComplexFloatImag());
  1792. // FIXME: the target may want to specify that this is packed.
  1793. llvm::StructType *STy =
  1794. llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
  1795. return llvm::ConstantStruct::get(STy, Complex);
  1796. }
  1797. case APValue::Vector: {
  1798. unsigned NumElts = Value.getVectorLength();
  1799. SmallVector<llvm::Constant *, 4> Inits(NumElts);
  1800. for (unsigned I = 0; I != NumElts; ++I) {
  1801. const APValue &Elt = Value.getVectorElt(I);
  1802. if (Elt.isInt())
  1803. Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
  1804. else if (Elt.isFloat())
  1805. Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
  1806. else
  1807. llvm_unreachable("unsupported vector element type");
  1808. }
  1809. return llvm::ConstantVector::get(Inits);
  1810. }
  1811. case APValue::AddrLabelDiff: {
  1812. const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
  1813. const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
  1814. llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
  1815. llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
  1816. if (!LHS || !RHS) return nullptr;
  1817. // Compute difference
  1818. llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
  1819. LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
  1820. RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
  1821. llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
  1822. // LLVM is a bit sensitive about the exact format of the
  1823. // address-of-label difference; make sure to truncate after
  1824. // the subtraction.
  1825. return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
  1826. }
  1827. case APValue::Struct:
  1828. case APValue::Union:
  1829. return ConstStructBuilder::BuildStruct(*this, Value, DestType);
  1830. case APValue::Array: {
  1831. const ArrayType *ArrayTy = CGM.getContext().getAsArrayType(DestType);
  1832. unsigned NumElements = Value.getArraySize();
  1833. unsigned NumInitElts = Value.getArrayInitializedElts();
  1834. // Emit array filler, if there is one.
  1835. llvm::Constant *Filler = nullptr;
  1836. if (Value.hasArrayFiller()) {
  1837. Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
  1838. ArrayTy->getElementType());
  1839. if (!Filler)
  1840. return nullptr;
  1841. }
  1842. // Emit initializer elements.
  1843. SmallVector<llvm::Constant*, 16> Elts;
  1844. if (Filler && Filler->isNullValue())
  1845. Elts.reserve(NumInitElts + 1);
  1846. else
  1847. Elts.reserve(NumElements);
  1848. llvm::Type *CommonElementType = nullptr;
  1849. for (unsigned I = 0; I < NumInitElts; ++I) {
  1850. llvm::Constant *C = tryEmitPrivateForMemory(
  1851. Value.getArrayInitializedElt(I), ArrayTy->getElementType());
  1852. if (!C) return nullptr;
  1853. if (I == 0)
  1854. CommonElementType = C->getType();
  1855. else if (C->getType() != CommonElementType)
  1856. CommonElementType = nullptr;
  1857. Elts.push_back(C);
  1858. }
  1859. llvm::ArrayType *Desired =
  1860. cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
  1861. return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
  1862. Filler);
  1863. }
  1864. case APValue::MemberPointer:
  1865. return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
  1866. }
  1867. llvm_unreachable("Unknown APValue kind");
  1868. }
  1869. llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
  1870. const CompoundLiteralExpr *E) {
  1871. return EmittedCompoundLiterals.lookup(E);
  1872. }
  1873. void CodeGenModule::setAddrOfConstantCompoundLiteral(
  1874. const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
  1875. bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
  1876. (void)Ok;
  1877. assert(Ok && "CLE has already been emitted!");
  1878. }
  1879. ConstantAddress
  1880. CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
  1881. assert(E->isFileScope() && "not a file-scope compound literal expr");
  1882. ConstantEmitter emitter(*this);
  1883. return tryEmitGlobalCompoundLiteral(emitter, E);
  1884. }
  1885. llvm::Constant *
  1886. CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
  1887. // Member pointer constants always have a very particular form.
  1888. const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
  1889. const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
  1890. // A member function pointer.
  1891. if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
  1892. return getCXXABI().EmitMemberFunctionPointer(method);
  1893. // Otherwise, a member data pointer.
  1894. uint64_t fieldOffset = getContext().getFieldOffset(decl);
  1895. CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
  1896. return getCXXABI().EmitMemberDataPointer(type, chars);
  1897. }
  1898. static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
  1899. llvm::Type *baseType,
  1900. const CXXRecordDecl *base);
  1901. static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
  1902. const RecordDecl *record,
  1903. bool asCompleteObject) {
  1904. const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
  1905. llvm::StructType *structure =
  1906. (asCompleteObject ? layout.getLLVMType()
  1907. : layout.getBaseSubobjectLLVMType());
  1908. unsigned numElements = structure->getNumElements();
  1909. std::vector<llvm::Constant *> elements(numElements);
  1910. auto CXXR = dyn_cast<CXXRecordDecl>(record);
  1911. // Fill in all the bases.
  1912. if (CXXR) {
  1913. for (const auto &I : CXXR->bases()) {
  1914. if (I.isVirtual()) {
  1915. // Ignore virtual bases; if we're laying out for a complete
  1916. // object, we'll lay these out later.
  1917. continue;
  1918. }
  1919. const CXXRecordDecl *base =
  1920. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1921. // Ignore empty bases.
  1922. if (base->isEmpty() ||
  1923. CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
  1924. .isZero())
  1925. continue;
  1926. unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
  1927. llvm::Type *baseType = structure->getElementType(fieldIndex);
  1928. elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
  1929. }
  1930. }
  1931. // Fill in all the fields.
  1932. for (const auto *Field : record->fields()) {
  1933. // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
  1934. // will fill in later.)
  1935. if (!Field->isBitField() && !Field->isZeroSize(CGM.getContext())) {
  1936. unsigned fieldIndex = layout.getLLVMFieldNo(Field);
  1937. elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
  1938. }
  1939. // For unions, stop after the first named field.
  1940. if (record->isUnion()) {
  1941. if (Field->getIdentifier())
  1942. break;
  1943. if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
  1944. if (FieldRD->findFirstNamedDataMember())
  1945. break;
  1946. }
  1947. }
  1948. // Fill in the virtual bases, if we're working with the complete object.
  1949. if (CXXR && asCompleteObject) {
  1950. for (const auto &I : CXXR->vbases()) {
  1951. const CXXRecordDecl *base =
  1952. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1953. // Ignore empty bases.
  1954. if (base->isEmpty())
  1955. continue;
  1956. unsigned fieldIndex = layout.getVirtualBaseIndex(base);
  1957. // We might have already laid this field out.
  1958. if (elements[fieldIndex]) continue;
  1959. llvm::Type *baseType = structure->getElementType(fieldIndex);
  1960. elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
  1961. }
  1962. }
  1963. // Now go through all other fields and zero them out.
  1964. for (unsigned i = 0; i != numElements; ++i) {
  1965. if (!elements[i])
  1966. elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
  1967. }
  1968. return llvm::ConstantStruct::get(structure, elements);
  1969. }
  1970. /// Emit the null constant for a base subobject.
  1971. static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
  1972. llvm::Type *baseType,
  1973. const CXXRecordDecl *base) {
  1974. const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
  1975. // Just zero out bases that don't have any pointer to data members.
  1976. if (baseLayout.isZeroInitializableAsBase())
  1977. return llvm::Constant::getNullValue(baseType);
  1978. // Otherwise, we can just use its null constant.
  1979. return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
  1980. }
  1981. llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
  1982. QualType T) {
  1983. return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
  1984. }
  1985. llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
  1986. if (T->getAs<PointerType>())
  1987. return getNullPointer(
  1988. cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
  1989. if (getTypes().isZeroInitializable(T))
  1990. return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
  1991. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
  1992. llvm::ArrayType *ATy =
  1993. cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
  1994. QualType ElementTy = CAT->getElementType();
  1995. llvm::Constant *Element =
  1996. ConstantEmitter::emitNullForMemory(*this, ElementTy);
  1997. unsigned NumElements = CAT->getSize().getZExtValue();
  1998. SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
  1999. return llvm::ConstantArray::get(ATy, Array);
  2000. }
  2001. if (const RecordType *RT = T->getAs<RecordType>())
  2002. return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
  2003. assert(T->isMemberDataPointerType() &&
  2004. "Should only see pointers to data members here!");
  2005. return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
  2006. }
  2007. llvm::Constant *
  2008. CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
  2009. return ::EmitNullConstant(*this, Record, false);
  2010. }