CGExprConstant.cpp 86 KB

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