CGExprConstant.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435
  1. //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This contains code to emit Constant Expr nodes as LLVM code.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CodeGenFunction.h"
  14. #include "CGCXXABI.h"
  15. #include "CGObjCRuntime.h"
  16. #include "CGRecordLayout.h"
  17. #include "CodeGenModule.h"
  18. #include "clang/AST/APValue.h"
  19. #include "clang/AST/ASTContext.h"
  20. #include "clang/AST/RecordLayout.h"
  21. #include "clang/AST/StmtVisitor.h"
  22. #include "clang/Basic/Builtins.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DataLayout.h"
  25. #include "llvm/IR/Function.h"
  26. #include "llvm/IR/GlobalVariable.h"
  27. using namespace clang;
  28. using namespace CodeGen;
  29. //===----------------------------------------------------------------------===//
  30. // ConstStructBuilder
  31. //===----------------------------------------------------------------------===//
  32. namespace {
  33. class ConstStructBuilder {
  34. CodeGenModule &CGM;
  35. CodeGenFunction *CGF;
  36. bool Packed;
  37. CharUnits NextFieldOffsetInChars;
  38. CharUnits LLVMStructAlignment;
  39. SmallVector<llvm::Constant *, 32> Elements;
  40. public:
  41. static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
  42. InitListExpr *ILE);
  43. static llvm::Constant *BuildStruct(CodeGenModule &CGM, CodeGenFunction *CGF,
  44. const APValue &Value, QualType ValTy);
  45. private:
  46. ConstStructBuilder(CodeGenModule &CGM, CodeGenFunction *CGF)
  47. : CGM(CGM), CGF(CGF), Packed(false),
  48. NextFieldOffsetInChars(CharUnits::Zero()),
  49. LLVMStructAlignment(CharUnits::One()) { }
  50. void AppendField(const FieldDecl *Field, uint64_t FieldOffset,
  51. llvm::Constant *InitExpr);
  52. void AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst);
  53. void AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
  54. llvm::ConstantInt *InitExpr);
  55. void AppendPadding(CharUnits PadSize);
  56. void AppendTailPadding(CharUnits RecordSize);
  57. void ConvertStructToPacked();
  58. bool Build(InitListExpr *ILE);
  59. void Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
  60. const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
  61. llvm::Constant *Finalize(QualType Ty);
  62. CharUnits getAlignment(const llvm::Constant *C) const {
  63. if (Packed) return CharUnits::One();
  64. return CharUnits::fromQuantity(
  65. CGM.getDataLayout().getABITypeAlignment(C->getType()));
  66. }
  67. CharUnits getSizeInChars(const llvm::Constant *C) const {
  68. return CharUnits::fromQuantity(
  69. CGM.getDataLayout().getTypeAllocSize(C->getType()));
  70. }
  71. };
  72. void ConstStructBuilder::
  73. AppendField(const FieldDecl *Field, uint64_t FieldOffset,
  74. llvm::Constant *InitCst) {
  75. const ASTContext &Context = CGM.getContext();
  76. CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
  77. AppendBytes(FieldOffsetInChars, InitCst);
  78. }
  79. void ConstStructBuilder::
  80. AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst) {
  81. assert(NextFieldOffsetInChars <= FieldOffsetInChars
  82. && "Field offset mismatch!");
  83. CharUnits FieldAlignment = getAlignment(InitCst);
  84. // Round up the field offset to the alignment of the field type.
  85. CharUnits AlignedNextFieldOffsetInChars =
  86. NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
  87. if (AlignedNextFieldOffsetInChars < FieldOffsetInChars) {
  88. // We need to append padding.
  89. AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
  90. assert(NextFieldOffsetInChars == FieldOffsetInChars &&
  91. "Did not add enough padding!");
  92. AlignedNextFieldOffsetInChars =
  93. NextFieldOffsetInChars.RoundUpToAlignment(FieldAlignment);
  94. }
  95. if (AlignedNextFieldOffsetInChars > FieldOffsetInChars) {
  96. assert(!Packed && "Alignment is wrong even with a packed struct!");
  97. // Convert the struct to a packed struct.
  98. ConvertStructToPacked();
  99. // After we pack the struct, we may need to insert padding.
  100. if (NextFieldOffsetInChars < FieldOffsetInChars) {
  101. // We need to append padding.
  102. AppendPadding(FieldOffsetInChars - NextFieldOffsetInChars);
  103. assert(NextFieldOffsetInChars == FieldOffsetInChars &&
  104. "Did not add enough padding!");
  105. }
  106. AlignedNextFieldOffsetInChars = NextFieldOffsetInChars;
  107. }
  108. // Add the field.
  109. Elements.push_back(InitCst);
  110. NextFieldOffsetInChars = AlignedNextFieldOffsetInChars +
  111. getSizeInChars(InitCst);
  112. if (Packed)
  113. assert(LLVMStructAlignment == CharUnits::One() &&
  114. "Packed struct not byte-aligned!");
  115. else
  116. LLVMStructAlignment = std::max(LLVMStructAlignment, FieldAlignment);
  117. }
  118. void ConstStructBuilder::AppendBitField(const FieldDecl *Field,
  119. uint64_t FieldOffset,
  120. llvm::ConstantInt *CI) {
  121. const ASTContext &Context = CGM.getContext();
  122. const uint64_t CharWidth = Context.getCharWidth();
  123. uint64_t NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
  124. if (FieldOffset > NextFieldOffsetInBits) {
  125. // We need to add padding.
  126. CharUnits PadSize = Context.toCharUnitsFromBits(
  127. llvm::RoundUpToAlignment(FieldOffset - NextFieldOffsetInBits,
  128. Context.getTargetInfo().getCharAlign()));
  129. AppendPadding(PadSize);
  130. }
  131. uint64_t FieldSize = Field->getBitWidthValue(Context);
  132. llvm::APInt FieldValue = CI->getValue();
  133. // Promote the size of FieldValue if necessary
  134. // FIXME: This should never occur, but currently it can because initializer
  135. // constants are cast to bool, and because clang is not enforcing bitfield
  136. // width limits.
  137. if (FieldSize > FieldValue.getBitWidth())
  138. FieldValue = FieldValue.zext(FieldSize);
  139. // Truncate the size of FieldValue to the bit field size.
  140. if (FieldSize < FieldValue.getBitWidth())
  141. FieldValue = FieldValue.trunc(FieldSize);
  142. NextFieldOffsetInBits = Context.toBits(NextFieldOffsetInChars);
  143. if (FieldOffset < NextFieldOffsetInBits) {
  144. // Either part of the field or the entire field can go into the previous
  145. // byte.
  146. assert(!Elements.empty() && "Elements can't be empty!");
  147. unsigned BitsInPreviousByte = NextFieldOffsetInBits - FieldOffset;
  148. bool FitsCompletelyInPreviousByte =
  149. BitsInPreviousByte >= FieldValue.getBitWidth();
  150. llvm::APInt Tmp = FieldValue;
  151. if (!FitsCompletelyInPreviousByte) {
  152. unsigned NewFieldWidth = FieldSize - BitsInPreviousByte;
  153. if (CGM.getDataLayout().isBigEndian()) {
  154. Tmp = Tmp.lshr(NewFieldWidth);
  155. Tmp = Tmp.trunc(BitsInPreviousByte);
  156. // We want the remaining high bits.
  157. FieldValue = FieldValue.trunc(NewFieldWidth);
  158. } else {
  159. Tmp = Tmp.trunc(BitsInPreviousByte);
  160. // We want the remaining low bits.
  161. FieldValue = FieldValue.lshr(BitsInPreviousByte);
  162. FieldValue = FieldValue.trunc(NewFieldWidth);
  163. }
  164. }
  165. Tmp = Tmp.zext(CharWidth);
  166. if (CGM.getDataLayout().isBigEndian()) {
  167. if (FitsCompletelyInPreviousByte)
  168. Tmp = Tmp.shl(BitsInPreviousByte - FieldValue.getBitWidth());
  169. } else {
  170. Tmp = Tmp.shl(CharWidth - BitsInPreviousByte);
  171. }
  172. // 'or' in the bits that go into the previous byte.
  173. llvm::Value *LastElt = Elements.back();
  174. if (llvm::ConstantInt *Val = dyn_cast<llvm::ConstantInt>(LastElt))
  175. Tmp |= Val->getValue();
  176. else {
  177. assert(isa<llvm::UndefValue>(LastElt));
  178. // If there is an undef field that we're adding to, it can either be a
  179. // scalar undef (in which case, we just replace it with our field) or it
  180. // is an array. If it is an array, we have to pull one byte off the
  181. // array so that the other undef bytes stay around.
  182. if (!isa<llvm::IntegerType>(LastElt->getType())) {
  183. // The undef padding will be a multibyte array, create a new smaller
  184. // padding and then an hole for our i8 to get plopped into.
  185. assert(isa<llvm::ArrayType>(LastElt->getType()) &&
  186. "Expected array padding of undefs");
  187. llvm::ArrayType *AT = cast<llvm::ArrayType>(LastElt->getType());
  188. assert(AT->getElementType()->isIntegerTy(CharWidth) &&
  189. AT->getNumElements() != 0 &&
  190. "Expected non-empty array padding of undefs");
  191. // Remove the padding array.
  192. NextFieldOffsetInChars -= CharUnits::fromQuantity(AT->getNumElements());
  193. Elements.pop_back();
  194. // Add the padding back in two chunks.
  195. AppendPadding(CharUnits::fromQuantity(AT->getNumElements()-1));
  196. AppendPadding(CharUnits::One());
  197. assert(isa<llvm::UndefValue>(Elements.back()) &&
  198. Elements.back()->getType()->isIntegerTy(CharWidth) &&
  199. "Padding addition didn't work right");
  200. }
  201. }
  202. Elements.back() = llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp);
  203. if (FitsCompletelyInPreviousByte)
  204. return;
  205. }
  206. while (FieldValue.getBitWidth() > CharWidth) {
  207. llvm::APInt Tmp;
  208. if (CGM.getDataLayout().isBigEndian()) {
  209. // We want the high bits.
  210. Tmp =
  211. FieldValue.lshr(FieldValue.getBitWidth() - CharWidth).trunc(CharWidth);
  212. } else {
  213. // We want the low bits.
  214. Tmp = FieldValue.trunc(CharWidth);
  215. FieldValue = FieldValue.lshr(CharWidth);
  216. }
  217. Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(), Tmp));
  218. ++NextFieldOffsetInChars;
  219. FieldValue = FieldValue.trunc(FieldValue.getBitWidth() - CharWidth);
  220. }
  221. assert(FieldValue.getBitWidth() > 0 &&
  222. "Should have at least one bit left!");
  223. assert(FieldValue.getBitWidth() <= CharWidth &&
  224. "Should not have more than a byte left!");
  225. if (FieldValue.getBitWidth() < CharWidth) {
  226. if (CGM.getDataLayout().isBigEndian()) {
  227. unsigned BitWidth = FieldValue.getBitWidth();
  228. FieldValue = FieldValue.zext(CharWidth) << (CharWidth - BitWidth);
  229. } else
  230. FieldValue = FieldValue.zext(CharWidth);
  231. }
  232. // Append the last element.
  233. Elements.push_back(llvm::ConstantInt::get(CGM.getLLVMContext(),
  234. FieldValue));
  235. ++NextFieldOffsetInChars;
  236. }
  237. void ConstStructBuilder::AppendPadding(CharUnits PadSize) {
  238. if (PadSize.isZero())
  239. return;
  240. llvm::Type *Ty = CGM.Int8Ty;
  241. if (PadSize > CharUnits::One())
  242. Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity());
  243. llvm::Constant *C = llvm::UndefValue::get(Ty);
  244. Elements.push_back(C);
  245. assert(getAlignment(C) == CharUnits::One() &&
  246. "Padding must have 1 byte alignment!");
  247. NextFieldOffsetInChars += getSizeInChars(C);
  248. }
  249. void ConstStructBuilder::AppendTailPadding(CharUnits RecordSize) {
  250. assert(NextFieldOffsetInChars <= RecordSize &&
  251. "Size mismatch!");
  252. AppendPadding(RecordSize - NextFieldOffsetInChars);
  253. }
  254. void ConstStructBuilder::ConvertStructToPacked() {
  255. SmallVector<llvm::Constant *, 16> PackedElements;
  256. CharUnits ElementOffsetInChars = CharUnits::Zero();
  257. for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
  258. llvm::Constant *C = Elements[i];
  259. CharUnits ElementAlign = CharUnits::fromQuantity(
  260. CGM.getDataLayout().getABITypeAlignment(C->getType()));
  261. CharUnits AlignedElementOffsetInChars =
  262. ElementOffsetInChars.RoundUpToAlignment(ElementAlign);
  263. if (AlignedElementOffsetInChars > ElementOffsetInChars) {
  264. // We need some padding.
  265. CharUnits NumChars =
  266. AlignedElementOffsetInChars - ElementOffsetInChars;
  267. llvm::Type *Ty = CGM.Int8Ty;
  268. if (NumChars > CharUnits::One())
  269. Ty = llvm::ArrayType::get(Ty, NumChars.getQuantity());
  270. llvm::Constant *Padding = llvm::UndefValue::get(Ty);
  271. PackedElements.push_back(Padding);
  272. ElementOffsetInChars += getSizeInChars(Padding);
  273. }
  274. PackedElements.push_back(C);
  275. ElementOffsetInChars += getSizeInChars(C);
  276. }
  277. assert(ElementOffsetInChars == NextFieldOffsetInChars &&
  278. "Packing the struct changed its size!");
  279. Elements.swap(PackedElements);
  280. LLVMStructAlignment = CharUnits::One();
  281. Packed = true;
  282. }
  283. bool ConstStructBuilder::Build(InitListExpr *ILE) {
  284. RecordDecl *RD = ILE->getType()->getAs<RecordType>()->getDecl();
  285. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  286. unsigned FieldNo = 0;
  287. unsigned ElementNo = 0;
  288. for (RecordDecl::field_iterator Field = RD->field_begin(),
  289. FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
  290. // If this is a union, skip all the fields that aren't being initialized.
  291. if (RD->isUnion() && ILE->getInitializedFieldInUnion() != *Field)
  292. continue;
  293. // Don't emit anonymous bitfields, they just affect layout.
  294. if (Field->isUnnamedBitfield())
  295. continue;
  296. // Get the initializer. A struct can include fields without initializers,
  297. // we just use explicit null values for them.
  298. llvm::Constant *EltInit;
  299. if (ElementNo < ILE->getNumInits())
  300. EltInit = CGM.EmitConstantExpr(ILE->getInit(ElementNo++),
  301. Field->getType(), CGF);
  302. else
  303. EltInit = CGM.EmitNullConstant(Field->getType());
  304. if (!EltInit)
  305. return false;
  306. if (!Field->isBitField()) {
  307. // Handle non-bitfield members.
  308. AppendField(*Field, Layout.getFieldOffset(FieldNo), EltInit);
  309. } else {
  310. // Otherwise we have a bitfield.
  311. if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
  312. AppendBitField(*Field, Layout.getFieldOffset(FieldNo), CI);
  313. } else {
  314. // We are trying to initialize a bitfield with a non-trivial constant,
  315. // this must require run-time code.
  316. return false;
  317. }
  318. }
  319. }
  320. return true;
  321. }
  322. namespace {
  323. struct BaseInfo {
  324. BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
  325. : Decl(Decl), Offset(Offset), Index(Index) {
  326. }
  327. const CXXRecordDecl *Decl;
  328. CharUnits Offset;
  329. unsigned Index;
  330. bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
  331. };
  332. }
  333. void ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
  334. bool IsPrimaryBase,
  335. const CXXRecordDecl *VTableClass,
  336. CharUnits Offset) {
  337. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  338. if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
  339. // Add a vtable pointer, if we need one and it hasn't already been added.
  340. if (CD->isDynamicClass() && !IsPrimaryBase) {
  341. llvm::Constant *VTableAddressPoint =
  342. CGM.getCXXABI().getVTableAddressPointForConstExpr(
  343. BaseSubobject(CD, Offset), VTableClass);
  344. AppendBytes(Offset, VTableAddressPoint);
  345. }
  346. // Accumulate and sort bases, in order to visit them in address order, which
  347. // may not be the same as declaration order.
  348. SmallVector<BaseInfo, 8> Bases;
  349. Bases.reserve(CD->getNumBases());
  350. unsigned BaseNo = 0;
  351. for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
  352. BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
  353. assert(!Base->isVirtual() && "should not have virtual bases here");
  354. const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
  355. CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
  356. Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
  357. }
  358. std::stable_sort(Bases.begin(), Bases.end());
  359. for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
  360. BaseInfo &Base = Bases[I];
  361. bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
  362. Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
  363. VTableClass, Offset + Base.Offset);
  364. }
  365. }
  366. unsigned FieldNo = 0;
  367. uint64_t OffsetBits = CGM.getContext().toBits(Offset);
  368. for (RecordDecl::field_iterator Field = RD->field_begin(),
  369. FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
  370. // If this is a union, skip all the fields that aren't being initialized.
  371. if (RD->isUnion() && Val.getUnionField() != *Field)
  372. continue;
  373. // Don't emit anonymous bitfields, they just affect layout.
  374. if (Field->isUnnamedBitfield())
  375. continue;
  376. // Emit the value of the initializer.
  377. const APValue &FieldValue =
  378. RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
  379. llvm::Constant *EltInit =
  380. CGM.EmitConstantValueForMemory(FieldValue, Field->getType(), CGF);
  381. assert(EltInit && "EmitConstantValue can't fail");
  382. if (!Field->isBitField()) {
  383. // Handle non-bitfield members.
  384. AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, EltInit);
  385. } else {
  386. // Otherwise we have a bitfield.
  387. AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
  388. cast<llvm::ConstantInt>(EltInit));
  389. }
  390. }
  391. }
  392. llvm::Constant *ConstStructBuilder::Finalize(QualType Ty) {
  393. RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
  394. const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
  395. CharUnits LayoutSizeInChars = Layout.getSize();
  396. if (NextFieldOffsetInChars > LayoutSizeInChars) {
  397. // If the struct is bigger than the size of the record type,
  398. // we must have a flexible array member at the end.
  399. assert(RD->hasFlexibleArrayMember() &&
  400. "Must have flexible array member if struct is bigger than type!");
  401. // No tail padding is necessary.
  402. } else {
  403. // Append tail padding if necessary.
  404. CharUnits LLVMSizeInChars =
  405. NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
  406. if (LLVMSizeInChars != LayoutSizeInChars)
  407. AppendTailPadding(LayoutSizeInChars);
  408. LLVMSizeInChars =
  409. NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
  410. // Check if we need to convert the struct to a packed struct.
  411. if (NextFieldOffsetInChars <= LayoutSizeInChars &&
  412. LLVMSizeInChars > LayoutSizeInChars) {
  413. assert(!Packed && "Size mismatch!");
  414. ConvertStructToPacked();
  415. assert(NextFieldOffsetInChars <= LayoutSizeInChars &&
  416. "Converting to packed did not help!");
  417. }
  418. LLVMSizeInChars =
  419. NextFieldOffsetInChars.RoundUpToAlignment(LLVMStructAlignment);
  420. assert(LayoutSizeInChars == LLVMSizeInChars &&
  421. "Tail padding mismatch!");
  422. }
  423. // Pick the type to use. If the type is layout identical to the ConvertType
  424. // type then use it, otherwise use whatever the builder produced for us.
  425. llvm::StructType *STy =
  426. llvm::ConstantStruct::getTypeForElements(CGM.getLLVMContext(),
  427. Elements, Packed);
  428. llvm::Type *ValTy = CGM.getTypes().ConvertType(Ty);
  429. if (llvm::StructType *ValSTy = dyn_cast<llvm::StructType>(ValTy)) {
  430. if (ValSTy->isLayoutIdentical(STy))
  431. STy = ValSTy;
  432. }
  433. llvm::Constant *Result = llvm::ConstantStruct::get(STy, Elements);
  434. assert(NextFieldOffsetInChars.RoundUpToAlignment(getAlignment(Result)) ==
  435. getSizeInChars(Result) && "Size mismatch!");
  436. return Result;
  437. }
  438. llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
  439. CodeGenFunction *CGF,
  440. InitListExpr *ILE) {
  441. ConstStructBuilder Builder(CGM, CGF);
  442. if (!Builder.Build(ILE))
  443. return nullptr;
  444. return Builder.Finalize(ILE->getType());
  445. }
  446. llvm::Constant *ConstStructBuilder::BuildStruct(CodeGenModule &CGM,
  447. CodeGenFunction *CGF,
  448. const APValue &Val,
  449. QualType ValTy) {
  450. ConstStructBuilder Builder(CGM, CGF);
  451. const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
  452. const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
  453. Builder.Build(Val, RD, false, CD, CharUnits::Zero());
  454. return Builder.Finalize(ValTy);
  455. }
  456. //===----------------------------------------------------------------------===//
  457. // ConstExprEmitter
  458. //===----------------------------------------------------------------------===//
  459. /// This class only needs to handle two cases:
  460. /// 1) Literals (this is used by APValue emission to emit literals).
  461. /// 2) Arrays, structs and unions (outside C++11 mode, we don't currently
  462. /// constant fold these types).
  463. class ConstExprEmitter :
  464. public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
  465. CodeGenModule &CGM;
  466. CodeGenFunction *CGF;
  467. llvm::LLVMContext &VMContext;
  468. public:
  469. ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
  470. : CGM(cgm), CGF(cgf), VMContext(cgm.getLLVMContext()) {
  471. }
  472. //===--------------------------------------------------------------------===//
  473. // Visitor Methods
  474. //===--------------------------------------------------------------------===//
  475. llvm::Constant *VisitStmt(Stmt *S) {
  476. return nullptr;
  477. }
  478. llvm::Constant *VisitParenExpr(ParenExpr *PE) {
  479. return Visit(PE->getSubExpr());
  480. }
  481. llvm::Constant *
  482. VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE) {
  483. return Visit(PE->getReplacement());
  484. }
  485. llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
  486. return Visit(GE->getResultExpr());
  487. }
  488. llvm::Constant *VisitChooseExpr(ChooseExpr *CE) {
  489. return Visit(CE->getChosenSubExpr());
  490. }
  491. llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
  492. return Visit(E->getInitializer());
  493. }
  494. llvm::Constant *VisitCastExpr(CastExpr* E) {
  495. Expr *subExpr = E->getSubExpr();
  496. llvm::Constant *C = CGM.EmitConstantExpr(subExpr, subExpr->getType(), CGF);
  497. if (!C) return nullptr;
  498. llvm::Type *destType = ConvertType(E->getType());
  499. switch (E->getCastKind()) {
  500. case CK_ToUnion: {
  501. // GCC cast to union extension
  502. assert(E->getType()->isUnionType() &&
  503. "Destination type is not union type!");
  504. // Build a struct with the union sub-element as the first member,
  505. // and padded to the appropriate size
  506. SmallVector<llvm::Constant*, 2> Elts;
  507. SmallVector<llvm::Type*, 2> Types;
  508. Elts.push_back(C);
  509. Types.push_back(C->getType());
  510. unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
  511. unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destType);
  512. assert(CurSize <= TotalSize && "Union size mismatch!");
  513. if (unsigned NumPadBytes = TotalSize - CurSize) {
  514. llvm::Type *Ty = CGM.Int8Ty;
  515. if (NumPadBytes > 1)
  516. Ty = llvm::ArrayType::get(Ty, NumPadBytes);
  517. Elts.push_back(llvm::UndefValue::get(Ty));
  518. Types.push_back(Ty);
  519. }
  520. llvm::StructType* STy =
  521. llvm::StructType::get(C->getType()->getContext(), Types, false);
  522. return llvm::ConstantStruct::get(STy, Elts);
  523. }
  524. case CK_AddressSpaceConversion:
  525. return llvm::ConstantExpr::getAddrSpaceCast(C, destType);
  526. case CK_LValueToRValue:
  527. case CK_AtomicToNonAtomic:
  528. case CK_NonAtomicToAtomic:
  529. case CK_NoOp:
  530. case CK_ConstructorConversion:
  531. return C;
  532. case CK_Dependent: llvm_unreachable("saw dependent cast!");
  533. case CK_BuiltinFnToFnPtr:
  534. llvm_unreachable("builtin functions are handled elsewhere");
  535. case CK_ReinterpretMemberPointer:
  536. case CK_DerivedToBaseMemberPointer:
  537. case CK_BaseToDerivedMemberPointer:
  538. return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
  539. // These will never be supported.
  540. case CK_ObjCObjectLValueCast:
  541. case CK_ARCProduceObject:
  542. case CK_ARCConsumeObject:
  543. case CK_ARCReclaimReturnedObject:
  544. case CK_ARCExtendBlockObject:
  545. case CK_CopyAndAutoreleaseBlockObject:
  546. return nullptr;
  547. // These don't need to be handled here because Evaluate knows how to
  548. // evaluate them in the cases where they can be folded.
  549. case CK_BitCast:
  550. case CK_ToVoid:
  551. case CK_Dynamic:
  552. case CK_LValueBitCast:
  553. case CK_NullToMemberPointer:
  554. case CK_UserDefinedConversion:
  555. case CK_CPointerToObjCPointerCast:
  556. case CK_BlockPointerToObjCPointerCast:
  557. case CK_AnyPointerToBlockPointerCast:
  558. case CK_ArrayToPointerDecay:
  559. case CK_FunctionToPointerDecay:
  560. case CK_BaseToDerived:
  561. case CK_DerivedToBase:
  562. case CK_UncheckedDerivedToBase:
  563. case CK_MemberPointerToBoolean:
  564. case CK_VectorSplat:
  565. case CK_FloatingRealToComplex:
  566. case CK_FloatingComplexToReal:
  567. case CK_FloatingComplexToBoolean:
  568. case CK_FloatingComplexCast:
  569. case CK_FloatingComplexToIntegralComplex:
  570. case CK_IntegralRealToComplex:
  571. case CK_IntegralComplexToReal:
  572. case CK_IntegralComplexToBoolean:
  573. case CK_IntegralComplexCast:
  574. case CK_IntegralComplexToFloatingComplex:
  575. case CK_PointerToIntegral:
  576. case CK_PointerToBoolean:
  577. case CK_NullToPointer:
  578. case CK_IntegralCast:
  579. case CK_IntegralToPointer:
  580. case CK_IntegralToBoolean:
  581. case CK_IntegralToFloating:
  582. case CK_FloatingToIntegral:
  583. case CK_FloatingToBoolean:
  584. case CK_FloatingCast:
  585. case CK_ZeroToOCLEvent:
  586. return nullptr;
  587. }
  588. llvm_unreachable("Invalid CastKind");
  589. }
  590. llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
  591. return Visit(DAE->getExpr());
  592. }
  593. llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
  594. // No need for a DefaultInitExprScope: we don't handle 'this' in a
  595. // constant expression.
  596. return Visit(DIE->getExpr());
  597. }
  598. llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
  599. return Visit(E->GetTemporaryExpr());
  600. }
  601. llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
  602. if (ILE->isStringLiteralInit())
  603. return Visit(ILE->getInit(0));
  604. llvm::ArrayType *AType =
  605. cast<llvm::ArrayType>(ConvertType(ILE->getType()));
  606. llvm::Type *ElemTy = AType->getElementType();
  607. unsigned NumInitElements = ILE->getNumInits();
  608. unsigned NumElements = AType->getNumElements();
  609. // Initialising an array requires us to automatically
  610. // initialise any elements that have not been initialised explicitly
  611. unsigned NumInitableElts = std::min(NumInitElements, NumElements);
  612. // Initialize remaining array elements.
  613. // FIXME: This doesn't handle member pointers correctly!
  614. llvm::Constant *fillC;
  615. if (Expr *filler = ILE->getArrayFiller())
  616. fillC = CGM.EmitConstantExpr(filler, filler->getType(), CGF);
  617. else
  618. fillC = llvm::Constant::getNullValue(ElemTy);
  619. if (!fillC)
  620. return nullptr;
  621. // Try to use a ConstantAggregateZero if we can.
  622. if (fillC->isNullValue() && !NumInitableElts)
  623. return llvm::ConstantAggregateZero::get(AType);
  624. // Copy initializer elements.
  625. std::vector<llvm::Constant*> Elts;
  626. Elts.reserve(NumInitableElts + NumElements);
  627. bool RewriteType = false;
  628. for (unsigned i = 0; i < NumInitableElts; ++i) {
  629. Expr *Init = ILE->getInit(i);
  630. llvm::Constant *C = CGM.EmitConstantExpr(Init, Init->getType(), CGF);
  631. if (!C)
  632. return nullptr;
  633. RewriteType |= (C->getType() != ElemTy);
  634. Elts.push_back(C);
  635. }
  636. RewriteType |= (fillC->getType() != ElemTy);
  637. Elts.resize(NumElements, fillC);
  638. if (RewriteType) {
  639. // FIXME: Try to avoid packing the array
  640. std::vector<llvm::Type*> Types;
  641. Types.reserve(NumInitableElts + NumElements);
  642. for (unsigned i = 0, e = Elts.size(); i < e; ++i)
  643. Types.push_back(Elts[i]->getType());
  644. llvm::StructType *SType = llvm::StructType::get(AType->getContext(),
  645. Types, true);
  646. return llvm::ConstantStruct::get(SType, Elts);
  647. }
  648. return llvm::ConstantArray::get(AType, Elts);
  649. }
  650. llvm::Constant *EmitRecordInitialization(InitListExpr *ILE) {
  651. return ConstStructBuilder::BuildStruct(CGM, CGF, ILE);
  652. }
  653. llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E) {
  654. return CGM.EmitNullConstant(E->getType());
  655. }
  656. llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
  657. if (ILE->getType()->isArrayType())
  658. return EmitArrayInitialization(ILE);
  659. if (ILE->getType()->isRecordType())
  660. return EmitRecordInitialization(ILE);
  661. return nullptr;
  662. }
  663. llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E) {
  664. if (!E->getConstructor()->isTrivial())
  665. return nullptr;
  666. QualType Ty = E->getType();
  667. // FIXME: We should not have to call getBaseElementType here.
  668. const RecordType *RT =
  669. CGM.getContext().getBaseElementType(Ty)->getAs<RecordType>();
  670. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  671. // If the class doesn't have a trivial destructor, we can't emit it as a
  672. // constant expr.
  673. if (!RD->hasTrivialDestructor())
  674. return nullptr;
  675. // Only copy and default constructors can be trivial.
  676. if (E->getNumArgs()) {
  677. assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
  678. assert(E->getConstructor()->isCopyOrMoveConstructor() &&
  679. "trivial ctor has argument but isn't a copy/move ctor");
  680. Expr *Arg = E->getArg(0);
  681. assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
  682. "argument to copy ctor is of wrong type");
  683. return Visit(Arg);
  684. }
  685. return CGM.EmitNullConstant(Ty);
  686. }
  687. llvm::Constant *VisitStringLiteral(StringLiteral *E) {
  688. return CGM.GetConstantArrayFromStringLiteral(E);
  689. }
  690. llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E) {
  691. // This must be an @encode initializing an array in a static initializer.
  692. // Don't emit it as the address of the string, emit the string data itself
  693. // as an inline array.
  694. std::string Str;
  695. CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
  696. QualType T = E->getType();
  697. if (T->getTypeClass() == Type::TypeOfExpr)
  698. T = cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType();
  699. const ConstantArrayType *CAT = cast<ConstantArrayType>(T);
  700. // Resize the string to the right size, adding zeros at the end, or
  701. // truncating as needed.
  702. Str.resize(CAT->getSize().getZExtValue(), '\0');
  703. return llvm::ConstantDataArray::getString(VMContext, Str, false);
  704. }
  705. llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
  706. return Visit(E->getSubExpr());
  707. }
  708. // Utility methods
  709. llvm::Type *ConvertType(QualType T) {
  710. return CGM.getTypes().ConvertType(T);
  711. }
  712. public:
  713. llvm::Constant *EmitLValue(APValue::LValueBase LVBase) {
  714. if (const ValueDecl *Decl = LVBase.dyn_cast<const ValueDecl*>()) {
  715. if (Decl->hasAttr<WeakRefAttr>())
  716. return CGM.GetWeakRefReference(Decl);
  717. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
  718. return CGM.GetAddrOfFunction(FD);
  719. if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
  720. // We can never refer to a variable with local storage.
  721. if (!VD->hasLocalStorage()) {
  722. if (VD->isFileVarDecl() || VD->hasExternalStorage())
  723. return CGM.GetAddrOfGlobalVar(VD);
  724. else if (VD->isLocalVarDecl())
  725. return CGM.getOrCreateStaticVarDecl(
  726. *VD, CGM.getLLVMLinkageVarDefinition(VD, /*isConstant=*/false));
  727. }
  728. }
  729. return nullptr;
  730. }
  731. Expr *E = const_cast<Expr*>(LVBase.get<const Expr*>());
  732. switch (E->getStmtClass()) {
  733. default: break;
  734. case Expr::CompoundLiteralExprClass: {
  735. // Note that due to the nature of compound literals, this is guaranteed
  736. // to be the only use of the variable, so we just generate it here.
  737. CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
  738. llvm::Constant* C = CGM.EmitConstantExpr(CLE->getInitializer(),
  739. CLE->getType(), CGF);
  740. // FIXME: "Leaked" on failure.
  741. if (C)
  742. C = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
  743. E->getType().isConstant(CGM.getContext()),
  744. llvm::GlobalValue::InternalLinkage,
  745. C, ".compoundliteral", nullptr,
  746. llvm::GlobalVariable::NotThreadLocal,
  747. CGM.getContext().getTargetAddressSpace(E->getType()));
  748. return C;
  749. }
  750. case Expr::StringLiteralClass:
  751. return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
  752. case Expr::ObjCEncodeExprClass:
  753. return CGM.GetAddrOfConstantStringFromObjCEncode(cast<ObjCEncodeExpr>(E));
  754. case Expr::ObjCStringLiteralClass: {
  755. ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
  756. llvm::Constant *C =
  757. CGM.getObjCRuntime().GenerateConstantString(SL->getString());
  758. return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
  759. }
  760. case Expr::PredefinedExprClass: {
  761. unsigned Type = cast<PredefinedExpr>(E)->getIdentType();
  762. if (CGF) {
  763. LValue Res = CGF->EmitPredefinedLValue(cast<PredefinedExpr>(E));
  764. return cast<llvm::Constant>(Res.getAddress());
  765. } else if (Type == PredefinedExpr::PrettyFunction) {
  766. return CGM.GetAddrOfConstantCString("top level", ".tmp");
  767. }
  768. return CGM.GetAddrOfConstantCString("", ".tmp");
  769. }
  770. case Expr::AddrLabelExprClass: {
  771. assert(CGF && "Invalid address of label expression outside function.");
  772. llvm::Constant *Ptr =
  773. CGF->GetAddrOfLabel(cast<AddrLabelExpr>(E)->getLabel());
  774. return llvm::ConstantExpr::getBitCast(Ptr, ConvertType(E->getType()));
  775. }
  776. case Expr::CallExprClass: {
  777. CallExpr* CE = cast<CallExpr>(E);
  778. unsigned builtin = CE->getBuiltinCallee();
  779. if (builtin !=
  780. Builtin::BI__builtin___CFStringMakeConstantString &&
  781. builtin !=
  782. Builtin::BI__builtin___NSStringMakeConstantString)
  783. break;
  784. const Expr *Arg = CE->getArg(0)->IgnoreParenCasts();
  785. const StringLiteral *Literal = cast<StringLiteral>(Arg);
  786. if (builtin ==
  787. Builtin::BI__builtin___NSStringMakeConstantString) {
  788. return CGM.getObjCRuntime().GenerateConstantString(Literal);
  789. }
  790. // FIXME: need to deal with UCN conversion issues.
  791. return CGM.GetAddrOfConstantCFString(Literal);
  792. }
  793. case Expr::BlockExprClass: {
  794. std::string FunctionName;
  795. if (CGF)
  796. FunctionName = CGF->CurFn->getName();
  797. else
  798. FunctionName = "global";
  799. return CGM.GetAddrOfGlobalBlock(cast<BlockExpr>(E), FunctionName.c_str());
  800. }
  801. case Expr::CXXTypeidExprClass: {
  802. CXXTypeidExpr *Typeid = cast<CXXTypeidExpr>(E);
  803. QualType T;
  804. if (Typeid->isTypeOperand())
  805. T = Typeid->getTypeOperand(CGM.getContext());
  806. else
  807. T = Typeid->getExprOperand()->getType();
  808. return CGM.GetAddrOfRTTIDescriptor(T);
  809. }
  810. case Expr::CXXUuidofExprClass: {
  811. return CGM.GetAddrOfUuidDescriptor(cast<CXXUuidofExpr>(E));
  812. }
  813. case Expr::MaterializeTemporaryExprClass: {
  814. MaterializeTemporaryExpr *MTE = cast<MaterializeTemporaryExpr>(E);
  815. assert(MTE->getStorageDuration() == SD_Static);
  816. SmallVector<const Expr *, 2> CommaLHSs;
  817. SmallVector<SubobjectAdjustment, 2> Adjustments;
  818. const Expr *Inner = MTE->GetTemporaryExpr()
  819. ->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
  820. return CGM.GetAddrOfGlobalTemporary(MTE, Inner);
  821. }
  822. }
  823. return nullptr;
  824. }
  825. };
  826. } // end anonymous namespace.
  827. llvm::Constant *CodeGenModule::EmitConstantInit(const VarDecl &D,
  828. CodeGenFunction *CGF) {
  829. // Make a quick check if variable can be default NULL initialized
  830. // and avoid going through rest of code which may do, for c++11,
  831. // initialization of memory to all NULLs.
  832. if (!D.hasLocalStorage()) {
  833. QualType Ty = D.getType();
  834. if (Ty->isArrayType())
  835. Ty = Context.getBaseElementType(Ty);
  836. if (Ty->isRecordType())
  837. if (const CXXConstructExpr *E =
  838. dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
  839. const CXXConstructorDecl *CD = E->getConstructor();
  840. if (CD->isTrivial() && CD->isDefaultConstructor())
  841. return EmitNullConstant(D.getType());
  842. }
  843. }
  844. if (const APValue *Value = D.evaluateValue())
  845. return EmitConstantValueForMemory(*Value, D.getType(), CGF);
  846. // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
  847. // reference is a constant expression, and the reference binds to a temporary,
  848. // then constant initialization is performed. ConstExprEmitter will
  849. // incorrectly emit a prvalue constant in this case, and the calling code
  850. // interprets that as the (pointer) value of the reference, rather than the
  851. // desired value of the referee.
  852. if (D.getType()->isReferenceType())
  853. return nullptr;
  854. const Expr *E = D.getInit();
  855. assert(E && "No initializer to emit");
  856. llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
  857. if (C && C->getType()->isIntegerTy(1)) {
  858. llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
  859. C = llvm::ConstantExpr::getZExt(C, BoolTy);
  860. }
  861. return C;
  862. }
  863. llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
  864. QualType DestType,
  865. CodeGenFunction *CGF) {
  866. Expr::EvalResult Result;
  867. bool Success = false;
  868. if (DestType->isReferenceType())
  869. Success = E->EvaluateAsLValue(Result, Context);
  870. else
  871. Success = E->EvaluateAsRValue(Result, Context);
  872. llvm::Constant *C = nullptr;
  873. if (Success && !Result.HasSideEffects)
  874. C = EmitConstantValue(Result.Val, DestType, CGF);
  875. else
  876. C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
  877. if (C && C->getType()->isIntegerTy(1)) {
  878. llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
  879. C = llvm::ConstantExpr::getZExt(C, BoolTy);
  880. }
  881. return C;
  882. }
  883. llvm::Constant *CodeGenModule::EmitConstantValue(const APValue &Value,
  884. QualType DestType,
  885. CodeGenFunction *CGF) {
  886. // For an _Atomic-qualified constant, we may need to add tail padding.
  887. if (auto *AT = DestType->getAs<AtomicType>()) {
  888. QualType InnerType = AT->getValueType();
  889. auto *Inner = EmitConstantValue(Value, InnerType, CGF);
  890. uint64_t InnerSize = Context.getTypeSize(InnerType);
  891. uint64_t OuterSize = Context.getTypeSize(DestType);
  892. if (InnerSize == OuterSize)
  893. return Inner;
  894. assert(InnerSize < OuterSize && "emitted over-large constant for atomic");
  895. llvm::Constant *Elts[] = {
  896. Inner,
  897. llvm::ConstantAggregateZero::get(
  898. llvm::ArrayType::get(Int8Ty, (OuterSize - InnerSize) / 8))
  899. };
  900. return llvm::ConstantStruct::getAnon(Elts);
  901. }
  902. switch (Value.getKind()) {
  903. case APValue::Uninitialized:
  904. llvm_unreachable("Constant expressions should be initialized.");
  905. case APValue::LValue: {
  906. llvm::Type *DestTy = getTypes().ConvertTypeForMem(DestType);
  907. llvm::Constant *Offset =
  908. llvm::ConstantInt::get(Int64Ty, Value.getLValueOffset().getQuantity());
  909. llvm::Constant *C;
  910. if (APValue::LValueBase LVBase = Value.getLValueBase()) {
  911. // An array can be represented as an lvalue referring to the base.
  912. if (isa<llvm::ArrayType>(DestTy)) {
  913. assert(Offset->isNullValue() && "offset on array initializer");
  914. return ConstExprEmitter(*this, CGF).Visit(
  915. const_cast<Expr*>(LVBase.get<const Expr*>()));
  916. }
  917. C = ConstExprEmitter(*this, CGF).EmitLValue(LVBase);
  918. // Apply offset if necessary.
  919. if (!Offset->isNullValue()) {
  920. unsigned AS = C->getType()->getPointerAddressSpace();
  921. llvm::Type *CharPtrTy = Int8Ty->getPointerTo(AS);
  922. llvm::Constant *Casted = llvm::ConstantExpr::getBitCast(C, CharPtrTy);
  923. Casted = llvm::ConstantExpr::getGetElementPtr(Int8Ty, Casted, Offset);
  924. C = llvm::ConstantExpr::getPointerCast(Casted, C->getType());
  925. }
  926. // Convert to the appropriate type; this could be an lvalue for
  927. // an integer.
  928. if (isa<llvm::PointerType>(DestTy))
  929. return llvm::ConstantExpr::getPointerCast(C, DestTy);
  930. return llvm::ConstantExpr::getPtrToInt(C, DestTy);
  931. } else {
  932. C = Offset;
  933. // Convert to the appropriate type; this could be an lvalue for
  934. // an integer.
  935. if (isa<llvm::PointerType>(DestTy))
  936. return llvm::ConstantExpr::getIntToPtr(C, DestTy);
  937. // If the types don't match this should only be a truncate.
  938. if (C->getType() != DestTy)
  939. return llvm::ConstantExpr::getTrunc(C, DestTy);
  940. return C;
  941. }
  942. }
  943. case APValue::Int:
  944. return llvm::ConstantInt::get(VMContext, Value.getInt());
  945. case APValue::ComplexInt: {
  946. llvm::Constant *Complex[2];
  947. Complex[0] = llvm::ConstantInt::get(VMContext,
  948. Value.getComplexIntReal());
  949. Complex[1] = llvm::ConstantInt::get(VMContext,
  950. Value.getComplexIntImag());
  951. // FIXME: the target may want to specify that this is packed.
  952. llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
  953. Complex[1]->getType(),
  954. nullptr);
  955. return llvm::ConstantStruct::get(STy, Complex);
  956. }
  957. case APValue::Float: {
  958. const llvm::APFloat &Init = Value.getFloat();
  959. if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf &&
  960. !Context.getLangOpts().NativeHalfType &&
  961. !Context.getLangOpts().HalfArgsAndReturns)
  962. return llvm::ConstantInt::get(VMContext, Init.bitcastToAPInt());
  963. else
  964. return llvm::ConstantFP::get(VMContext, Init);
  965. }
  966. case APValue::ComplexFloat: {
  967. llvm::Constant *Complex[2];
  968. Complex[0] = llvm::ConstantFP::get(VMContext,
  969. Value.getComplexFloatReal());
  970. Complex[1] = llvm::ConstantFP::get(VMContext,
  971. Value.getComplexFloatImag());
  972. // FIXME: the target may want to specify that this is packed.
  973. llvm::StructType *STy = llvm::StructType::get(Complex[0]->getType(),
  974. Complex[1]->getType(),
  975. nullptr);
  976. return llvm::ConstantStruct::get(STy, Complex);
  977. }
  978. case APValue::Vector: {
  979. SmallVector<llvm::Constant *, 4> Inits;
  980. unsigned NumElts = Value.getVectorLength();
  981. for (unsigned i = 0; i != NumElts; ++i) {
  982. const APValue &Elt = Value.getVectorElt(i);
  983. if (Elt.isInt())
  984. Inits.push_back(llvm::ConstantInt::get(VMContext, Elt.getInt()));
  985. else
  986. Inits.push_back(llvm::ConstantFP::get(VMContext, Elt.getFloat()));
  987. }
  988. return llvm::ConstantVector::get(Inits);
  989. }
  990. case APValue::AddrLabelDiff: {
  991. const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
  992. const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
  993. llvm::Constant *LHS = EmitConstantExpr(LHSExpr, LHSExpr->getType(), CGF);
  994. llvm::Constant *RHS = EmitConstantExpr(RHSExpr, RHSExpr->getType(), CGF);
  995. // Compute difference
  996. llvm::Type *ResultType = getTypes().ConvertType(DestType);
  997. LHS = llvm::ConstantExpr::getPtrToInt(LHS, IntPtrTy);
  998. RHS = llvm::ConstantExpr::getPtrToInt(RHS, IntPtrTy);
  999. llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
  1000. // LLVM is a bit sensitive about the exact format of the
  1001. // address-of-label difference; make sure to truncate after
  1002. // the subtraction.
  1003. return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
  1004. }
  1005. case APValue::Struct:
  1006. case APValue::Union:
  1007. return ConstStructBuilder::BuildStruct(*this, CGF, Value, DestType);
  1008. case APValue::Array: {
  1009. const ArrayType *CAT = Context.getAsArrayType(DestType);
  1010. unsigned NumElements = Value.getArraySize();
  1011. unsigned NumInitElts = Value.getArrayInitializedElts();
  1012. // Emit array filler, if there is one.
  1013. llvm::Constant *Filler = nullptr;
  1014. if (Value.hasArrayFiller())
  1015. Filler = EmitConstantValueForMemory(Value.getArrayFiller(),
  1016. CAT->getElementType(), CGF);
  1017. // Emit initializer elements.
  1018. llvm::Type *CommonElementType =
  1019. getTypes().ConvertType(CAT->getElementType());
  1020. // Try to use a ConstantAggregateZero if we can.
  1021. if (Filler && Filler->isNullValue() && !NumInitElts) {
  1022. llvm::ArrayType *AType =
  1023. llvm::ArrayType::get(CommonElementType, NumElements);
  1024. return llvm::ConstantAggregateZero::get(AType);
  1025. }
  1026. std::vector<llvm::Constant*> Elts;
  1027. Elts.reserve(NumElements);
  1028. for (unsigned I = 0; I < NumElements; ++I) {
  1029. llvm::Constant *C = Filler;
  1030. if (I < NumInitElts)
  1031. C = EmitConstantValueForMemory(Value.getArrayInitializedElt(I),
  1032. CAT->getElementType(), CGF);
  1033. else
  1034. assert(Filler && "Missing filler for implicit elements of initializer");
  1035. if (I == 0)
  1036. CommonElementType = C->getType();
  1037. else if (C->getType() != CommonElementType)
  1038. CommonElementType = nullptr;
  1039. Elts.push_back(C);
  1040. }
  1041. if (!CommonElementType) {
  1042. // FIXME: Try to avoid packing the array
  1043. std::vector<llvm::Type*> Types;
  1044. Types.reserve(NumElements);
  1045. for (unsigned i = 0, e = Elts.size(); i < e; ++i)
  1046. Types.push_back(Elts[i]->getType());
  1047. llvm::StructType *SType = llvm::StructType::get(VMContext, Types, true);
  1048. return llvm::ConstantStruct::get(SType, Elts);
  1049. }
  1050. llvm::ArrayType *AType =
  1051. llvm::ArrayType::get(CommonElementType, NumElements);
  1052. return llvm::ConstantArray::get(AType, Elts);
  1053. }
  1054. case APValue::MemberPointer:
  1055. return getCXXABI().EmitMemberPointer(Value, DestType);
  1056. }
  1057. llvm_unreachable("Unknown APValue kind");
  1058. }
  1059. llvm::Constant *
  1060. CodeGenModule::EmitConstantValueForMemory(const APValue &Value,
  1061. QualType DestType,
  1062. CodeGenFunction *CGF) {
  1063. llvm::Constant *C = EmitConstantValue(Value, DestType, CGF);
  1064. if (C->getType()->isIntegerTy(1)) {
  1065. llvm::Type *BoolTy = getTypes().ConvertTypeForMem(DestType);
  1066. C = llvm::ConstantExpr::getZExt(C, BoolTy);
  1067. }
  1068. return C;
  1069. }
  1070. llvm::Constant *
  1071. CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
  1072. assert(E->isFileScope() && "not a file-scope compound literal expr");
  1073. return ConstExprEmitter(*this, nullptr).EmitLValue(E);
  1074. }
  1075. llvm::Constant *
  1076. CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
  1077. // Member pointer constants always have a very particular form.
  1078. const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
  1079. const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
  1080. // A member function pointer.
  1081. if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
  1082. return getCXXABI().EmitMemberPointer(method);
  1083. // Otherwise, a member data pointer.
  1084. uint64_t fieldOffset = getContext().getFieldOffset(decl);
  1085. CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
  1086. return getCXXABI().EmitMemberDataPointer(type, chars);
  1087. }
  1088. static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
  1089. llvm::Type *baseType,
  1090. const CXXRecordDecl *base);
  1091. static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
  1092. const CXXRecordDecl *record,
  1093. bool asCompleteObject) {
  1094. const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
  1095. llvm::StructType *structure =
  1096. (asCompleteObject ? layout.getLLVMType()
  1097. : layout.getBaseSubobjectLLVMType());
  1098. unsigned numElements = structure->getNumElements();
  1099. std::vector<llvm::Constant *> elements(numElements);
  1100. // Fill in all the bases.
  1101. for (const auto &I : record->bases()) {
  1102. if (I.isVirtual()) {
  1103. // Ignore virtual bases; if we're laying out for a complete
  1104. // object, we'll lay these out later.
  1105. continue;
  1106. }
  1107. const CXXRecordDecl *base =
  1108. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1109. // Ignore empty bases.
  1110. if (base->isEmpty())
  1111. continue;
  1112. unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
  1113. llvm::Type *baseType = structure->getElementType(fieldIndex);
  1114. elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
  1115. }
  1116. // Fill in all the fields.
  1117. for (const auto *Field : record->fields()) {
  1118. // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
  1119. // will fill in later.)
  1120. if (!Field->isBitField()) {
  1121. unsigned fieldIndex = layout.getLLVMFieldNo(Field);
  1122. elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
  1123. }
  1124. // For unions, stop after the first named field.
  1125. if (record->isUnion()) {
  1126. if (Field->getIdentifier())
  1127. break;
  1128. if (const auto *FieldRD =
  1129. dyn_cast_or_null<RecordDecl>(Field->getType()->getAsTagDecl()))
  1130. if (FieldRD->findFirstNamedDataMember())
  1131. break;
  1132. }
  1133. }
  1134. // Fill in the virtual bases, if we're working with the complete object.
  1135. if (asCompleteObject) {
  1136. for (const auto &I : record->vbases()) {
  1137. const CXXRecordDecl *base =
  1138. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  1139. // Ignore empty bases.
  1140. if (base->isEmpty())
  1141. continue;
  1142. unsigned fieldIndex = layout.getVirtualBaseIndex(base);
  1143. // We might have already laid this field out.
  1144. if (elements[fieldIndex]) continue;
  1145. llvm::Type *baseType = structure->getElementType(fieldIndex);
  1146. elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
  1147. }
  1148. }
  1149. // Now go through all other fields and zero them out.
  1150. for (unsigned i = 0; i != numElements; ++i) {
  1151. if (!elements[i])
  1152. elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
  1153. }
  1154. return llvm::ConstantStruct::get(structure, elements);
  1155. }
  1156. /// Emit the null constant for a base subobject.
  1157. static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
  1158. llvm::Type *baseType,
  1159. const CXXRecordDecl *base) {
  1160. const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
  1161. // Just zero out bases that don't have any pointer to data members.
  1162. if (baseLayout.isZeroInitializableAsBase())
  1163. return llvm::Constant::getNullValue(baseType);
  1164. // Otherwise, we can just use its null constant.
  1165. return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
  1166. }
  1167. llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
  1168. if (getTypes().isZeroInitializable(T))
  1169. return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
  1170. if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
  1171. llvm::ArrayType *ATy =
  1172. cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
  1173. QualType ElementTy = CAT->getElementType();
  1174. llvm::Constant *Element = EmitNullConstant(ElementTy);
  1175. unsigned NumElements = CAT->getSize().getZExtValue();
  1176. SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
  1177. return llvm::ConstantArray::get(ATy, Array);
  1178. }
  1179. if (const RecordType *RT = T->getAs<RecordType>()) {
  1180. const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
  1181. return ::EmitNullConstant(*this, RD, /*complete object*/ true);
  1182. }
  1183. assert(T->isMemberDataPointerType() &&
  1184. "Should only see pointers to data members here!");
  1185. return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
  1186. }
  1187. llvm::Constant *
  1188. CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
  1189. return ::EmitNullConstant(*this, Record, false);
  1190. }