CGExprConstant.cpp 85 KB

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