CGExprConstant.cpp 77 KB

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