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
13#include "ABIInfoImpl.h"
14#include "CGCXXABI.h"
15#include "CGObjCRuntime.h"
16#include "CGRecordLayout.h"
17#include "CodeGenFunction.h"
18#include "CodeGenModule.h"
19#include "ConstantEmitter.h"
20#include "TargetInfo.h"
21#include "clang/AST/APValue.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/MatrixUtils.h"
25#include "clang/AST/NSAPI.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/Basic/Builtins.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/Sequence.h"
31#include "llvm/Analysis/ConstantFolding.h"
32#include "llvm/IR/Constants.h"
33#include "llvm/IR/DataLayout.h"
34#include "llvm/IR/Function.h"
35#include "llvm/IR/GlobalVariable.h"
36#include "llvm/Support/SipHash.h"
37#include <optional>
38using namespace clang;
39using namespace CodeGen;
40
41//===----------------------------------------------------------------------===//
42// ConstantAggregateBuilder
43//===----------------------------------------------------------------------===//
44
45namespace {
46class ConstExprEmitter;
47
48llvm::Constant *getPadding(const CodeGenModule &CGM, CharUnits PadSize) {
49 llvm::Type *Ty = CGM.CharTy;
50 if (PadSize > CharUnits::One())
51 Ty = llvm::ArrayType::get(ElementType: Ty, NumElements: PadSize.getQuantity());
52 if (CGM.shouldZeroInitPadding()) {
53 return llvm::Constant::getNullValue(Ty);
54 }
55 return llvm::UndefValue::get(T: Ty);
56}
57
58struct ConstantAggregateBuilderUtils {
59 CodeGenModule &CGM;
60
61 ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
62
63 CharUnits getAlignment(const llvm::Constant *C) const {
64 return CharUnits::fromQuantity(
65 Quantity: CGM.getDataLayout().getABITypeAlign(Ty: C->getType()));
66 }
67
68 CharUnits getSize(llvm::Type *Ty) const {
69 return CharUnits::fromQuantity(Quantity: CGM.getDataLayout().getTypeAllocSize(Ty));
70 }
71
72 CharUnits getSize(const llvm::Constant *C) const {
73 return getSize(Ty: C->getType());
74 }
75
76 llvm::Constant *getPadding(CharUnits PadSize) const {
77 return ::getPadding(CGM, PadSize);
78 }
79
80 llvm::Constant *getZeroes(CharUnits ZeroSize) const {
81 llvm::Type *Ty = llvm::ArrayType::get(ElementType: CGM.CharTy, NumElements: ZeroSize.getQuantity());
82 return llvm::ConstantAggregateZero::get(Ty);
83 }
84};
85
86/// Incremental builder for an llvm::Constant* holding a struct or array
87/// constant.
88class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils {
89 /// The elements of the constant. These two arrays must have the same size;
90 /// Offsets[i] describes the offset of Elems[i] within the constant. The
91 /// elements are kept in increasing offset order, and we ensure that there
92 /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]).
93 ///
94 /// This may contain explicit padding elements (in order to create a
95 /// natural layout), but need not. Gaps between elements are implicitly
96 /// considered to be filled with undef.
97 llvm::SmallVector<llvm::Constant*, 32> Elems;
98 llvm::SmallVector<CharUnits, 32> Offsets;
99
100 /// The size of the constant (the maximum end offset of any added element).
101 /// May be larger than the end of Elems.back() if we split the last element
102 /// and removed some trailing undefs.
103 CharUnits Size = CharUnits::Zero();
104
105 /// This is true only if laying out Elems in order as the elements of a
106 /// non-packed LLVM struct will give the correct layout.
107 bool NaturalLayout = true;
108
109 bool split(size_t Index, CharUnits Hint);
110 std::optional<size_t> splitAt(CharUnits Pos);
111
112 static llvm::Constant *buildFrom(CodeGenModule &CGM,
113 ArrayRef<llvm::Constant *> Elems,
114 ArrayRef<CharUnits> Offsets,
115 CharUnits StartOffset, CharUnits Size,
116 bool NaturalLayout, llvm::Type *DesiredTy,
117 bool AllowOversized);
118
119public:
120 ConstantAggregateBuilder(CodeGenModule &CGM)
121 : ConstantAggregateBuilderUtils(CGM) {}
122
123 /// Update or overwrite the value starting at \p Offset with \c C.
124 ///
125 /// \param AllowOverwrite If \c true, this constant might overwrite (part of)
126 /// a constant that has already been added. This flag is only used to
127 /// detect bugs.
128 bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite);
129
130 /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits.
131 bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite);
132
133 /// Attempt to condense the value starting at \p Offset to a constant of type
134 /// \p DesiredTy.
135 void condense(CharUnits Offset, llvm::Type *DesiredTy);
136
137 /// Produce a constant representing the entire accumulated value, ideally of
138 /// the specified type. If \p AllowOversized, the constant might be larger
139 /// than implied by \p DesiredTy (eg, if there is a flexible array member).
140 /// Otherwise, the constant will be of exactly the same size as \p DesiredTy
141 /// even if we can't represent it as that type.
142 llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const {
143 return buildFrom(CGM, Elems, Offsets, StartOffset: CharUnits::Zero(), Size,
144 NaturalLayout, DesiredTy, AllowOversized);
145 }
146};
147
148template<typename Container, typename Range = std::initializer_list<
149 typename Container::value_type>>
150static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) {
151 assert(BeginOff <= EndOff && "invalid replacement range");
152 llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals);
153}
154
155bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset,
156 bool AllowOverwrite) {
157 // Common case: appending to a layout.
158 if (Offset >= Size) {
159 CharUnits Align = getAlignment(C);
160 CharUnits AlignedSize = Size.alignTo(Align);
161 if (AlignedSize > Offset || Offset.alignTo(Align) != Offset)
162 NaturalLayout = false;
163 else if (AlignedSize < Offset) {
164 Elems.push_back(Elt: getPadding(PadSize: Offset - Size));
165 Offsets.push_back(Elt: Size);
166 }
167 Elems.push_back(Elt: C);
168 Offsets.push_back(Elt: Offset);
169 Size = Offset + getSize(C);
170 return true;
171 }
172
173 // Uncommon case: constant overlaps what we've already created.
174 std::optional<size_t> FirstElemToReplace = splitAt(Pos: Offset);
175 if (!FirstElemToReplace)
176 return false;
177
178 CharUnits CSize = getSize(C);
179 std::optional<size_t> LastElemToReplace = splitAt(Pos: Offset + CSize);
180 if (!LastElemToReplace)
181 return false;
182
183 assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) &&
184 "unexpectedly overwriting field");
185
186 replace(C&: Elems, BeginOff: *FirstElemToReplace, EndOff: *LastElemToReplace, Vals: {C});
187 replace(C&: Offsets, BeginOff: *FirstElemToReplace, EndOff: *LastElemToReplace, Vals: {Offset});
188 Size = std::max(a: Size, b: Offset + CSize);
189 NaturalLayout = false;
190 return true;
191}
192
193bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits,
194 bool AllowOverwrite) {
195 const ASTContext &Context = CGM.getContext();
196 const uint64_t CharWidth = CGM.getContext().getCharWidth();
197
198 // Offset of where we want the first bit to go within the bits of the
199 // current char.
200 unsigned OffsetWithinChar = OffsetInBits % CharWidth;
201
202 // We split bit-fields up into individual bytes. Walk over the bytes and
203 // update them.
204 for (CharUnits OffsetInChars =
205 Context.toCharUnitsFromBits(BitSize: OffsetInBits - OffsetWithinChar);
206 /**/; ++OffsetInChars) {
207 // Number of bits we want to fill in this char.
208 unsigned WantedBits =
209 std::min(a: (uint64_t)Bits.getBitWidth(), b: CharWidth - OffsetWithinChar);
210
211 // Get a char containing the bits we want in the right places. The other
212 // bits have unspecified values.
213 llvm::APInt BitsThisChar = Bits;
214 if (BitsThisChar.getBitWidth() < CharWidth)
215 BitsThisChar = BitsThisChar.zext(width: CharWidth);
216 if (CGM.getDataLayout().isBigEndian()) {
217 // Figure out how much to shift by. We may need to left-shift if we have
218 // less than one byte of Bits left.
219 int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar;
220 if (Shift > 0)
221 BitsThisChar.lshrInPlace(ShiftAmt: Shift);
222 else if (Shift < 0)
223 BitsThisChar = BitsThisChar.shl(shiftAmt: -Shift);
224 } else {
225 BitsThisChar = BitsThisChar.shl(shiftAmt: OffsetWithinChar);
226 }
227 if (BitsThisChar.getBitWidth() > CharWidth)
228 BitsThisChar = BitsThisChar.trunc(width: CharWidth);
229
230 if (WantedBits == CharWidth) {
231 // Got a full byte: just add it directly.
232 add(C: llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: BitsThisChar),
233 Offset: OffsetInChars, AllowOverwrite);
234 } else {
235 // Partial byte: update the existing integer if there is one. If we
236 // can't split out a 1-CharUnit range to update, then we can't add
237 // these bits and fail the entire constant emission.
238 std::optional<size_t> FirstElemToUpdate = splitAt(Pos: OffsetInChars);
239 if (!FirstElemToUpdate)
240 return false;
241 std::optional<size_t> LastElemToUpdate =
242 splitAt(Pos: OffsetInChars + CharUnits::One());
243 if (!LastElemToUpdate)
244 return false;
245 assert(*LastElemToUpdate - *FirstElemToUpdate < 2 &&
246 "should have at most one element covering one byte");
247
248 // Figure out which bits we want and discard the rest.
249 llvm::APInt UpdateMask(CharWidth, 0);
250 if (CGM.getDataLayout().isBigEndian())
251 UpdateMask.setBits(loBit: CharWidth - OffsetWithinChar - WantedBits,
252 hiBit: CharWidth - OffsetWithinChar);
253 else
254 UpdateMask.setBits(loBit: OffsetWithinChar, hiBit: OffsetWithinChar + WantedBits);
255 BitsThisChar &= UpdateMask;
256
257 if (*FirstElemToUpdate == *LastElemToUpdate ||
258 Elems[*FirstElemToUpdate]->isNullValue() ||
259 isa<llvm::UndefValue>(Val: Elems[*FirstElemToUpdate])) {
260 // All existing bits are either zero or undef.
261 add(C: llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: BitsThisChar),
262 Offset: OffsetInChars, /*AllowOverwrite*/ true);
263 } else {
264 llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate];
265 // In order to perform a partial update, we need the existing bitwise
266 // value, which we can only extract for a constant int.
267 auto *CI = dyn_cast<llvm::ConstantInt>(Val: ToUpdate);
268 if (!CI)
269 return false;
270 // Because this is a 1-CharUnit range, the constant occupying it must
271 // be exactly one CharUnit wide.
272 assert(CI->getBitWidth() == CharWidth && "splitAt failed");
273 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
274 "unexpectedly overwriting bitfield");
275 BitsThisChar |= (CI->getValue() & ~UpdateMask);
276 ToUpdate = llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: BitsThisChar);
277 }
278 }
279
280 // Stop if we've added all the bits.
281 if (WantedBits == Bits.getBitWidth())
282 break;
283
284 // Remove the consumed bits from Bits.
285 if (!CGM.getDataLayout().isBigEndian())
286 Bits.lshrInPlace(ShiftAmt: WantedBits);
287 Bits = Bits.trunc(width: Bits.getBitWidth() - WantedBits);
288
289 // The remanining bits go at the start of the following bytes.
290 OffsetWithinChar = 0;
291 }
292
293 return true;
294}
295
296/// Returns a position within Elems and Offsets such that all elements
297/// before the returned index end before Pos and all elements at or after
298/// the returned index begin at or after Pos. Splits elements as necessary
299/// to ensure this. Returns std::nullopt if we find something we can't split.
300std::optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) {
301 if (Pos >= Size)
302 return Offsets.size();
303
304 while (true) {
305 auto FirstAfterPos = llvm::upper_bound(Range&: Offsets, Value&: Pos);
306 if (FirstAfterPos == Offsets.begin())
307 return 0;
308
309 // If we already have an element starting at Pos, we're done.
310 size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1;
311 if (Offsets[LastAtOrBeforePosIndex] == Pos)
312 return LastAtOrBeforePosIndex;
313
314 // We found an element starting before Pos. Check for overlap.
315 if (Offsets[LastAtOrBeforePosIndex] +
316 getSize(C: Elems[LastAtOrBeforePosIndex]) <= Pos)
317 return LastAtOrBeforePosIndex + 1;
318
319 // Try to decompose it into smaller constants.
320 if (!split(Index: LastAtOrBeforePosIndex, Hint: Pos))
321 return std::nullopt;
322 }
323}
324
325/// Split the constant at index Index, if possible. Return true if we did.
326/// Hint indicates the location at which we'd like to split, but may be
327/// ignored.
328bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) {
329 NaturalLayout = false;
330 llvm::Constant *C = Elems[Index];
331 CharUnits Offset = Offsets[Index];
332
333 if (auto *CA = dyn_cast<llvm::ConstantAggregate>(Val: C)) {
334 // Expand the sequence into its contained elements.
335 // FIXME: This assumes vector elements are byte-sized.
336 replace(C&: Elems, BeginOff: Index, EndOff: Index + 1,
337 Vals: llvm::map_range(C: llvm::seq(Begin: 0u, End: CA->getNumOperands()),
338 F: [&](unsigned Op) { return CA->getOperand(i_nocapture: Op); }));
339 if (isa<llvm::ArrayType>(Val: CA->getType()) ||
340 isa<llvm::VectorType>(Val: CA->getType())) {
341 // Array or vector.
342 llvm::Type *ElemTy =
343 llvm::GetElementPtrInst::getTypeAtIndex(Ty: CA->getType(), Idx: (uint64_t)0);
344 CharUnits ElemSize = getSize(Ty: ElemTy);
345 replace(
346 C&: Offsets, BeginOff: Index, EndOff: Index + 1,
347 Vals: llvm::map_range(C: llvm::seq(Begin: 0u, End: CA->getNumOperands()),
348 F: [&](unsigned Op) { return Offset + Op * ElemSize; }));
349 } else {
350 // Must be a struct.
351 auto *ST = cast<llvm::StructType>(Val: CA->getType());
352 const llvm::StructLayout *Layout =
353 CGM.getDataLayout().getStructLayout(Ty: ST);
354 replace(C&: Offsets, BeginOff: Index, EndOff: Index + 1,
355 Vals: llvm::map_range(
356 C: llvm::seq(Begin: 0u, End: CA->getNumOperands()), F: [&](unsigned Op) {
357 return Offset + CharUnits::fromQuantity(
358 Quantity: Layout->getElementOffset(Idx: Op));
359 }));
360 }
361 return true;
362 }
363
364 if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(Val: C)) {
365 // Expand the sequence into its contained elements.
366 // FIXME: This assumes vector elements are byte-sized.
367 // FIXME: If possible, split into two ConstantDataSequentials at Hint.
368 CharUnits ElemSize = getSize(Ty: CDS->getElementType());
369 replace(C&: Elems, BeginOff: Index, EndOff: Index + 1,
370 Vals: llvm::map_range(C: llvm::seq(Begin: uint64_t(0u), End: CDS->getNumElements()),
371 F: [&](uint64_t Elem) {
372 return CDS->getElementAsConstant(i: Elem);
373 }));
374 replace(C&: Offsets, BeginOff: Index, EndOff: Index + 1,
375 Vals: llvm::map_range(
376 C: llvm::seq(Begin: uint64_t(0u), End: CDS->getNumElements()),
377 F: [&](uint64_t Elem) { return Offset + Elem * ElemSize; }));
378 return true;
379 }
380
381 if (isa<llvm::ConstantAggregateZero>(Val: C)) {
382 // Split into two zeros at the hinted offset.
383 CharUnits ElemSize = getSize(C);
384 assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
385 replace(C&: Elems, BeginOff: Index, EndOff: Index + 1,
386 Vals: {getZeroes(ZeroSize: Hint - Offset), getZeroes(ZeroSize: Offset + ElemSize - Hint)});
387 replace(C&: Offsets, BeginOff: Index, EndOff: Index + 1, Vals: {Offset, Hint});
388 return true;
389 }
390
391 if (isa<llvm::UndefValue>(Val: C)) {
392 // Drop undef; it doesn't contribute to the final layout.
393 replace(C&: Elems, BeginOff: Index, EndOff: Index + 1, Vals: {});
394 replace(C&: Offsets, BeginOff: Index, EndOff: Index + 1, Vals: {});
395 return true;
396 }
397
398 // FIXME: We could split a ConstantInt if the need ever arose.
399 // We don't need to do this to handle bit-fields because we always eagerly
400 // split them into 1-byte chunks.
401
402 return false;
403}
404
405static llvm::Constant *
406EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
407 llvm::Type *CommonElementType, uint64_t ArrayBound,
408 SmallVectorImpl<llvm::Constant *> &Elements,
409 llvm::Constant *Filler);
410
411llvm::Constant *ConstantAggregateBuilder::buildFrom(
412 CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems,
413 ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size,
414 bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) {
415 ConstantAggregateBuilderUtils Utils(CGM);
416
417 if (Elems.empty())
418 return llvm::UndefValue::get(T: DesiredTy);
419
420 auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; };
421
422 // If we want an array type, see if all the elements are the same type and
423 // appropriately spaced.
424 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Val: DesiredTy)) {
425 assert(!AllowOversized && "oversized array emission not supported");
426
427 bool CanEmitArray = true;
428 llvm::Type *CommonType = Elems[0]->getType();
429 llvm::Constant *Filler = llvm::Constant::getNullValue(Ty: CommonType);
430 CharUnits ElemSize = Utils.getSize(Ty: ATy->getElementType());
431 SmallVector<llvm::Constant*, 32> ArrayElements;
432 for (size_t I = 0; I != Elems.size(); ++I) {
433 // Skip zeroes; we'll use a zero value as our array filler.
434 if (Elems[I]->isNullValue())
435 continue;
436
437 // All remaining elements must be the same type.
438 if (Elems[I]->getType() != CommonType ||
439 !Offset(I).isMultipleOf(N: ElemSize)) {
440 CanEmitArray = false;
441 break;
442 }
443 ArrayElements.resize(N: Offset(I) / ElemSize + 1, NV: Filler);
444 ArrayElements.back() = Elems[I];
445 }
446
447 if (CanEmitArray) {
448 return EmitArrayConstant(CGM, DesiredType: ATy, CommonElementType: CommonType, ArrayBound: ATy->getNumElements(),
449 Elements&: ArrayElements, Filler);
450 }
451
452 // Can't emit as an array, carry on to emit as a struct.
453 }
454
455 // The size of the constant we plan to generate. This is usually just
456 // the size of the initialized type, but in AllowOversized mode (i.e.
457 // flexible array init), it can be larger.
458 CharUnits DesiredSize = Utils.getSize(Ty: DesiredTy);
459 if (Size > DesiredSize) {
460 assert(AllowOversized && "Elems are oversized");
461 DesiredSize = Size;
462 }
463
464 // The natural alignment of an unpacked LLVM struct with the given elements.
465 CharUnits Align = CharUnits::One();
466 for (llvm::Constant *C : Elems)
467 Align = std::max(a: Align, b: Utils.getAlignment(C));
468
469 // The natural size of an unpacked LLVM struct with the given elements.
470 CharUnits AlignedSize = Size.alignTo(Align);
471
472 bool Packed = false;
473 ArrayRef<llvm::Constant*> UnpackedElems = Elems;
474 llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
475 if (DesiredSize < AlignedSize || DesiredSize.alignTo(Align) != DesiredSize) {
476 // The natural layout would be too big; force use of a packed layout.
477 NaturalLayout = false;
478 Packed = true;
479 } else if (DesiredSize > AlignedSize) {
480 // The natural layout would be too small. Add padding to fix it. (This
481 // is ignored if we choose a packed layout.)
482 UnpackedElemStorage.assign(in_start: Elems.begin(), in_end: Elems.end());
483 UnpackedElemStorage.push_back(Elt: Utils.getPadding(PadSize: DesiredSize - Size));
484 UnpackedElems = UnpackedElemStorage;
485 }
486
487 // If we don't have a natural layout, insert padding as necessary.
488 // As we go, double-check to see if we can actually just emit Elems
489 // as a non-packed struct and do so opportunistically if possible.
490 llvm::SmallVector<llvm::Constant*, 32> PackedElems;
491 if (!NaturalLayout) {
492 CharUnits SizeSoFar = CharUnits::Zero();
493 for (size_t I = 0; I != Elems.size(); ++I) {
494 CharUnits Align = Utils.getAlignment(C: Elems[I]);
495 CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
496 CharUnits DesiredOffset = Offset(I);
497 assert(DesiredOffset >= SizeSoFar && "elements out of order");
498
499 if (DesiredOffset != NaturalOffset)
500 Packed = true;
501 if (DesiredOffset != SizeSoFar)
502 PackedElems.push_back(Elt: Utils.getPadding(PadSize: DesiredOffset - SizeSoFar));
503 PackedElems.push_back(Elt: Elems[I]);
504 SizeSoFar = DesiredOffset + Utils.getSize(C: Elems[I]);
505 }
506 // If we're using the packed layout, pad it out to the desired size if
507 // necessary.
508 if (Packed) {
509 assert(SizeSoFar <= DesiredSize &&
510 "requested size is too small for contents");
511 if (SizeSoFar < DesiredSize)
512 PackedElems.push_back(Elt: Utils.getPadding(PadSize: DesiredSize - SizeSoFar));
513 }
514 }
515
516 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
517 Ctx&: CGM.getLLVMContext(), V: Packed ? PackedElems : UnpackedElems, Packed);
518
519 // Pick the type to use. If the type is layout identical to the desired
520 // type then use it, otherwise use whatever the builder produced for us.
521 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(Val: DesiredTy)) {
522 if (DesiredSTy->isLayoutIdentical(Other: STy))
523 STy = DesiredSTy;
524 }
525
526 return llvm::ConstantStruct::get(T: STy, V: Packed ? PackedElems : UnpackedElems);
527}
528
529void ConstantAggregateBuilder::condense(CharUnits Offset,
530 llvm::Type *DesiredTy) {
531 CharUnits Size = getSize(Ty: DesiredTy);
532
533 std::optional<size_t> FirstElemToReplace = splitAt(Pos: Offset);
534 if (!FirstElemToReplace)
535 return;
536 size_t First = *FirstElemToReplace;
537
538 std::optional<size_t> LastElemToReplace = splitAt(Pos: Offset + Size);
539 if (!LastElemToReplace)
540 return;
541 size_t Last = *LastElemToReplace;
542
543 size_t Length = Last - First;
544 if (Length == 0)
545 return;
546
547 if (Length == 1 && Offsets[First] == Offset &&
548 getSize(C: Elems[First]) == Size) {
549 // Re-wrap single element structs if necessary. Otherwise, leave any single
550 // element constant of the right size alone even if it has the wrong type.
551 auto *STy = dyn_cast<llvm::StructType>(Val: DesiredTy);
552 if (STy && STy->getNumElements() == 1 &&
553 STy->getElementType(N: 0) == Elems[First]->getType())
554 Elems[First] = llvm::ConstantStruct::get(T: STy, Vs: Elems[First]);
555 return;
556 }
557
558 llvm::Constant *Replacement = buildFrom(
559 CGM, Elems: ArrayRef(Elems).slice(N: First, M: Length),
560 Offsets: ArrayRef(Offsets).slice(N: First, M: Length), StartOffset: Offset, Size: getSize(Ty: DesiredTy),
561 /*known to have natural layout=*/NaturalLayout: false, DesiredTy, AllowOversized: false);
562 replace(C&: Elems, BeginOff: First, EndOff: Last, Vals: {Replacement});
563 replace(C&: Offsets, BeginOff: First, EndOff: Last, Vals: {Offset});
564}
565
566//===----------------------------------------------------------------------===//
567// ConstStructBuilder
568//===----------------------------------------------------------------------===//
569
570class ConstStructBuilder {
571 CodeGenModule &CGM;
572 ConstantEmitter &Emitter;
573 ConstantAggregateBuilder &Builder;
574 CharUnits StartOffset;
575
576public:
577 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
578 const InitListExpr *ILE,
579 QualType StructTy);
580 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
581 const APValue &Value, QualType ValTy);
582 static bool UpdateStruct(ConstantEmitter &Emitter,
583 ConstantAggregateBuilder &Const, CharUnits Offset,
584 const InitListExpr *Updater);
585
586private:
587 ConstStructBuilder(ConstantEmitter &Emitter,
588 ConstantAggregateBuilder &Builder, CharUnits StartOffset)
589 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
590 StartOffset(StartOffset) {}
591
592 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
593 llvm::Constant *InitExpr, bool AllowOverwrite = false);
594
595 bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
596 bool AllowOverwrite = false);
597
598 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
599 llvm::Constant *InitExpr, bool AllowOverwrite = false);
600
601 bool Build(const InitListExpr *ILE, bool AllowOverwrite);
602 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
603 const CXXRecordDecl *VTableClass, CharUnits BaseOffset,
604 bool IsCompleteClass = true);
605 bool DoZeroInitPadding(const ASTRecordLayout &Layout, unsigned FieldNo,
606 const FieldDecl &Field, bool AllowOverwrite,
607 CharUnits &SizeSoFar, bool &ZeroFieldSize);
608 bool DoZeroInitPadding(const ASTRecordLayout &Layout, bool AllowOverwrite,
609 CharUnits SizeSoFar);
610 llvm::Constant *Finalize(QualType Ty);
611};
612
613bool ConstStructBuilder::AppendField(
614 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
615 bool AllowOverwrite) {
616 const ASTContext &Context = CGM.getContext();
617
618 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(BitSize: FieldOffset);
619
620 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
621}
622
623bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
624 llvm::Constant *InitCst,
625 bool AllowOverwrite) {
626 return Builder.add(C: InitCst, Offset: StartOffset + FieldOffsetInChars, AllowOverwrite);
627}
628
629bool ConstStructBuilder::AppendBitField(const FieldDecl *Field,
630 uint64_t FieldOffset, llvm::Constant *C,
631 bool AllowOverwrite) {
632
633 llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(Val: C);
634 if (!CI) {
635 // Constants for long _BitInt types are sometimes split into individual
636 // bytes. Try to fold these back into an integer constant. If that doesn't
637 // work out, then we are trying to initialize a bitfield with a non-trivial
638 // constant, this must require run-time code.
639 llvm::Type *LoadType =
640 CGM.getTypes().convertTypeForLoadStore(T: Field->getType(), LLVMTy: C->getType());
641 llvm::Constant *FoldedConstant = llvm::ConstantFoldLoadFromConst(
642 C, Ty: LoadType, Offset: llvm::APInt::getZero(numBits: 32), DL: CGM.getDataLayout());
643 CI = dyn_cast_if_present<llvm::ConstantInt>(Val: FoldedConstant);
644 if (!CI)
645 return false;
646 }
647
648 const CGRecordLayout &RL =
649 CGM.getTypes().getCGRecordLayout(Field->getParent());
650 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD: Field);
651 llvm::APInt FieldValue = CI->getValue();
652
653 // Promote the size of FieldValue if necessary
654 // FIXME: This should never occur, but currently it can because initializer
655 // constants are cast to bool, and because clang is not enforcing bitfield
656 // width limits.
657 if (Info.Size > FieldValue.getBitWidth())
658 FieldValue = FieldValue.zext(width: Info.Size);
659
660 // Truncate the size of FieldValue to the bit field size.
661 if (Info.Size < FieldValue.getBitWidth())
662 FieldValue = FieldValue.trunc(width: Info.Size);
663
664 return Builder.addBits(Bits: FieldValue,
665 OffsetInBits: CGM.getContext().toBits(CharSize: StartOffset) + FieldOffset,
666 AllowOverwrite);
667}
668
669static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
670 ConstantAggregateBuilder &Const,
671 CharUnits Offset, QualType Type,
672 const InitListExpr *Updater) {
673 if (Type->isRecordType())
674 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
675
676 auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(T: Type);
677 if (!CAT)
678 return false;
679 QualType ElemType = CAT->getElementType();
680 CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(T: ElemType);
681 llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(T: ElemType);
682
683 llvm::Constant *FillC = nullptr;
684 if (const Expr *Filler = Updater->getArrayFiller()) {
685 if (!isa<NoInitExpr>(Val: Filler)) {
686 FillC = Emitter.tryEmitAbstractForMemory(E: Filler, T: ElemType);
687 if (!FillC)
688 return false;
689 }
690 }
691
692 unsigned NumElementsToUpdate =
693 FillC ? CAT->getZExtSize() : Updater->getNumInits();
694 for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
695 const Expr *Init = nullptr;
696 if (I < Updater->getNumInits())
697 Init = Updater->getInit(Init: I);
698
699 if (!Init && FillC) {
700 if (!Const.add(C: FillC, Offset, AllowOverwrite: true))
701 return false;
702 } else if (!Init || isa<NoInitExpr>(Val: Init)) {
703 continue;
704 } else if (const auto *ChildILE = dyn_cast<InitListExpr>(Val: Init)) {
705 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, Type: ElemType,
706 Updater: ChildILE))
707 return false;
708 // Attempt to reduce the array element to a single constant if necessary.
709 Const.condense(Offset, DesiredTy: ElemTy);
710 } else {
711 llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(E: Init, T: ElemType);
712 if (!Const.add(C: Val, Offset, AllowOverwrite: true))
713 return false;
714 }
715 }
716
717 return true;
718}
719
720bool ConstStructBuilder::Build(const InitListExpr *ILE, bool AllowOverwrite) {
721 auto *RD = ILE->getType()->castAsRecordDecl();
722 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D: RD);
723
724 unsigned FieldNo = -1;
725 unsigned ElementNo = 0;
726
727 // Bail out if we have base classes. We could support these, but they only
728 // arise in C++1z where we will have already constant folded most interesting
729 // cases. FIXME: There are still a few more cases we can handle this way.
730 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Val: RD))
731 if (CXXRD->getNumBases())
732 return false;
733
734 const bool ZeroInitPadding = CGM.shouldZeroInitPadding();
735 bool ZeroFieldSize = false;
736 CharUnits SizeSoFar = CharUnits::Zero();
737
738 for (FieldDecl *Field : RD->fields()) {
739 ++FieldNo;
740
741 // If this is a union, skip all the fields that aren't being initialized.
742 if (RD->isUnion() &&
743 !declaresSameEntity(D1: ILE->getInitializedFieldInUnion(), D2: Field))
744 continue;
745
746 // Don't emit anonymous bitfields.
747 if (Field->isUnnamedBitField())
748 continue;
749
750 // Get the initializer. A struct can include fields without initializers,
751 // we just use explicit null values for them.
752 const Expr *Init = nullptr;
753 if (ElementNo < ILE->getNumInits())
754 Init = ILE->getInit(Init: ElementNo++);
755 if (isa_and_nonnull<NoInitExpr>(Val: Init)) {
756 if (ZeroInitPadding &&
757 !DoZeroInitPadding(Layout, FieldNo, Field: *Field, AllowOverwrite, SizeSoFar,
758 ZeroFieldSize))
759 return false;
760 continue;
761 }
762
763 // Zero-sized fields are not emitted, but their initializers may still
764 // prevent emission of this struct as a constant.
765 if (isEmptyFieldForLayout(Context: CGM.getContext(), FD: Field)) {
766 if (Init && Init->HasSideEffects(Ctx: CGM.getContext()))
767 return false;
768 continue;
769 }
770
771 if (ZeroInitPadding &&
772 !DoZeroInitPadding(Layout, FieldNo, Field: *Field, AllowOverwrite, SizeSoFar,
773 ZeroFieldSize))
774 return false;
775
776 // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
777 // represents additional overwriting of our current constant value, and not
778 // a new constant to emit independently.
779 if (AllowOverwrite &&
780 (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
781 if (auto *SubILE = dyn_cast<InitListExpr>(Val: Init)) {
782 CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
783 BitSize: Layout.getFieldOffset(FieldNo));
784 if (!EmitDesignatedInitUpdater(Emitter, Const&: Builder, Offset: StartOffset + Offset,
785 Type: Field->getType(), Updater: SubILE))
786 return false;
787 // If we split apart the field's value, try to collapse it down to a
788 // single value now.
789 Builder.condense(Offset: StartOffset + Offset,
790 DesiredTy: CGM.getTypes().ConvertTypeForMem(T: Field->getType()));
791 continue;
792 }
793 }
794
795 llvm::Constant *EltInit =
796 Init ? Emitter.tryEmitPrivateForMemory(E: Init, T: Field->getType())
797 : Emitter.emitNullForMemory(T: Field->getType());
798 if (!EltInit)
799 return false;
800
801 if (ZeroInitPadding && ZeroFieldSize)
802 SizeSoFar += CharUnits::fromQuantity(
803 Quantity: CGM.getDataLayout().getTypeAllocSize(Ty: EltInit->getType()));
804
805 if (!Field->isBitField()) {
806 // Handle non-bitfield members.
807 if (!AppendField(Field, FieldOffset: Layout.getFieldOffset(FieldNo), InitCst: EltInit,
808 AllowOverwrite))
809 return false;
810 // After emitting a non-empty field with [[no_unique_address]], we may
811 // need to overwrite its tail padding.
812 if (Field->hasAttr<NoUniqueAddressAttr>())
813 AllowOverwrite = true;
814 } else {
815 // Otherwise we have a bitfield.
816 if (!AppendBitField(Field, FieldOffset: Layout.getFieldOffset(FieldNo), C: EltInit,
817 AllowOverwrite))
818 return false;
819 }
820 }
821
822 if (ZeroInitPadding && !DoZeroInitPadding(Layout, AllowOverwrite, SizeSoFar))
823 return false;
824
825 return true;
826}
827
828namespace {
829struct BaseInfo {
830 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
831 : Decl(Decl), Offset(Offset), Index(Index) {
832 }
833
834 const CXXRecordDecl *Decl;
835 CharUnits Offset;
836 unsigned Index;
837
838 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
839};
840}
841
842bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
843 bool IsPrimaryBase,
844 const CXXRecordDecl *VTableClass,
845 CharUnits Offset, bool IsCompleteClass) {
846 assert(Val.isStruct() || Val.isUnion());
847
848 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(D: RD);
849
850 if (Val.isStruct()) {
851 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(Val: RD)) {
852 // Add a vtable pointer, if we need one and it hasn't already been added.
853 if (Layout.hasOwnVFPtr()) {
854 llvm::Constant *VTableAddressPoint =
855 CGM.getCXXABI().getVTableAddressPoint(Base: BaseSubobject(CD, Offset),
856 VTableClass);
857 if (auto Authentication = CGM.getVTablePointerAuthentication(thisClass: CD)) {
858 VTableAddressPoint = Emitter.tryEmitConstantSignedPointer(
859 Ptr: VTableAddressPoint, Auth: *Authentication);
860 if (!VTableAddressPoint)
861 return false;
862 }
863 if (!AppendBytes(FieldOffsetInChars: Offset, InitCst: VTableAddressPoint))
864 return false;
865 }
866
867 // Accumulate and sort bases, in order to visit them in address order,
868 // which may not be the same as declaration order.
869 SmallVector<BaseInfo, 8> Bases;
870 Bases.reserve(N: Val.getStructNumBases());
871 unsigned BaseNo = 0;
872 for (const CXXBaseSpecifier &Base : CD->bases()) {
873 if (Base.isVirtual())
874 continue;
875 const CXXRecordDecl *BD = Base.getType()->getAsCXXRecordDecl();
876 CharUnits BaseOffset = Layout.getBaseClassOffset(Base: BD);
877 Bases.push_back(Elt: BaseInfo(BD, BaseOffset, BaseNo));
878 ++BaseNo;
879 }
880 llvm::stable_sort(Range&: Bases);
881
882 for (const BaseInfo &Base : Bases) {
883 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
884 if (!Build(Val: Val.getStructBase(i: Base.Index), RD: Base.Decl, IsPrimaryBase,
885 VTableClass, Offset: Offset + Base.Offset, IsCompleteClass: false))
886 return false;
887 }
888
889 if (IsCompleteClass) {
890 Bases.clear();
891 BaseNo = 0;
892 Bases.reserve(N: Val.getStructNumVirtualBases());
893 for (const CXXBaseSpecifier &Base : CD->vbases()) {
894 const CXXRecordDecl *BD = Base.getType()->getAsCXXRecordDecl();
895 CharUnits BaseOffset = Layout.getVBaseClassOffset(VBase: BD);
896 Bases.push_back(Elt: BaseInfo(BD, BaseOffset, BaseNo));
897 ++BaseNo;
898 }
899 llvm::stable_sort(Range&: Bases);
900
901 for (const BaseInfo &Base : Bases) {
902 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
903 if (!Build(Val: Val.getStructVirtualBase(i: Base.Index), RD: Base.Decl,
904 IsPrimaryBase, VTableClass, Offset: Offset + Base.Offset, IsCompleteClass: false))
905 return false;
906 }
907 }
908 }
909 }
910
911 unsigned FieldNo = 0;
912 uint64_t OffsetBits = CGM.getContext().toBits(CharSize: Offset);
913 const bool ZeroInitPadding = CGM.shouldZeroInitPadding();
914 bool ZeroFieldSize = false;
915 CharUnits SizeSoFar = CharUnits::Zero();
916
917 bool AllowOverwrite = false;
918 for (RecordDecl::field_iterator Field = RD->field_begin(),
919 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
920 // If this is a union, skip all the fields that aren't being initialized.
921 if (RD->isUnion() && !declaresSameEntity(D1: Val.getUnionField(), D2: *Field))
922 continue;
923
924 // Don't emit anonymous bitfields or zero-sized fields.
925 if (Field->isUnnamedBitField() ||
926 isEmptyFieldForLayout(Context: CGM.getContext(), FD: *Field))
927 continue;
928
929 // Emit the value of the initializer.
930 const APValue &FieldValue =
931 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(i: FieldNo);
932 llvm::Constant *EltInit =
933 Emitter.tryEmitPrivateForMemory(value: FieldValue, T: Field->getType());
934 if (!EltInit)
935 return false;
936
937 if (CGM.getContext().isPFPField(Field: *Field)) {
938 llvm::ConstantInt *Disc;
939 llvm::Constant *AddrDisc;
940 if (CGM.getContext().arePFPFieldsTriviallyCopyable(RD)) {
941 uint64_t FieldSignature =
942 llvm::getPointerAuthStableSipHash(S: CGM.getPFPFieldName(FD: *Field));
943 Disc = llvm::ConstantInt::get(Ty: CGM.Int64Ty, V: FieldSignature);
944 AddrDisc = llvm::ConstantPointerNull::get(T: CGM.VoidPtrTy);
945 } else if (Emitter.isAbstract()) {
946 // isAbstract means that we don't know the global's address. Since we
947 // can only form a pointer without knowing the address if the fields are
948 // trivially copyable, we need to return false otherwise.
949 return false;
950 } else {
951 Disc = llvm::ConstantInt::get(Ty: CGM.Int64Ty,
952 V: -(Layout.getFieldOffset(FieldNo) / 8));
953 AddrDisc = Emitter.getCurrentAddrPrivate();
954 }
955 EltInit = llvm::ConstantPtrAuth::get(
956 Ptr: EltInit, Key: llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: 2), Disc, AddrDisc,
957 DeactivationSymbol: CGM.getPFPDeactivationSymbol(FD: *Field));
958 if (!CGM.getContext().arePFPFieldsTriviallyCopyable(RD))
959 Emitter.registerCurrentAddrPrivate(signal: EltInit,
960 placeholder: cast<llvm::GlobalValue>(Val: AddrDisc));
961 }
962
963 if (ZeroInitPadding) {
964 if (!DoZeroInitPadding(Layout, FieldNo, Field: **Field, AllowOverwrite,
965 SizeSoFar, ZeroFieldSize))
966 return false;
967 if (ZeroFieldSize)
968 SizeSoFar += CharUnits::fromQuantity(
969 Quantity: CGM.getDataLayout().getTypeAllocSize(Ty: EltInit->getType()));
970 }
971
972 if (!Field->isBitField()) {
973 // Handle non-bitfield members.
974 if (!AppendField(Field: *Field, FieldOffset: Layout.getFieldOffset(FieldNo) + OffsetBits,
975 InitCst: EltInit, AllowOverwrite))
976 return false;
977 // After emitting a non-empty field with [[no_unique_address]], we may
978 // need to overwrite its tail padding.
979 if (Field->hasAttr<NoUniqueAddressAttr>())
980 AllowOverwrite = true;
981 } else {
982 // Otherwise we have a bitfield.
983 if (!AppendBitField(Field: *Field, FieldOffset: Layout.getFieldOffset(FieldNo) + OffsetBits,
984 C: EltInit, AllowOverwrite))
985 return false;
986 }
987 }
988 if (ZeroInitPadding && !DoZeroInitPadding(Layout, AllowOverwrite, SizeSoFar))
989 return false;
990
991 return true;
992}
993
994bool ConstStructBuilder::DoZeroInitPadding(
995 const ASTRecordLayout &Layout, unsigned FieldNo, const FieldDecl &Field,
996 bool AllowOverwrite, CharUnits &SizeSoFar, bool &ZeroFieldSize) {
997 uint64_t StartBitOffset = Layout.getFieldOffset(FieldNo);
998 CharUnits StartOffset = CGM.getContext().toCharUnitsFromBits(BitSize: StartBitOffset);
999 if (SizeSoFar < StartOffset)
1000 if (!AppendBytes(FieldOffsetInChars: SizeSoFar, InitCst: getPadding(CGM, PadSize: StartOffset - SizeSoFar),
1001 AllowOverwrite))
1002 return false;
1003
1004 if (!Field.isBitField()) {
1005 CharUnits FieldSize = CGM.getContext().getTypeSizeInChars(T: Field.getType());
1006 SizeSoFar = StartOffset + FieldSize;
1007 ZeroFieldSize = FieldSize.isZero();
1008 } else {
1009 const CGRecordLayout &RL =
1010 CGM.getTypes().getCGRecordLayout(Field.getParent());
1011 const CGBitFieldInfo &Info = RL.getBitFieldInfo(FD: &Field);
1012 uint64_t EndBitOffset = StartBitOffset + Info.Size;
1013 SizeSoFar = CGM.getContext().toCharUnitsFromBits(BitSize: EndBitOffset);
1014 if (EndBitOffset % CGM.getContext().getCharWidth() != 0) {
1015 SizeSoFar++;
1016 }
1017 ZeroFieldSize = Info.Size == 0;
1018 }
1019 return true;
1020}
1021
1022bool ConstStructBuilder::DoZeroInitPadding(const ASTRecordLayout &Layout,
1023 bool AllowOverwrite,
1024 CharUnits SizeSoFar) {
1025 CharUnits TotalSize = Layout.getSize();
1026 if (SizeSoFar < TotalSize)
1027 if (!AppendBytes(FieldOffsetInChars: SizeSoFar, InitCst: getPadding(CGM, PadSize: TotalSize - SizeSoFar),
1028 AllowOverwrite))
1029 return false;
1030 SizeSoFar = TotalSize;
1031 return true;
1032}
1033
1034llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
1035 Type = Type.getNonReferenceType();
1036 auto *RD = Type->castAsRecordDecl();
1037 llvm::Type *ValTy = CGM.getTypes().ConvertType(T: Type);
1038 return Builder.build(DesiredTy: ValTy, AllowOversized: RD->hasFlexibleArrayMember());
1039}
1040
1041llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
1042 const InitListExpr *ILE,
1043 QualType ValTy) {
1044 ConstantAggregateBuilder Const(Emitter.CGM);
1045 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
1046
1047 if (!Builder.Build(ILE, /*AllowOverwrite*/false))
1048 return nullptr;
1049
1050 return Builder.Finalize(Type: ValTy);
1051}
1052
1053llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
1054 const APValue &Val,
1055 QualType ValTy) {
1056 ConstantAggregateBuilder Const(Emitter.CGM);
1057 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
1058
1059 const auto *RD = ValTy->castAsRecordDecl();
1060 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(Val: RD);
1061 if (!Builder.Build(Val, RD, IsPrimaryBase: false, VTableClass: CD, Offset: CharUnits::Zero()))
1062 return nullptr;
1063
1064 return Builder.Finalize(Type: ValTy);
1065}
1066
1067bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
1068 ConstantAggregateBuilder &Const,
1069 CharUnits Offset,
1070 const InitListExpr *Updater) {
1071 return ConstStructBuilder(Emitter, Const, Offset)
1072 .Build(ILE: Updater, /*AllowOverwrite*/ true);
1073}
1074
1075//===----------------------------------------------------------------------===//
1076// ConstExprEmitter
1077//===----------------------------------------------------------------------===//
1078
1079static ConstantAddress
1080tryEmitGlobalCompoundLiteral(ConstantEmitter &emitter,
1081 const CompoundLiteralExpr *E) {
1082 CodeGenModule &CGM = emitter.CGM;
1083 CharUnits Align = CGM.getContext().getTypeAlignInChars(T: E->getType());
1084 if (llvm::GlobalVariable *Addr =
1085 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
1086 return ConstantAddress(Addr, Addr->getValueType(), Align);
1087
1088 LangAS addressSpace = E->getType().getAddressSpace();
1089 llvm::Constant *C = emitter.tryEmitForInitializer(E: E->getInitializer(),
1090 destAddrSpace: addressSpace, destType: E->getType());
1091 if (!C) {
1092 assert(!E->isFileScope() &&
1093 "file-scope compound literal did not have constant initializer!");
1094 return ConstantAddress::invalid();
1095 }
1096
1097 auto GV = new llvm::GlobalVariable(
1098 CGM.getModule(), C->getType(),
1099 E->getType().isConstantStorage(Ctx: CGM.getContext(), ExcludeCtor: true, ExcludeDtor: false),
1100 llvm::GlobalValue::InternalLinkage, C, ".compoundliteral", nullptr,
1101 llvm::GlobalVariable::NotThreadLocal,
1102 CGM.getContext().getTargetAddressSpace(AS: addressSpace));
1103 emitter.finalize(global: GV);
1104 GV->setAlignment(Align.getAsAlign());
1105 CGM.setAddrOfConstantCompoundLiteral(CLE: E, GV);
1106 return ConstantAddress(GV, GV->getValueType(), Align);
1107}
1108
1109static llvm::Constant *
1110EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
1111 llvm::Type *CommonElementType, uint64_t ArrayBound,
1112 SmallVectorImpl<llvm::Constant *> &Elements,
1113 llvm::Constant *Filler) {
1114 // Figure out how long the initial prefix of non-zero elements is.
1115 uint64_t NonzeroLength = ArrayBound;
1116 if (Elements.size() < NonzeroLength && Filler->isNullValue())
1117 NonzeroLength = Elements.size();
1118 if (NonzeroLength == Elements.size()) {
1119 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
1120 --NonzeroLength;
1121 }
1122
1123 if (NonzeroLength == 0)
1124 return llvm::ConstantAggregateZero::get(Ty: DesiredType);
1125
1126 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
1127 uint64_t TrailingZeroes = ArrayBound - NonzeroLength;
1128 if (TrailingZeroes >= 8) {
1129 assert(Elements.size() >= NonzeroLength &&
1130 "missing initializer for non-zero element");
1131
1132 // If all the elements had the same type up to the trailing zeroes, emit a
1133 // struct of two arrays (the nonzero data and the zeroinitializer).
1134 if (CommonElementType && NonzeroLength >= 8) {
1135 llvm::Constant *Initial = llvm::ConstantArray::get(
1136 T: llvm::ArrayType::get(ElementType: CommonElementType, NumElements: NonzeroLength),
1137 V: ArrayRef(Elements).take_front(N: NonzeroLength));
1138 Elements.resize(N: 2);
1139 Elements[0] = Initial;
1140 } else {
1141 Elements.resize(N: NonzeroLength + 1);
1142 }
1143
1144 auto *FillerType =
1145 CommonElementType ? CommonElementType : DesiredType->getElementType();
1146 FillerType = llvm::ArrayType::get(ElementType: FillerType, NumElements: TrailingZeroes);
1147 Elements.back() = llvm::ConstantAggregateZero::get(Ty: FillerType);
1148 CommonElementType = nullptr;
1149 } else if (Elements.size() != ArrayBound) {
1150 // Otherwise pad to the right size with the filler if necessary.
1151 Elements.resize(N: ArrayBound, NV: Filler);
1152 if (Filler->getType() != CommonElementType)
1153 CommonElementType = nullptr;
1154 }
1155
1156 // If all elements have the same type, just emit an array constant.
1157 if (CommonElementType)
1158 return llvm::ConstantArray::get(
1159 T: llvm::ArrayType::get(ElementType: CommonElementType, NumElements: ArrayBound), V: Elements);
1160
1161 // We have mixed types. Use a packed struct.
1162 llvm::SmallVector<llvm::Type *, 16> Types;
1163 Types.reserve(N: Elements.size());
1164 for (llvm::Constant *Elt : Elements)
1165 Types.push_back(Elt: Elt->getType());
1166 llvm::StructType *SType =
1167 llvm::StructType::get(Context&: CGM.getLLVMContext(), Elements: Types, isPacked: true);
1168 return llvm::ConstantStruct::get(T: SType, V: Elements);
1169}
1170
1171// This class only needs to handle arrays, structs and unions. Outside C++11
1172// mode, we don't currently constant fold those types. All other types are
1173// handled by constant folding.
1174//
1175// Constant folding is currently missing support for a few features supported
1176// here: CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
1177class ConstExprEmitter
1178 : public ConstStmtVisitor<ConstExprEmitter, llvm::Constant *, QualType> {
1179 CodeGenModule &CGM;
1180 ConstantEmitter &Emitter;
1181 llvm::LLVMContext &VMContext;
1182public:
1183 ConstExprEmitter(ConstantEmitter &emitter)
1184 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
1185 }
1186
1187 //===--------------------------------------------------------------------===//
1188 // Visitor Methods
1189 //===--------------------------------------------------------------------===//
1190
1191 llvm::Constant *VisitStmt(const Stmt *S, QualType T) { return nullptr; }
1192
1193 llvm::Constant *VisitConstantExpr(const ConstantExpr *CE, QualType T) {
1194 if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE))
1195 return Result;
1196 return Visit(S: CE->getSubExpr(), P: T);
1197 }
1198
1199 llvm::Constant *VisitParenExpr(const ParenExpr *PE, QualType T) {
1200 return Visit(S: PE->getSubExpr(), P: T);
1201 }
1202
1203 llvm::Constant *
1204 VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *PE,
1205 QualType T) {
1206 return Visit(S: PE->getReplacement(), P: T);
1207 }
1208
1209 llvm::Constant *VisitGenericSelectionExpr(const GenericSelectionExpr *GE,
1210 QualType T) {
1211 return Visit(S: GE->getResultExpr(), P: T);
1212 }
1213
1214 llvm::Constant *VisitChooseExpr(const ChooseExpr *CE, QualType T) {
1215 return Visit(S: CE->getChosenSubExpr(), P: T);
1216 }
1217
1218 llvm::Constant *VisitCompoundLiteralExpr(const CompoundLiteralExpr *E,
1219 QualType T) {
1220 return Visit(S: E->getInitializer(), P: T);
1221 }
1222
1223 llvm::Constant *ProduceIntToIntCast(const Expr *E, QualType DestType) {
1224 QualType FromType = E->getType();
1225 // See also HandleIntToIntCast in ExprConstant.cpp
1226 if (FromType->isIntegerType())
1227 if (llvm::Constant *C = Visit(S: E, P: FromType))
1228 if (auto *CI = dyn_cast<llvm::ConstantInt>(Val: C)) {
1229 unsigned SrcWidth = CGM.getContext().getIntWidth(T: FromType);
1230 unsigned DstWidth = CGM.getContext().getIntWidth(T: DestType);
1231 if (DstWidth == SrcWidth)
1232 return CI;
1233 llvm::APInt A = FromType->isSignedIntegerType()
1234 ? CI->getValue().sextOrTrunc(width: DstWidth)
1235 : CI->getValue().zextOrTrunc(width: DstWidth);
1236 return llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: A);
1237 }
1238 return nullptr;
1239 }
1240
1241 llvm::Constant *VisitCastExpr(const CastExpr *E, QualType destType) {
1242 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(Val: E))
1243 CGM.EmitExplicitCastExprType(E: ECE, CGF: Emitter.CGF);
1244 const Expr *subExpr = E->getSubExpr();
1245
1246 switch (E->getCastKind()) {
1247 case CK_ToUnion: {
1248 // GCC cast to union extension
1249 assert(E->getType()->isUnionType() &&
1250 "Destination type is not union type!");
1251
1252 auto field = E->getTargetUnionField();
1253
1254 auto C = Emitter.tryEmitPrivateForMemory(E: subExpr, T: field->getType());
1255 if (!C) return nullptr;
1256
1257 auto destTy = ConvertType(T: destType);
1258 if (C->getType() == destTy) return C;
1259
1260 // Build a struct with the union sub-element as the first member,
1261 // and padded to the appropriate size.
1262 SmallVector<llvm::Constant*, 2> Elts;
1263 SmallVector<llvm::Type*, 2> Types;
1264 Elts.push_back(Elt: C);
1265 Types.push_back(Elt: C->getType());
1266 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(Ty: C->getType());
1267 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(Ty: destTy);
1268
1269 assert(CurSize <= TotalSize && "Union size mismatch!");
1270 if (unsigned NumPadBytes = TotalSize - CurSize) {
1271 llvm::Constant *Padding =
1272 getPadding(CGM, PadSize: CharUnits::fromQuantity(Quantity: NumPadBytes));
1273 Elts.push_back(Elt: Padding);
1274 Types.push_back(Elt: Padding->getType());
1275 }
1276
1277 llvm::StructType *STy = llvm::StructType::get(Context&: VMContext, Elements: Types, isPacked: false);
1278 return llvm::ConstantStruct::get(T: STy, V: Elts);
1279 }
1280
1281 case CK_AddressSpaceConversion: {
1282 llvm::Constant *C = Emitter.tryEmitPrivate(E: subExpr, T: subExpr->getType());
1283 if (!C)
1284 return nullptr;
1285 llvm::Type *destTy = ConvertType(T: E->getType());
1286 return CGM.performAddrSpaceCast(Src: C, DestTy: destTy);
1287 }
1288
1289 case CK_LValueToRValue: {
1290 // We don't really support doing lvalue-to-rvalue conversions here; any
1291 // interesting conversions should be done in Evaluate(). But as a
1292 // special case, allow compound literals to support the gcc extension
1293 // allowing "struct x {int x;} x = (struct x) {};".
1294 if (const auto *E =
1295 dyn_cast<CompoundLiteralExpr>(Val: subExpr->IgnoreParens()))
1296 return Visit(S: E->getInitializer(), P: destType);
1297 return nullptr;
1298 }
1299
1300 case CK_AtomicToNonAtomic:
1301 case CK_NonAtomicToAtomic:
1302 case CK_NoOp:
1303 case CK_ConstructorConversion:
1304 return Visit(S: subExpr, P: destType);
1305
1306 case CK_ArrayToPointerDecay:
1307 if (const auto *S = dyn_cast<StringLiteral>(Val: subExpr))
1308 return CGM.GetAddrOfConstantStringFromLiteral(S).getPointer();
1309 return nullptr;
1310 case CK_NullToPointer:
1311 if (Visit(S: subExpr, P: destType))
1312 return CGM.EmitNullConstant(T: destType);
1313 return nullptr;
1314
1315 case CK_IntToOCLSampler:
1316 llvm_unreachable("global sampler variables are not generated");
1317
1318 case CK_IntegralCast:
1319 return ProduceIntToIntCast(E: subExpr, DestType: destType);
1320
1321 case CK_Dependent: llvm_unreachable("saw dependent cast!");
1322
1323 case CK_BuiltinFnToFnPtr:
1324 llvm_unreachable("builtin functions are handled elsewhere");
1325
1326 case CK_ReinterpretMemberPointer:
1327 case CK_DerivedToBaseMemberPointer:
1328 case CK_BaseToDerivedMemberPointer: {
1329 auto C = Emitter.tryEmitPrivate(E: subExpr, T: subExpr->getType());
1330 if (!C) return nullptr;
1331 return CGM.getCXXABI().EmitMemberPointerConversion(E, Src: C);
1332 }
1333
1334 // These will never be supported.
1335 case CK_ObjCObjectLValueCast:
1336 case CK_ARCProduceObject:
1337 case CK_ARCConsumeObject:
1338 case CK_ARCReclaimReturnedObject:
1339 case CK_ARCExtendBlockObject:
1340 case CK_CopyAndAutoreleaseBlockObject:
1341 return nullptr;
1342
1343 // These don't need to be handled here because Evaluate knows how to
1344 // evaluate them in the cases where they can be folded.
1345 case CK_BitCast:
1346 case CK_ToVoid:
1347 case CK_Dynamic:
1348 case CK_LValueBitCast:
1349 case CK_LValueToRValueBitCast:
1350 case CK_NullToMemberPointer:
1351 case CK_UserDefinedConversion:
1352 case CK_CPointerToObjCPointerCast:
1353 case CK_BlockPointerToObjCPointerCast:
1354 case CK_AnyPointerToBlockPointerCast:
1355 case CK_FunctionToPointerDecay:
1356 case CK_BaseToDerived:
1357 case CK_DerivedToBase:
1358 case CK_UncheckedDerivedToBase:
1359 case CK_MemberPointerToBoolean:
1360 case CK_VectorSplat:
1361 case CK_FloatingRealToComplex:
1362 case CK_FloatingComplexToReal:
1363 case CK_FloatingComplexToBoolean:
1364 case CK_FloatingComplexCast:
1365 case CK_FloatingComplexToIntegralComplex:
1366 case CK_IntegralRealToComplex:
1367 case CK_IntegralComplexToReal:
1368 case CK_IntegralComplexToBoolean:
1369 case CK_IntegralComplexCast:
1370 case CK_IntegralComplexToFloatingComplex:
1371 case CK_PointerToIntegral:
1372 case CK_PointerToBoolean:
1373 case CK_BooleanToSignedIntegral:
1374 case CK_IntegralToPointer:
1375 case CK_IntegralToBoolean:
1376 case CK_IntegralToFloating:
1377 case CK_FloatingToIntegral:
1378 case CK_FloatingToBoolean:
1379 case CK_FloatingCast:
1380 case CK_FloatingToFixedPoint:
1381 case CK_FixedPointToFloating:
1382 case CK_FixedPointCast:
1383 case CK_FixedPointToBoolean:
1384 case CK_FixedPointToIntegral:
1385 case CK_IntegralToFixedPoint:
1386 case CK_ZeroToOCLOpaqueType:
1387 case CK_MatrixCast:
1388 case CK_HLSLVectorTruncation:
1389 case CK_HLSLMatrixTruncation:
1390 case CK_HLSLArrayRValue:
1391 case CK_HLSLElementwiseCast:
1392 case CK_HLSLAggregateSplatCast:
1393 return nullptr;
1394 }
1395 llvm_unreachable("Invalid CastKind");
1396 }
1397
1398 llvm::Constant *VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *DIE,
1399 QualType T) {
1400 // No need for a DefaultInitExprScope: we don't handle 'this' in a
1401 // constant expression.
1402 return Visit(S: DIE->getExpr(), P: T);
1403 }
1404
1405 llvm::Constant *VisitExprWithCleanups(const ExprWithCleanups *E, QualType T) {
1406 return Visit(S: E->getSubExpr(), P: T);
1407 }
1408
1409 llvm::Constant *VisitIntegerLiteral(const IntegerLiteral *I, QualType T) {
1410 return llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: I->getValue());
1411 }
1412
1413 static APValue withDestType(ASTContext &Ctx, const Expr *E, QualType SrcType,
1414 QualType DestType, const llvm::APSInt &Value) {
1415 if (!Ctx.hasSameType(T1: SrcType, T2: DestType)) {
1416 if (DestType->isFloatingType()) {
1417 llvm::APFloat Result =
1418 llvm::APFloat(Ctx.getFloatTypeSemantics(T: DestType), 1);
1419 llvm::RoundingMode RM =
1420 E->getFPFeaturesInEffect(LO: Ctx.getLangOpts()).getRoundingMode();
1421 if (RM == llvm::RoundingMode::Dynamic)
1422 RM = llvm::RoundingMode::NearestTiesToEven;
1423 Result.convertFromAPInt(Input: Value, IsSigned: Value.isSigned(), RM);
1424 return APValue(Result);
1425 }
1426 }
1427 return APValue(Value);
1428 }
1429
1430 llvm::Constant *EmitArrayInitialization(const InitListExpr *ILE, QualType T) {
1431 auto *CAT = CGM.getContext().getAsConstantArrayType(T: ILE->getType());
1432 assert(CAT && "can't emit array init for non-constant-bound array");
1433 uint64_t NumInitElements = ILE->getNumInits();
1434 const uint64_t NumElements = CAT->getZExtSize();
1435 for (const auto *Init : ILE->inits()) {
1436 if (const auto *Embed =
1437 dyn_cast<EmbedExpr>(Val: Init->IgnoreParenImpCasts())) {
1438 NumInitElements += Embed->getDataElementCount() - 1;
1439 if (NumInitElements > NumElements) {
1440 NumInitElements = NumElements;
1441 break;
1442 }
1443 }
1444 }
1445
1446 // Initialising an array requires us to automatically
1447 // initialise any elements that have not been initialised explicitly
1448 uint64_t NumInitableElts = std::min<uint64_t>(a: NumInitElements, b: NumElements);
1449
1450 QualType EltType = CAT->getElementType();
1451
1452 // Initialize remaining array elements.
1453 llvm::Constant *fillC = nullptr;
1454 if (const Expr *filler = ILE->getArrayFiller()) {
1455 fillC = Emitter.tryEmitAbstractForMemory(E: filler, T: EltType);
1456 if (!fillC)
1457 return nullptr;
1458 }
1459
1460 // Copy initializer elements.
1461 SmallVector<llvm::Constant *, 16> Elts;
1462 if (fillC && fillC->isNullValue())
1463 Elts.reserve(N: NumInitableElts + 1);
1464 else
1465 Elts.reserve(N: NumElements);
1466
1467 llvm::Type *CommonElementType = nullptr;
1468 auto Emit = [&](const Expr *Init, unsigned ArrayIndex) {
1469 llvm::Constant *C = nullptr;
1470 C = Emitter.tryEmitPrivateForMemory(E: Init, T: EltType);
1471 if (!C)
1472 return false;
1473 if (ArrayIndex == 0)
1474 CommonElementType = C->getType();
1475 else if (C->getType() != CommonElementType)
1476 CommonElementType = nullptr;
1477 Elts.push_back(Elt: C);
1478 return true;
1479 };
1480
1481 unsigned ArrayIndex = 0;
1482 QualType DestTy = CAT->getElementType();
1483 for (unsigned i = 0; i < ILE->getNumInits(); ++i) {
1484 const Expr *Init = ILE->getInit(Init: i);
1485 if (auto *EmbedS = dyn_cast<EmbedExpr>(Val: Init->IgnoreParenImpCasts())) {
1486 StringLiteral *SL = EmbedS->getDataStringLiteral();
1487 llvm::APSInt Value(CGM.getContext().getTypeSize(T: DestTy),
1488 DestTy->isUnsignedIntegerType());
1489 llvm::Constant *C;
1490 for (unsigned I = EmbedS->getStartingElementPos(),
1491 N = EmbedS->getDataElementCount();
1492 I != EmbedS->getStartingElementPos() + N; ++I) {
1493 Value = SL->getCodeUnit(i: I);
1494 if (DestTy->isIntegerType()) {
1495 C = llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: Value);
1496 } else {
1497 C = Emitter.tryEmitPrivateForMemory(
1498 value: withDestType(Ctx&: CGM.getContext(), E: Init, SrcType: EmbedS->getType(), DestType: DestTy,
1499 Value),
1500 T: EltType);
1501 }
1502 if (!C)
1503 return nullptr;
1504 Elts.push_back(Elt: C);
1505 ArrayIndex++;
1506 }
1507 if ((ArrayIndex - EmbedS->getDataElementCount()) == 0)
1508 CommonElementType = C->getType();
1509 else if (C->getType() != CommonElementType)
1510 CommonElementType = nullptr;
1511 } else {
1512 if (!Emit(Init, ArrayIndex))
1513 return nullptr;
1514 ArrayIndex++;
1515 }
1516 }
1517
1518 llvm::ArrayType *Desired =
1519 cast<llvm::ArrayType>(Val: CGM.getTypes().ConvertType(T: ILE->getType()));
1520 return EmitArrayConstant(CGM, DesiredType: Desired, CommonElementType, ArrayBound: NumElements, Elements&: Elts,
1521 Filler: fillC);
1522 }
1523
1524 llvm::Constant *EmitRecordInitialization(const InitListExpr *ILE,
1525 QualType T) {
1526 return ConstStructBuilder::BuildStruct(Emitter, ILE, ValTy: T);
1527 }
1528
1529 llvm::Constant *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E,
1530 QualType T) {
1531 return CGM.EmitNullConstant(T);
1532 }
1533
1534 llvm::Constant *VisitInitListExpr(const InitListExpr *ILE, QualType T) {
1535 if (ILE->isTransparent())
1536 return Visit(S: ILE->getInit(Init: 0), P: T);
1537
1538 if (ILE->getType()->isArrayType())
1539 return EmitArrayInitialization(ILE, T);
1540
1541 if (ILE->getType()->isRecordType())
1542 return EmitRecordInitialization(ILE, T);
1543
1544 return nullptr;
1545 }
1546
1547 llvm::Constant *
1548 VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E,
1549 QualType destType) {
1550 auto C = Visit(S: E->getBase(), P: destType);
1551 if (!C)
1552 return nullptr;
1553
1554 ConstantAggregateBuilder Const(CGM);
1555 Const.add(C, Offset: CharUnits::Zero(), AllowOverwrite: false);
1556
1557 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset: CharUnits::Zero(), Type: destType,
1558 Updater: E->getUpdater()))
1559 return nullptr;
1560
1561 llvm::Type *ValTy = CGM.getTypes().ConvertType(T: destType);
1562 bool HasFlexibleArray = false;
1563 if (const auto *RD = destType->getAsRecordDecl())
1564 HasFlexibleArray = RD->hasFlexibleArrayMember();
1565 return Const.build(DesiredTy: ValTy, AllowOversized: HasFlexibleArray);
1566 }
1567
1568 llvm::Constant *VisitCXXConstructExpr(const CXXConstructExpr *E,
1569 QualType Ty) {
1570 if (!E->getConstructor()->isTrivial())
1571 return nullptr;
1572
1573 // Only default and copy/move constructors can be trivial.
1574 if (E->getNumArgs()) {
1575 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
1576 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1577 "trivial ctor has argument but isn't a copy/move ctor");
1578
1579 const Expr *Arg = E->getArg(Arg: 0);
1580 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1581 "argument to copy ctor is of wrong type");
1582
1583 // Look through the temporary; it's just converting the value to an
1584 // lvalue to pass it to the constructor.
1585 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(Val: Arg))
1586 return Visit(S: MTE->getSubExpr(), P: Ty);
1587 // Don't try to support arbitrary lvalue-to-rvalue conversions for now.
1588 return nullptr;
1589 }
1590
1591 return CGM.EmitNullConstant(T: Ty);
1592 }
1593
1594 llvm::Constant *VisitStringLiteral(const StringLiteral *E, QualType T) {
1595 // This is a string literal initializing an array in an initializer.
1596 return CGM.GetConstantArrayFromStringLiteral(E);
1597 }
1598
1599 llvm::Constant *VisitObjCEncodeExpr(const ObjCEncodeExpr *E, QualType T) {
1600 // This must be an @encode initializing an array in a static initializer.
1601 // Don't emit it as the address of the string, emit the string data itself
1602 // as an inline array.
1603 std::string Str;
1604 CGM.getContext().getObjCEncodingForType(T: E->getEncodedType(), S&: Str);
1605 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
1606 assert(CAT && "String data not of constant array type!");
1607
1608 // Resize the string to the right size, adding zeros at the end, or
1609 // truncating as needed.
1610 Str.resize(n: CAT->getZExtSize(), c: '\0');
1611 return llvm::ConstantDataArray::getString(Context&: VMContext, Initializer: Str, AddNull: false);
1612 }
1613
1614 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1615 return Visit(S: E->getSubExpr(), P: T);
1616 }
1617
1618 llvm::Constant *VisitUnaryMinus(const UnaryOperator *U, QualType T) {
1619 if (llvm::Constant *C = Visit(S: U->getSubExpr(), P: T))
1620 if (auto *CI = dyn_cast<llvm::ConstantInt>(Val: C))
1621 return llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: -CI->getValue());
1622 return nullptr;
1623 }
1624
1625 llvm::Constant *VisitPackIndexingExpr(const PackIndexingExpr *E, QualType T) {
1626 return Visit(S: E->getSelectedExpr(), P: T);
1627 }
1628
1629 // Utility methods
1630 llvm::Type *ConvertType(QualType T) {
1631 return CGM.getTypes().ConvertType(T);
1632 }
1633};
1634
1635} // end anonymous namespace.
1636
1637llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1638 AbstractState saved) {
1639 Abstract = saved.OldValue;
1640
1641 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1642 "created a placeholder while doing an abstract emission?");
1643
1644 // No validation necessary for now.
1645 // No cleanup to do for now.
1646 return C;
1647}
1648
1649llvm::Constant *
1650ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1651 auto state = pushAbstract();
1652 auto C = tryEmitPrivateForVarInit(D);
1653 return validateAndPopAbstract(C, saved: state);
1654}
1655
1656llvm::Constant *
1657ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1658 auto state = pushAbstract();
1659 auto C = tryEmitPrivate(E, T: destType);
1660 return validateAndPopAbstract(C, saved: state);
1661}
1662
1663llvm::Constant *
1664ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1665 auto state = pushAbstract();
1666 auto C = tryEmitPrivate(value, T: destType);
1667 return validateAndPopAbstract(C, saved: state);
1668}
1669
1670llvm::Constant *ConstantEmitter::tryEmitConstantExpr(const ConstantExpr *CE) {
1671 if (!CE->hasAPValueResult())
1672 return nullptr;
1673
1674 QualType RetType = CE->getType();
1675 if (CE->isGLValue())
1676 RetType = CGM.getContext().getLValueReferenceType(T: RetType);
1677
1678 return tryEmitAbstract(value: CE->getAPValueResult(), destType: RetType);
1679}
1680
1681llvm::Constant *
1682ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1683 auto state = pushAbstract();
1684 auto C = tryEmitPrivate(E, T: destType);
1685 C = validateAndPopAbstract(C, saved: state);
1686 if (!C) {
1687 CGM.Error(loc: E->getExprLoc(),
1688 error: "internal error: could not emit constant value \"abstractly\"");
1689 C = CGM.EmitNullConstant(T: destType);
1690 }
1691 return C;
1692}
1693
1694llvm::Constant *
1695ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1696 QualType destType,
1697 bool EnablePtrAuthFunctionTypeDiscrimination) {
1698 auto state = pushAbstract();
1699 auto C =
1700 tryEmitPrivate(value, T: destType, EnablePtrAuthFunctionTypeDiscrimination);
1701 C = validateAndPopAbstract(C, saved: state);
1702 if (!C) {
1703 CGM.Error(loc,
1704 error: "internal error: could not emit constant value \"abstractly\"");
1705 C = CGM.EmitNullConstant(T: destType);
1706 }
1707 return C;
1708}
1709
1710llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1711 initializeNonAbstract(destAS: D.getType().getAddressSpace());
1712 llvm::Constant *Init = tryEmitPrivateForVarInit(D);
1713
1714 // If a placeholder address was needed for a TLS variable, implying that the
1715 // initializer's value depends on its address, then the object may not be
1716 // initialized in .tdata because the initializer will be memcpy'd to the
1717 // thread's TLS. Instead the initialization must be done in code.
1718 if (!PlaceholderAddresses.empty() && D.getTLSKind() != VarDecl::TLS_None) {
1719 for (auto [_, GV] : PlaceholderAddresses)
1720 GV->eraseFromParent();
1721 PlaceholderAddresses.clear();
1722 Init = nullptr;
1723 }
1724
1725 return markIfFailed(init: Init);
1726}
1727
1728llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
1729 LangAS destAddrSpace,
1730 QualType destType) {
1731 initializeNonAbstract(destAS: destAddrSpace);
1732 return markIfFailed(init: tryEmitPrivateForMemory(E, T: destType));
1733}
1734
1735llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
1736 LangAS destAddrSpace,
1737 QualType destType) {
1738 initializeNonAbstract(destAS: destAddrSpace);
1739 auto C = tryEmitPrivateForMemory(value, T: destType);
1740 assert(C && "couldn't emit constant value non-abstractly?");
1741 return C;
1742}
1743
1744llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1745 assert(!Abstract && "cannot get current address for abstract constant");
1746
1747
1748
1749 // Make an obviously ill-formed global that should blow up compilation
1750 // if it survives.
1751 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1752 llvm::GlobalValue::PrivateLinkage,
1753 /*init*/ nullptr,
1754 /*name*/ "",
1755 /*before*/ nullptr,
1756 llvm::GlobalVariable::NotThreadLocal,
1757 CGM.getContext().getTargetAddressSpace(AS: DestAddressSpace));
1758
1759 PlaceholderAddresses.push_back(Elt: std::make_pair(x: nullptr, y&: global));
1760
1761 return global;
1762}
1763
1764void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1765 llvm::GlobalValue *placeholder) {
1766 assert(!PlaceholderAddresses.empty());
1767 assert(PlaceholderAddresses.back().first == nullptr);
1768 assert(PlaceholderAddresses.back().second == placeholder);
1769 PlaceholderAddresses.back().first = signal;
1770}
1771
1772namespace {
1773 struct ReplacePlaceholders {
1774 CodeGenModule &CGM;
1775
1776 /// The base address of the global.
1777 llvm::Constant *Base;
1778 llvm::Type *BaseValueTy = nullptr;
1779
1780 /// The placeholder addresses that were registered during emission.
1781 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1782
1783 /// The locations of the placeholder signals.
1784 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1785
1786 /// The current index stack. We use a simple unsigned stack because
1787 /// we assume that placeholders will be relatively sparse in the
1788 /// initializer, but we cache the index values we find just in case.
1789 llvm::SmallVector<unsigned, 8> Indices;
1790 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1791
1792 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1793 ArrayRef<std::pair<llvm::Constant*,
1794 llvm::GlobalVariable*>> addresses)
1795 : CGM(CGM), Base(base),
1796 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1797 }
1798
1799 void replaceInInitializer(llvm::Constant *init) {
1800 // Remember the type of the top-most initializer.
1801 BaseValueTy = init->getType();
1802
1803 // Initialize the stack.
1804 Indices.push_back(Elt: 0);
1805 IndexValues.push_back(Elt: nullptr);
1806
1807 // Recurse into the initializer.
1808 findLocations(init);
1809
1810 // Check invariants.
1811 assert(IndexValues.size() == Indices.size() && "mismatch");
1812 assert(Indices.size() == 1 && "didn't pop all indices");
1813
1814 // Do the replacement; this basically invalidates 'init'.
1815 assert(Locations.size() == PlaceholderAddresses.size() &&
1816 "missed a placeholder?");
1817
1818 // We're iterating over a hashtable, so this would be a source of
1819 // non-determinism in compiler output *except* that we're just
1820 // messing around with llvm::Constant structures, which never itself
1821 // does anything that should be visible in compiler output.
1822 for (auto &entry : Locations) {
1823 assert(entry.first->getName() == "" && "not a placeholder!");
1824 entry.first->replaceAllUsesWith(V: entry.second);
1825 entry.first->eraseFromParent();
1826 }
1827 }
1828
1829 private:
1830 void findLocations(llvm::Constant *init) {
1831 // Recurse into aggregates.
1832 if (auto agg = dyn_cast<llvm::ConstantAggregate>(Val: init)) {
1833 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1834 Indices.push_back(Elt: i);
1835 IndexValues.push_back(Elt: nullptr);
1836
1837 findLocations(init: agg->getOperand(i_nocapture: i));
1838
1839 IndexValues.pop_back();
1840 Indices.pop_back();
1841 }
1842 return;
1843 }
1844
1845 // Otherwise, check for registered constants.
1846 while (true) {
1847 auto it = PlaceholderAddresses.find(Val: init);
1848 if (it != PlaceholderAddresses.end()) {
1849 setLocation(it->second);
1850 break;
1851 }
1852
1853 // Look through bitcasts or other expressions.
1854 if (auto expr = dyn_cast<llvm::ConstantExpr>(Val: init)) {
1855 init = expr->getOperand(i_nocapture: 0);
1856 } else {
1857 break;
1858 }
1859 }
1860 }
1861
1862 void setLocation(llvm::GlobalVariable *placeholder) {
1863 assert(!Locations.contains(placeholder) &&
1864 "already found location for placeholder!");
1865
1866 // Lazily fill in IndexValues with the values from Indices.
1867 // We do this in reverse because we should always have a strict
1868 // prefix of indices from the start.
1869 assert(Indices.size() == IndexValues.size());
1870 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1871 if (IndexValues[i]) {
1872#ifndef NDEBUG
1873 for (size_t j = 0; j != i + 1; ++j) {
1874 assert(IndexValues[j] &&
1875 isa<llvm::ConstantInt>(IndexValues[j]) &&
1876 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1877 == Indices[j]);
1878 }
1879#endif
1880 break;
1881 }
1882
1883 IndexValues[i] = llvm::ConstantInt::get(Ty: CGM.Int32Ty, V: Indices[i]);
1884 }
1885
1886 llvm::Constant *location = llvm::ConstantExpr::getInBoundsGetElementPtr(
1887 Ty: BaseValueTy, C: Base, IdxList: IndexValues);
1888
1889 Locations.insert(KV: {placeholder, location});
1890 }
1891 };
1892}
1893
1894void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1895 assert(InitializedNonAbstract &&
1896 "finalizing emitter that was used for abstract emission?");
1897 assert(!Finalized && "finalizing emitter multiple times");
1898 assert(global->getInitializer());
1899
1900 // Note that we might also be Failed.
1901 Finalized = true;
1902
1903 if (!PlaceholderAddresses.empty()) {
1904 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1905 .replaceInInitializer(init: global->getInitializer());
1906 PlaceholderAddresses.clear(); // satisfy
1907 }
1908}
1909
1910ConstantEmitter::~ConstantEmitter() {
1911 assert((!InitializedNonAbstract || Finalized || Failed) &&
1912 "not finalized after being initialized for non-abstract emission");
1913 assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1914}
1915
1916static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1917 if (auto AT = type->getAs<AtomicType>()) {
1918 return CGM.getContext().getQualifiedType(T: AT->getValueType(),
1919 Qs: type.getQualifiers());
1920 }
1921 return type;
1922}
1923
1924llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
1925 // Make a quick check if variable can be default NULL initialized
1926 // and avoid going through rest of code which may do, for c++11,
1927 // initialization of memory to all NULLs.
1928 if (!D.hasLocalStorage()) {
1929 QualType Ty = CGM.getContext().getBaseElementType(QT: D.getType());
1930 if (Ty->isRecordType())
1931 if (const CXXConstructExpr *E =
1932 dyn_cast_or_null<CXXConstructExpr>(Val: D.getInit())) {
1933 const CXXConstructorDecl *CD = E->getConstructor();
1934 if (CD->isTrivial() && CD->isDefaultConstructor())
1935 return CGM.EmitNullConstant(T: D.getType());
1936 }
1937 }
1938 InConstantContext = D.hasConstantInitialization();
1939
1940 QualType destType = D.getType();
1941 const Expr *E = D.getInit();
1942 assert(E && "No initializer to emit");
1943
1944 if (!destType->isReferenceType()) {
1945 QualType nonMemoryDestType = getNonMemoryType(CGM, type: destType);
1946 if (llvm::Constant *C = ConstExprEmitter(*this).Visit(S: E, P: nonMemoryDestType))
1947 return emitForMemory(C, T: destType);
1948 }
1949
1950 // Try to emit the initializer. Note that this can allow some things that
1951 // are not allowed by tryEmitPrivateForMemory alone.
1952 if (const APValue *value = D.evaluateValue()) {
1953 assert(!value->allowConstexprUnknown() &&
1954 "Constexpr unknown values are not allowed in CodeGen");
1955 return tryEmitPrivateForMemory(value: *value, T: destType);
1956 }
1957
1958 return nullptr;
1959}
1960
1961llvm::Constant *
1962ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1963 auto nonMemoryDestType = getNonMemoryType(CGM, type: destType);
1964 auto C = tryEmitAbstract(E, destType: nonMemoryDestType);
1965 return (C ? emitForMemory(C, T: destType) : nullptr);
1966}
1967
1968llvm::Constant *
1969ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1970 QualType destType) {
1971 auto nonMemoryDestType = getNonMemoryType(CGM, type: destType);
1972 auto C = tryEmitAbstract(value, destType: nonMemoryDestType);
1973 return (C ? emitForMemory(C, T: destType) : nullptr);
1974}
1975
1976llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1977 QualType destType) {
1978 auto nonMemoryDestType = getNonMemoryType(CGM, type: destType);
1979 llvm::Constant *C = tryEmitPrivate(E, T: nonMemoryDestType);
1980 return (C ? emitForMemory(C, T: destType) : nullptr);
1981}
1982
1983llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1984 QualType destType) {
1985 auto nonMemoryDestType = getNonMemoryType(CGM, type: destType);
1986 auto C = tryEmitPrivate(value, T: nonMemoryDestType);
1987 return (C ? emitForMemory(C, T: destType) : nullptr);
1988}
1989
1990/// Try to emit a constant signed pointer, given a raw pointer and the
1991/// destination ptrauth qualifier.
1992///
1993/// This can fail if the qualifier needs address discrimination and the
1994/// emitter is in an abstract mode.
1995llvm::Constant *
1996ConstantEmitter::tryEmitConstantSignedPointer(llvm::Constant *UnsignedPointer,
1997 PointerAuthQualifier Schema) {
1998 assert(Schema && "applying trivial ptrauth schema");
1999
2000 if (Schema.hasKeyNone())
2001 return UnsignedPointer;
2002
2003 unsigned Key = Schema.getKey();
2004
2005 // Create an address placeholder if we're using address discrimination.
2006 llvm::GlobalValue *StorageAddress = nullptr;
2007 if (Schema.isAddressDiscriminated()) {
2008 // We can't do this if the emitter is in an abstract state.
2009 if (isAbstract())
2010 return nullptr;
2011
2012 StorageAddress = getCurrentAddrPrivate();
2013 }
2014
2015 llvm::ConstantInt *Discriminator =
2016 llvm::ConstantInt::get(Ty: CGM.IntPtrTy, V: Schema.getExtraDiscriminator());
2017
2018 llvm::Constant *SignedPointer = CGM.getConstantSignedPointer(
2019 Pointer: UnsignedPointer, Key, StorageAddress, OtherDiscriminator: Discriminator);
2020
2021 if (Schema.isAddressDiscriminated())
2022 registerCurrentAddrPrivate(signal: SignedPointer, placeholder: StorageAddress);
2023
2024 return SignedPointer;
2025}
2026
2027llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
2028 llvm::Constant *C,
2029 QualType destType) {
2030 // For an _Atomic-qualified constant, we may need to add tail padding.
2031 if (auto AT = destType->getAs<AtomicType>()) {
2032 QualType destValueType = AT->getValueType();
2033 C = emitForMemory(CGM, C, destType: destValueType);
2034
2035 uint64_t innerSize = CGM.getContext().getTypeSize(T: destValueType);
2036 uint64_t outerSize = CGM.getContext().getTypeSize(T: destType);
2037 if (innerSize == outerSize)
2038 return C;
2039
2040 assert(innerSize < outerSize && "emitted over-large constant for atomic");
2041 llvm::Constant *elts[] = {
2042 C,
2043 llvm::ConstantAggregateZero::get(
2044 Ty: llvm::ArrayType::get(ElementType: CGM.Int8Ty, NumElements: (outerSize - innerSize) / 8))
2045 };
2046 return llvm::ConstantStruct::getAnon(V: elts);
2047 }
2048
2049 // Zero-extend bool.
2050 // In HLSL bool vectors are stored in memory as a vector of i32
2051 if ((C->getType()->isIntegerTy(BitWidth: 1) && !destType->isBitIntType()) ||
2052 (destType->isExtVectorBoolType() &&
2053 !destType->isPackedVectorBoolType(ctx: CGM.getContext()))) {
2054 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(T: destType);
2055 llvm::Constant *Res = llvm::ConstantFoldCastOperand(
2056 Opcode: llvm::Instruction::ZExt, C, DestTy: boolTy, DL: CGM.getDataLayout());
2057 assert(Res && "Constant folding must succeed");
2058 return Res;
2059 }
2060
2061 if (destType->isBitIntType()) {
2062 llvm::Type *MemTy = CGM.getTypes().ConvertTypeForMem(T: destType);
2063 if (C->getType() != MemTy) {
2064 ConstantAggregateBuilder Builder(CGM);
2065 llvm::Type *LoadStoreTy =
2066 CGM.getTypes().convertTypeForLoadStore(T: destType);
2067 // ptrtoint/inttoptr should not involve _BitInt in constant expressions,
2068 // so casting to ConstantInt is safe here.
2069 auto *CI = cast<llvm::ConstantInt>(Val: C);
2070 llvm::Constant *Res = llvm::ConstantFoldCastOperand(
2071 Opcode: destType->isSignedIntegerOrEnumerationType()
2072 ? llvm::Instruction::SExt
2073 : llvm::Instruction::ZExt,
2074 C: CI, DestTy: LoadStoreTy, DL: CGM.getDataLayout());
2075 if (CGM.getTypes().typeRequiresSplitIntoByteArray(ASTTy: destType,
2076 LLVMTy: C->getType())) {
2077 // Long _BitInt has array of bytes as in-memory type.
2078 // So, split constant into individual bytes.
2079 llvm::APInt Value = cast<llvm::ConstantInt>(Val: Res)->getValue();
2080 Builder.addBits(Bits: Value, /*OffsetInBits=*/0, /*AllowOverwrite=*/false);
2081 return Builder.build(DesiredTy: MemTy, /*AllowOversized*/ false);
2082 }
2083 return Res;
2084 }
2085 }
2086
2087 return C;
2088}
2089
2090llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
2091 QualType destType) {
2092 assert(!destType->isVoidType() && "can't emit a void constant");
2093
2094 if (!destType->isReferenceType())
2095 if (llvm::Constant *C = ConstExprEmitter(*this).Visit(S: E, P: destType))
2096 return C;
2097
2098 Expr::EvalResult Result;
2099
2100 bool Success = false;
2101
2102 if (destType->isReferenceType())
2103 Success = E->EvaluateAsLValue(Result, Ctx: CGM.getContext());
2104 else
2105 Success = E->EvaluateAsRValue(Result, Ctx: CGM.getContext(), InConstantContext);
2106
2107 if (Success && !Result.HasSideEffects)
2108 return tryEmitPrivate(value: Result.Val, T: destType);
2109
2110 return nullptr;
2111}
2112
2113llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
2114 return getTargetCodeGenInfo().getNullPointer(CGM: *this, T, QT);
2115}
2116
2117namespace {
2118/// A struct which can be used to peephole certain kinds of finalization
2119/// that normally happen during l-value emission.
2120struct ConstantLValue {
2121 llvm::Constant *Value;
2122 bool HasOffsetApplied;
2123 bool HasDestPointerAuth;
2124
2125 /*implicit*/ ConstantLValue(llvm::Constant *value,
2126 bool hasOffsetApplied = false,
2127 bool hasDestPointerAuth = false)
2128 : Value(value), HasOffsetApplied(hasOffsetApplied),
2129 HasDestPointerAuth(hasDestPointerAuth) {}
2130
2131 /*implicit*/ ConstantLValue(ConstantAddress address)
2132 : ConstantLValue(address.getPointer()) {}
2133};
2134
2135/// A helper class for emitting constant l-values.
2136class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
2137 ConstantLValue> {
2138 CodeGenModule &CGM;
2139 ConstantEmitter &Emitter;
2140 const APValue &Value;
2141 QualType DestType;
2142 bool EnablePtrAuthFunctionTypeDiscrimination;
2143
2144 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
2145 friend StmtVisitorBase;
2146
2147public:
2148 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
2149 QualType destType,
2150 bool EnablePtrAuthFunctionTypeDiscrimination = true)
2151 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType),
2152 EnablePtrAuthFunctionTypeDiscrimination(
2153 EnablePtrAuthFunctionTypeDiscrimination) {}
2154
2155 llvm::Constant *tryEmit();
2156
2157private:
2158 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
2159 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
2160
2161 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
2162 ConstantLValue VisitConstantExpr(const ConstantExpr *E);
2163 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2164 ConstantLValue VisitStringLiteral(const StringLiteral *E);
2165 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
2166 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
2167 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
2168 llvm::Constant *VisitObjCCollectionElement(const Expr *E);
2169 ConstantLValue VisitObjCArrayLiteral(const ObjCArrayLiteral *E);
2170 ConstantLValue VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E);
2171 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
2172 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
2173 ConstantLValue VisitCallExpr(const CallExpr *E);
2174 ConstantLValue VisitBlockExpr(const BlockExpr *E);
2175 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2176 ConstantLValue VisitMaterializeTemporaryExpr(
2177 const MaterializeTemporaryExpr *E);
2178
2179 ConstantLValue emitPointerAuthSignConstant(const CallExpr *E);
2180 llvm::Constant *emitPointerAuthPointer(const Expr *E);
2181 unsigned emitPointerAuthKey(const Expr *E);
2182 std::pair<llvm::Constant *, llvm::ConstantInt *>
2183 emitPointerAuthDiscriminator(const Expr *E);
2184
2185 bool hasNonZeroOffset() const {
2186 return !Value.getLValueOffset().isZero();
2187 }
2188
2189 /// Return the value offset.
2190 llvm::Constant *getOffset() {
2191 return llvm::ConstantInt::get(Ty: CGM.Int64Ty,
2192 V: Value.getLValueOffset().getQuantity());
2193 }
2194
2195 /// Apply the value offset to the given constant.
2196 llvm::Constant *applyOffset(llvm::Constant *C) {
2197 if (!hasNonZeroOffset())
2198 return C;
2199
2200 return llvm::ConstantExpr::getPtrAdd(Ptr: C, Offset: getOffset());
2201 }
2202};
2203
2204}
2205
2206llvm::Constant *ConstantLValueEmitter::tryEmit() {
2207 const APValue::LValueBase &base = Value.getLValueBase();
2208
2209 // The destination type should be a pointer or reference
2210 // type, but it might also be a cast thereof.
2211 //
2212 // FIXME: the chain of casts required should be reflected in the APValue.
2213 // We need this in order to correctly handle things like a ptrtoint of a
2214 // non-zero null pointer and addrspace casts that aren't trivially
2215 // represented in LLVM IR.
2216 auto destTy = CGM.getTypes().ConvertTypeForMem(T: DestType);
2217 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
2218
2219 // If there's no base at all, this is a null or absolute pointer,
2220 // possibly cast back to an integer type.
2221 if (!base) {
2222 return tryEmitAbsolute(destTy);
2223 }
2224
2225 // Otherwise, try to emit the base.
2226 ConstantLValue result = tryEmitBase(base);
2227
2228 // If that failed, we're done.
2229 llvm::Constant *value = result.Value;
2230 if (!value) return nullptr;
2231
2232 // Apply the offset if necessary and not already done.
2233 if (!result.HasOffsetApplied) {
2234 value = applyOffset(C: value);
2235 }
2236
2237 // Apply pointer-auth signing from the destination type.
2238 if (PointerAuthQualifier PointerAuth = DestType.getPointerAuth();
2239 PointerAuth && !result.HasDestPointerAuth) {
2240 value = Emitter.tryEmitConstantSignedPointer(UnsignedPointer: value, Schema: PointerAuth);
2241 if (!value)
2242 return nullptr;
2243 }
2244
2245 // Convert to the appropriate type; this could be an lvalue for
2246 // an integer. FIXME: performAddrSpaceCast
2247 if (isa<llvm::PointerType>(Val: destTy))
2248 return llvm::ConstantExpr::getPointerCast(C: value, Ty: destTy);
2249
2250 return llvm::ConstantExpr::getPtrToInt(C: value, Ty: destTy);
2251}
2252
2253/// Try to emit an absolute l-value, such as a null pointer or an integer
2254/// bitcast to pointer type.
2255llvm::Constant *
2256ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
2257 // If we're producing a pointer, this is easy.
2258 auto destPtrTy = cast<llvm::PointerType>(Val: destTy);
2259 if (Value.isNullPointer()) {
2260 // FIXME: integer offsets from non-zero null pointers.
2261 return CGM.getNullPointer(T: destPtrTy, QT: DestType);
2262 }
2263
2264 // Convert the integer to a pointer-sized integer before converting it
2265 // to a pointer.
2266 // FIXME: signedness depends on the original integer type.
2267 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
2268 llvm::Constant *C;
2269 C = llvm::ConstantFoldIntegerCast(C: getOffset(), DestTy: intptrTy, /*isSigned*/ IsSigned: false,
2270 DL: CGM.getDataLayout());
2271 assert(C && "Must have folded, as Offset is a ConstantInt");
2272 C = llvm::ConstantExpr::getIntToPtr(C, Ty: destPtrTy);
2273 return C;
2274}
2275
2276ConstantLValue
2277ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
2278 // Handle values.
2279 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
2280 // The constant always points to the canonical declaration. We want to look
2281 // at properties of the most recent declaration at the point of emission.
2282 D = cast<ValueDecl>(Val: D->getMostRecentDecl());
2283
2284 if (D->hasAttr<WeakRefAttr>())
2285 return CGM.GetWeakRefReference(VD: D).getPointer();
2286
2287 auto PtrAuthSign = [&](llvm::Constant *C) {
2288 if (PointerAuthQualifier PointerAuth = DestType.getPointerAuth()) {
2289 C = applyOffset(C);
2290 C = Emitter.tryEmitConstantSignedPointer(UnsignedPointer: C, Schema: PointerAuth);
2291 return ConstantLValue(C, /*applied offset*/ true, /*signed*/ true);
2292 }
2293
2294 CGPointerAuthInfo AuthInfo;
2295
2296 if (EnablePtrAuthFunctionTypeDiscrimination)
2297 AuthInfo = CGM.getFunctionPointerAuthInfo(T: DestType);
2298
2299 if (AuthInfo) {
2300 if (hasNonZeroOffset())
2301 return ConstantLValue(nullptr);
2302
2303 C = applyOffset(C);
2304 C = CGM.getConstantSignedPointer(
2305 Pointer: C, Key: AuthInfo.getKey(), StorageAddress: nullptr,
2306 OtherDiscriminator: cast_or_null<llvm::ConstantInt>(Val: AuthInfo.getDiscriminator()));
2307 return ConstantLValue(C, /*applied offset*/ true, /*signed*/ true);
2308 }
2309
2310 return ConstantLValue(C);
2311 };
2312
2313 if (const auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
2314 llvm::Constant *C = CGM.getRawFunctionPointer(GD: FD);
2315 if (FD->getType()->isCFIUncheckedCalleeFunctionType())
2316 C = llvm::NoCFIValue::get(GV: cast<llvm::GlobalValue>(Val: C));
2317 return PtrAuthSign(C);
2318 }
2319
2320 if (const auto *VD = dyn_cast<VarDecl>(Val: D)) {
2321 // We can never refer to a variable with local storage.
2322 if (!VD->hasLocalStorage()) {
2323 if (VD->isFileVarDecl() || VD->hasExternalStorage())
2324 return CGM.GetAddrOfGlobalVar(D: VD);
2325
2326 if (VD->isLocalVarDecl()) {
2327 return CGM.getOrCreateStaticVarDecl(
2328 D: *VD, Linkage: CGM.getLLVMLinkageVarDefinition(VD));
2329 }
2330 }
2331 }
2332
2333 if (const auto *GD = dyn_cast<MSGuidDecl>(Val: D))
2334 return CGM.GetAddrOfMSGuidDecl(GD);
2335
2336 if (const auto *GCD = dyn_cast<UnnamedGlobalConstantDecl>(Val: D))
2337 return CGM.GetAddrOfUnnamedGlobalConstantDecl(GCD);
2338
2339 if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(Val: D))
2340 return CGM.GetAddrOfTemplateParamObject(TPO);
2341
2342 return nullptr;
2343 }
2344
2345 // Handle typeid(T).
2346 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>())
2347 return CGM.GetAddrOfRTTIDescriptor(Ty: QualType(TI.getType(), 0));
2348
2349 // Otherwise, it must be an expression.
2350 return Visit(S: base.get<const Expr*>());
2351}
2352
2353ConstantLValue
2354ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
2355 if (llvm::Constant *Result = Emitter.tryEmitConstantExpr(CE: E))
2356 return Result;
2357 return Visit(S: E->getSubExpr());
2358}
2359
2360ConstantLValue
2361ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2362 ConstantEmitter CompoundLiteralEmitter(CGM, Emitter.CGF);
2363 CompoundLiteralEmitter.setInConstantContext(Emitter.isInConstantContext());
2364 return tryEmitGlobalCompoundLiteral(emitter&: CompoundLiteralEmitter, E);
2365}
2366
2367ConstantLValue
2368ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
2369 return CGM.GetAddrOfConstantStringFromLiteral(S: E);
2370}
2371
2372ConstantLValue
2373ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2374 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
2375}
2376
2377static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
2378 QualType T,
2379 CodeGenModule &CGM) {
2380 auto C = CGM.getObjCRuntime().GenerateConstantString(S);
2381 return C.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T));
2382}
2383
2384ConstantLValue
2385ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
2386 return emitConstantObjCStringLiteral(S: E->getString(), T: E->getType(), CGM);
2387}
2388
2389ConstantLValue
2390ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
2391 ASTContext &Context = CGM.getContext();
2392 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2393 const Expr *SubExpr = E->getSubExpr();
2394 const QualType &Ty = SubExpr->IgnoreParens()->getType();
2395
2396 assert(SubExpr->isEvaluatable(Context) &&
2397 "Non const NSNumber is being emitted as a constant");
2398
2399 if (const auto *SL = dyn_cast<StringLiteral>(Val: SubExpr->IgnoreParenCasts()))
2400 return emitConstantObjCStringLiteral(S: SL, T: E->getType(), CGM);
2401
2402 // Note `@YES` `@NO` need to be handled explicitly
2403 // to meet existing plist encoding / decoding expectations
2404 const bool IsBoolType =
2405 (Ty->isBooleanType() || NSAPI(Context).isObjCBOOLType(T: Ty));
2406 bool BoolValue = false;
2407 if (IsBoolType && SubExpr->EvaluateAsBooleanCondition(Result&: BoolValue, Ctx: Context)) {
2408 ConstantAddress C = Runtime.GenerateConstantNumber(Value: BoolValue, Ty);
2409 return C.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T: E->getType()));
2410 }
2411
2412 Expr::EvalResult IntResult{};
2413 if (SubExpr->EvaluateAsInt(Result&: IntResult, Ctx: Context)) {
2414 ConstantAddress C =
2415 Runtime.GenerateConstantNumber(Value: IntResult.Val.getInt(), Ty);
2416 return C.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T: E->getType()));
2417 }
2418
2419 llvm::APFloat FloatValue(0.0);
2420 if (SubExpr->EvaluateAsFloat(Result&: FloatValue, Ctx: Context)) {
2421 ConstantAddress C = Runtime.GenerateConstantNumber(Value: FloatValue, Ty);
2422 return C.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T: E->getType()));
2423 }
2424
2425 llvm_unreachable("SubExpr is expected to be evaluated as a numeric type");
2426}
2427
2428llvm::Constant *
2429ConstantLValueEmitter::VisitObjCCollectionElement(const Expr *E) {
2430 auto CE = cast<CastExpr>(Val: E);
2431 const Expr *Elm = CE->getSubExpr();
2432 QualType DestTy = CE->getType();
2433
2434 assert(CE->getCastKind() == CK_BitCast &&
2435 "Expected a CK_BitCast type for valid items in constant objc "
2436 "collection literals");
2437
2438 llvm::Type *DstTy = CGM.getTypes().ConvertType(T: DestTy);
2439 ConstantLValue LV = Visit(S: Elm);
2440 llvm::Constant *ConstVal = cast<llvm::Constant>(Val: LV.Value);
2441 llvm::Constant *Val = llvm::ConstantExpr::getBitCast(C: ConstVal, Ty: DstTy);
2442 return Val;
2443}
2444
2445ConstantLValue
2446ConstantLValueEmitter::VisitObjCArrayLiteral(const ObjCArrayLiteral *E) {
2447 SmallVector<llvm::Constant *, 16> ObjectExpressions;
2448 uint64_t NumElements = E->getNumElements();
2449 ObjectExpressions.reserve(N: NumElements);
2450
2451 for (uint64_t i = 0; i < NumElements; i++) {
2452 llvm::Constant *Val = VisitObjCCollectionElement(E: E->getElement(Index: i));
2453 ObjectExpressions.push_back(Elt: Val);
2454 }
2455 ConstantAddress C =
2456 CGM.getObjCRuntime().GenerateConstantArray(Objects: ObjectExpressions);
2457 return C.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T: E->getType()));
2458}
2459
2460ConstantLValue ConstantLValueEmitter::VisitObjCDictionaryLiteral(
2461 const ObjCDictionaryLiteral *E) {
2462 SmallVector<std::pair<llvm::Constant *, llvm::Constant *>, 16> KeysAndObjects;
2463 uint64_t NumElements = E->getNumElements();
2464 KeysAndObjects.reserve(N: NumElements);
2465
2466 for (uint64_t i = 0; i < NumElements; i++) {
2467 llvm::Constant *Key =
2468 VisitObjCCollectionElement(E: E->getKeyValueElement(Index: i).Key);
2469 llvm::Constant *Val =
2470 VisitObjCCollectionElement(E: E->getKeyValueElement(Index: i).Value);
2471 KeysAndObjects.push_back(Elt: {Key, Val});
2472 }
2473 ConstantAddress C =
2474 CGM.getObjCRuntime().GenerateConstantDictionary(E, KeysAndObjects);
2475 return C.withElementType(ElemTy: CGM.getTypes().ConvertTypeForMem(T: E->getType()));
2476}
2477
2478ConstantLValue
2479ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
2480 return CGM.GetAddrOfConstantStringFromLiteral(S: E->getFunctionName());
2481}
2482
2483ConstantLValue
2484ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
2485 assert(Emitter.CGF && "Invalid address of label expression outside function");
2486 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(L: E->getLabel());
2487 return Ptr;
2488}
2489
2490ConstantLValue
2491ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
2492 unsigned builtin = E->getBuiltinCallee();
2493 if (builtin == Builtin::BI__builtin_function_start)
2494 return CGM.GetFunctionStart(
2495 Decl: E->getArg(Arg: 0)->getAsBuiltinConstantDeclRef(Context: CGM.getContext()));
2496
2497 if (builtin == Builtin::BI__builtin_ptrauth_sign_constant)
2498 return emitPointerAuthSignConstant(E);
2499
2500 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
2501 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
2502 return nullptr;
2503
2504 const auto *Literal = cast<StringLiteral>(Val: E->getArg(Arg: 0)->IgnoreParenCasts());
2505 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
2506 return CGM.getObjCRuntime().GenerateConstantString(Literal);
2507 } else {
2508 // FIXME: need to deal with UCN conversion issues.
2509 return CGM.GetAddrOfConstantCFString(Literal);
2510 }
2511}
2512
2513ConstantLValue
2514ConstantLValueEmitter::emitPointerAuthSignConstant(const CallExpr *E) {
2515 llvm::Constant *UnsignedPointer = emitPointerAuthPointer(E: E->getArg(Arg: 0));
2516 unsigned Key = emitPointerAuthKey(E: E->getArg(Arg: 1));
2517 auto [StorageAddress, OtherDiscriminator] =
2518 emitPointerAuthDiscriminator(E: E->getArg(Arg: 2));
2519
2520 llvm::Constant *SignedPointer = CGM.getConstantSignedPointer(
2521 Pointer: UnsignedPointer, Key, StorageAddress, OtherDiscriminator);
2522 return SignedPointer;
2523}
2524
2525llvm::Constant *ConstantLValueEmitter::emitPointerAuthPointer(const Expr *E) {
2526 Expr::EvalResult Result;
2527 bool Succeeded = E->EvaluateAsRValue(Result, Ctx: CGM.getContext());
2528 assert(Succeeded);
2529 (void)Succeeded;
2530
2531 // The assertions here are all checked by Sema.
2532 assert(Result.Val.isLValue());
2533 if (isa<FunctionDecl>(Val: Result.Val.getLValueBase().get<const ValueDecl *>()))
2534 assert(Result.Val.getLValueOffset().isZero());
2535 return ConstantEmitter(CGM, Emitter.CGF)
2536 .emitAbstract(loc: E->getExprLoc(), value: Result.Val, destType: E->getType(), EnablePtrAuthFunctionTypeDiscrimination: false);
2537}
2538
2539unsigned ConstantLValueEmitter::emitPointerAuthKey(const Expr *E) {
2540 return E->EvaluateKnownConstInt(Ctx: CGM.getContext()).getZExtValue();
2541}
2542
2543std::pair<llvm::Constant *, llvm::ConstantInt *>
2544ConstantLValueEmitter::emitPointerAuthDiscriminator(const Expr *E) {
2545 E = E->IgnoreParens();
2546
2547 if (const auto *Call = dyn_cast<CallExpr>(Val: E)) {
2548 if (Call->getBuiltinCallee() ==
2549 Builtin::BI__builtin_ptrauth_blend_discriminator) {
2550 llvm::Constant *Pointer = ConstantEmitter(CGM).emitAbstract(
2551 E: Call->getArg(Arg: 0), destType: Call->getArg(Arg: 0)->getType());
2552 auto *Extra = cast<llvm::ConstantInt>(Val: ConstantEmitter(CGM).emitAbstract(
2553 E: Call->getArg(Arg: 1), destType: Call->getArg(Arg: 1)->getType()));
2554 return {Pointer, Extra};
2555 }
2556 }
2557
2558 llvm::Constant *Result = ConstantEmitter(CGM).emitAbstract(E, destType: E->getType());
2559 if (Result->getType()->isPointerTy())
2560 return {Result, nullptr};
2561 return {nullptr, cast<llvm::ConstantInt>(Val: Result)};
2562}
2563
2564ConstantLValue
2565ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
2566 StringRef functionName;
2567 if (auto CGF = Emitter.CGF)
2568 functionName = CGF->CurFn->getName();
2569 else
2570 functionName = "global";
2571
2572 return CGM.GetAddrOfGlobalBlock(BE: E, Name: functionName);
2573}
2574
2575ConstantLValue
2576ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2577 QualType T;
2578 if (E->isTypeOperand())
2579 T = E->getTypeOperand(Context: CGM.getContext());
2580 else
2581 T = E->getExprOperand()->getType();
2582 return CGM.GetAddrOfRTTIDescriptor(Ty: T);
2583}
2584
2585ConstantLValue
2586ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
2587 const MaterializeTemporaryExpr *E) {
2588 assert(E->getStorageDuration() == SD_Static);
2589 const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
2590 return CGM.GetAddrOfGlobalTemporary(E, Inner);
2591}
2592
2593llvm::Constant *
2594ConstantEmitter::tryEmitPrivate(const APValue &Value, QualType DestType,
2595 bool EnablePtrAuthFunctionTypeDiscrimination) {
2596 switch (Value.getKind()) {
2597 case APValue::None:
2598 case APValue::Indeterminate:
2599 // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2600 return llvm::UndefValue::get(T: CGM.getTypes().ConvertType(T: DestType));
2601 case APValue::LValue:
2602 return ConstantLValueEmitter(*this, Value, DestType,
2603 EnablePtrAuthFunctionTypeDiscrimination)
2604 .tryEmit();
2605 case APValue::Int:
2606 if (PointerAuthQualifier PointerAuth = DestType.getPointerAuth();
2607 PointerAuth &&
2608 (PointerAuth.authenticatesNullValues() || Value.getInt() != 0))
2609 return nullptr;
2610 return llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: Value.getInt());
2611 case APValue::FixedPoint:
2612 return llvm::ConstantInt::get(Context&: CGM.getLLVMContext(),
2613 V: Value.getFixedPoint().getValue());
2614 case APValue::ComplexInt: {
2615 llvm::Constant *Complex[2];
2616
2617 Complex[0] = llvm::ConstantInt::get(Context&: CGM.getLLVMContext(),
2618 V: Value.getComplexIntReal());
2619 Complex[1] = llvm::ConstantInt::get(Context&: CGM.getLLVMContext(),
2620 V: Value.getComplexIntImag());
2621
2622 // FIXME: the target may want to specify that this is packed.
2623 llvm::StructType *STy =
2624 llvm::StructType::get(elt1: Complex[0]->getType(), elts: Complex[1]->getType());
2625 return llvm::ConstantStruct::get(T: STy, V: Complex);
2626 }
2627 case APValue::Float:
2628 return llvm::ConstantFP::get(Context&: CGM.getLLVMContext(), V: Value.getFloat());
2629 case APValue::ComplexFloat: {
2630 llvm::Constant *Complex[2];
2631
2632 Complex[0] = llvm::ConstantFP::get(Context&: CGM.getLLVMContext(),
2633 V: Value.getComplexFloatReal());
2634 Complex[1] = llvm::ConstantFP::get(Context&: CGM.getLLVMContext(),
2635 V: Value.getComplexFloatImag());
2636
2637 // FIXME: the target may want to specify that this is packed.
2638 llvm::StructType *STy =
2639 llvm::StructType::get(elt1: Complex[0]->getType(), elts: Complex[1]->getType());
2640 return llvm::ConstantStruct::get(T: STy, V: Complex);
2641 }
2642 case APValue::Vector: {
2643 unsigned NumElts = Value.getVectorLength();
2644 SmallVector<llvm::Constant *, 4> Inits(NumElts);
2645
2646 for (unsigned I = 0; I != NumElts; ++I) {
2647 const APValue &Elt = Value.getVectorElt(I);
2648 if (Elt.isInt())
2649 Inits[I] = llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: Elt.getInt());
2650 else if (Elt.isFloat())
2651 Inits[I] = llvm::ConstantFP::get(Context&: CGM.getLLVMContext(), V: Elt.getFloat());
2652 else if (Elt.isIndeterminate())
2653 Inits[I] = llvm::UndefValue::get(T: CGM.getTypes().ConvertType(
2654 T: DestType->castAs<VectorType>()->getElementType()));
2655 else
2656 llvm_unreachable("unsupported vector element type");
2657 }
2658 return llvm::ConstantVector::get(V: Inits);
2659 }
2660 case APValue::Matrix: {
2661 const auto *MT = DestType->castAs<ConstantMatrixType>();
2662 unsigned NumRows = Value.getMatrixNumRows();
2663 unsigned NumCols = Value.getMatrixNumColumns();
2664 unsigned NumElts = NumRows * NumCols;
2665 SmallVector<llvm::Constant *, 16> Inits(NumElts);
2666
2667 bool IsRowMajor = isMatrixRowMajor(LangOpts: CGM.getLangOpts(), T: DestType);
2668
2669 for (unsigned Row = 0; Row != NumRows; ++Row) {
2670 for (unsigned Col = 0; Col != NumCols; ++Col) {
2671 const APValue &Elt = Value.getMatrixElt(Row, Col);
2672 unsigned Idx = MT->getFlattenedIndex(Row, Column: Col, IsRowMajor);
2673 if (Elt.isInt())
2674 Inits[Idx] =
2675 llvm::ConstantInt::get(Context&: CGM.getLLVMContext(), V: Elt.getInt());
2676 else if (Elt.isFloat())
2677 Inits[Idx] =
2678 llvm::ConstantFP::get(Context&: CGM.getLLVMContext(), V: Elt.getFloat());
2679 else if (Elt.isIndeterminate())
2680 Inits[Idx] = llvm::PoisonValue::get(
2681 T: CGM.getTypes().ConvertType(T: MT->getElementType()));
2682 else
2683 llvm_unreachable("unsupported matrix element type");
2684 }
2685 }
2686 return llvm::ConstantVector::get(V: Inits);
2687 }
2688 case APValue::AddrLabelDiff: {
2689 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2690 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
2691 llvm::Constant *LHS = tryEmitPrivate(E: LHSExpr, destType: LHSExpr->getType());
2692 llvm::Constant *RHS = tryEmitPrivate(E: RHSExpr, destType: RHSExpr->getType());
2693 if (!LHS || !RHS) return nullptr;
2694
2695 // Compute difference
2696 llvm::Type *ResultType = CGM.getTypes().ConvertType(T: DestType);
2697 LHS = llvm::ConstantExpr::getPtrToInt(C: LHS, Ty: CGM.IntPtrTy);
2698 RHS = llvm::ConstantExpr::getPtrToInt(C: RHS, Ty: CGM.IntPtrTy);
2699 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(C1: LHS, C2: RHS);
2700
2701 // LLVM is a bit sensitive about the exact format of the
2702 // address-of-label difference; make sure to truncate after
2703 // the subtraction.
2704 return llvm::ConstantExpr::getTruncOrBitCast(C: AddrLabelDiff, Ty: ResultType);
2705 }
2706 case APValue::Struct:
2707 case APValue::Union:
2708 return ConstStructBuilder::BuildStruct(Emitter&: *this, Val: Value, ValTy: DestType);
2709 case APValue::Array: {
2710 const ArrayType *ArrayTy = CGM.getContext().getAsArrayType(T: DestType);
2711 unsigned NumElements = Value.getArraySize();
2712 unsigned NumInitElts = Value.getArrayInitializedElts();
2713
2714 // Emit array filler, if there is one.
2715 llvm::Constant *Filler = nullptr;
2716 if (Value.hasArrayFiller()) {
2717 Filler = tryEmitAbstractForMemory(value: Value.getArrayFiller(),
2718 destType: ArrayTy->getElementType());
2719 if (!Filler)
2720 return nullptr;
2721 }
2722
2723 // Emit initializer elements.
2724 SmallVector<llvm::Constant*, 16> Elts;
2725 if (Filler && Filler->isNullValue())
2726 Elts.reserve(N: NumInitElts + 1);
2727 else
2728 Elts.reserve(N: NumElements);
2729
2730 llvm::Type *CommonElementType = nullptr;
2731 for (unsigned I = 0; I < NumInitElts; ++I) {
2732 llvm::Constant *C = tryEmitPrivateForMemory(
2733 value: Value.getArrayInitializedElt(I), destType: ArrayTy->getElementType());
2734 if (!C) return nullptr;
2735
2736 if (I == 0)
2737 CommonElementType = C->getType();
2738 else if (C->getType() != CommonElementType)
2739 CommonElementType = nullptr;
2740 Elts.push_back(Elt: C);
2741 }
2742
2743 llvm::ArrayType *Desired =
2744 cast<llvm::ArrayType>(Val: CGM.getTypes().ConvertType(T: DestType));
2745
2746 // Fix the type of incomplete arrays if the initializer isn't empty.
2747 if (DestType->isIncompleteArrayType() && !Elts.empty())
2748 Desired = llvm::ArrayType::get(ElementType: Desired->getElementType(), NumElements: Elts.size());
2749
2750 return EmitArrayConstant(CGM, DesiredType: Desired, CommonElementType, ArrayBound: NumElements, Elements&: Elts,
2751 Filler);
2752 }
2753 case APValue::MemberPointer:
2754 return CGM.getCXXABI().EmitMemberPointer(MP: Value, MPT: DestType);
2755 }
2756 llvm_unreachable("Unknown APValue kind");
2757}
2758
2759llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2760 const CompoundLiteralExpr *E) {
2761 return EmittedCompoundLiterals.lookup(Val: E);
2762}
2763
2764void CodeGenModule::setAddrOfConstantCompoundLiteral(
2765 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2766 bool Ok = EmittedCompoundLiterals.insert(KV: std::make_pair(x&: CLE, y&: GV)).second;
2767 (void)Ok;
2768 assert(Ok && "CLE has already been emitted!");
2769}
2770
2771ConstantAddress
2772CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2773 assert(E->isFileScope() && "not a file-scope compound literal expr");
2774 ConstantEmitter emitter(*this);
2775 return tryEmitGlobalCompoundLiteral(emitter, E);
2776}
2777
2778llvm::Constant *
2779CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2780 // Member pointer constants always have a very particular form.
2781 const MemberPointerType *type = cast<MemberPointerType>(Val: uo->getType());
2782 const ValueDecl *decl = cast<DeclRefExpr>(Val: uo->getSubExpr())->getDecl();
2783
2784 // A member function pointer.
2785 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(Val: decl))
2786 return getCXXABI().EmitMemberFunctionPointer(MD: method);
2787
2788 // Otherwise, a member data pointer.
2789 getContext().recordMemberDataPointerEvaluation(VD: decl);
2790 uint64_t fieldOffset = getContext().getFieldOffset(FD: decl);
2791 CharUnits chars = getContext().toCharUnitsFromBits(BitSize: (int64_t) fieldOffset);
2792 return getCXXABI().EmitMemberDataPointer(MPT: type, offset: chars);
2793}
2794
2795static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2796 llvm::Type *baseType,
2797 const CXXRecordDecl *base);
2798
2799static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
2800 const RecordDecl *record,
2801 bool asCompleteObject) {
2802 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
2803 llvm::StructType *structure =
2804 (asCompleteObject ? layout.getLLVMType()
2805 : layout.getBaseSubobjectLLVMType());
2806
2807 unsigned numElements = structure->getNumElements();
2808 std::vector<llvm::Constant *> elements(numElements);
2809
2810 auto CXXR = dyn_cast<CXXRecordDecl>(Val: record);
2811 // Fill in all the bases.
2812 if (CXXR) {
2813 for (const auto &I : CXXR->bases()) {
2814 if (I.isVirtual()) {
2815 // Ignore virtual bases; if we're laying out for a complete
2816 // object, we'll lay these out later.
2817 continue;
2818 }
2819
2820 const auto *base = I.getType()->castAsCXXRecordDecl();
2821 // Ignore empty bases.
2822 if (isEmptyRecordForLayout(Context: CGM.getContext(), T: I.getType()) ||
2823 CGM.getContext()
2824 .getASTRecordLayout(D: base)
2825 .getNonVirtualSize()
2826 .isZero())
2827 continue;
2828
2829 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(RD: base);
2830 llvm::Type *baseType = structure->getElementType(N: fieldIndex);
2831 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2832 }
2833 }
2834
2835 // Fill in all the fields.
2836 for (const auto *Field : record->fields()) {
2837 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2838 // will fill in later.)
2839 if (!Field->isBitField() &&
2840 !isEmptyFieldForLayout(Context: CGM.getContext(), FD: Field)) {
2841 unsigned fieldIndex = layout.getLLVMFieldNo(FD: Field);
2842 elements[fieldIndex] = CGM.EmitNullConstant(T: Field->getType());
2843 }
2844
2845 // For unions, stop after the first named field.
2846 if (record->isUnion()) {
2847 if (Field->getIdentifier())
2848 break;
2849 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
2850 if (FieldRD->findFirstNamedDataMember())
2851 break;
2852 }
2853 }
2854
2855 // Fill in the virtual bases, if we're working with the complete object.
2856 if (CXXR && asCompleteObject) {
2857 for (const auto &I : CXXR->vbases()) {
2858 const auto *base = I.getType()->castAsCXXRecordDecl();
2859 // Ignore empty bases.
2860 if (isEmptyRecordForLayout(Context: CGM.getContext(), T: I.getType()))
2861 continue;
2862
2863 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2864
2865 // We might have already laid this field out.
2866 if (elements[fieldIndex]) continue;
2867
2868 llvm::Type *baseType = structure->getElementType(N: fieldIndex);
2869 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2870 }
2871 }
2872
2873 // Now go through all other fields and zero them out.
2874 for (unsigned i = 0; i != numElements; ++i) {
2875 if (!elements[i])
2876 elements[i] = llvm::Constant::getNullValue(Ty: structure->getElementType(N: i));
2877 }
2878
2879 return llvm::ConstantStruct::get(T: structure, V: elements);
2880}
2881
2882/// Emit the null constant for a base subobject.
2883static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
2884 llvm::Type *baseType,
2885 const CXXRecordDecl *base) {
2886 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2887
2888 // Just zero out bases that don't have any pointer to data members.
2889 if (baseLayout.isZeroInitializableAsBase())
2890 return llvm::Constant::getNullValue(Ty: baseType);
2891
2892 // Otherwise, we can just use its null constant.
2893 return EmitNullConstant(CGM, record: base, /*asCompleteObject=*/false);
2894}
2895
2896llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2897 QualType T) {
2898 return emitForMemory(CGM, C: CGM.EmitNullConstant(T), destType: T);
2899}
2900
2901llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
2902 if (T->getAs<PointerType>()) {
2903 llvm::Type *LT = getTypes().ConvertTypeForMem(T);
2904 if (auto *PT = dyn_cast<llvm::PointerType>(Val: LT))
2905 return getNullPointer(T: PT, QT: T);
2906 // Some pointer types do not lower to an LLVM pointer (e.g. a WebAssembly
2907 // funcref, which is an opaque reference type). Use the type's zero value.
2908 return llvm::Constant::getNullValue(Ty: LT);
2909 }
2910
2911 if (getTypes().isZeroInitializable(T))
2912 return llvm::Constant::getNullValue(Ty: getTypes().ConvertTypeForMem(T));
2913
2914 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
2915 llvm::ArrayType *ATy =
2916 cast<llvm::ArrayType>(Val: getTypes().ConvertTypeForMem(T));
2917
2918 QualType ElementTy = CAT->getElementType();
2919
2920 llvm::Constant *Element =
2921 ConstantEmitter::emitNullForMemory(CGM&: *this, T: ElementTy);
2922 unsigned NumElements = CAT->getZExtSize();
2923 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
2924 return llvm::ConstantArray::get(T: ATy, V: Array);
2925 }
2926
2927 if (const auto *RD = T->getAsRecordDecl())
2928 return ::EmitNullConstant(CGM&: *this, record: RD,
2929 /*asCompleteObject=*/true);
2930
2931 assert(T->isMemberDataPointerType() &&
2932 "Should only see pointers to data members here!");
2933
2934 return getCXXABI().EmitNullMemberPointer(MPT: T->castAs<MemberPointerType>());
2935}
2936
2937llvm::Constant *
2938CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2939 return ::EmitNullConstant(CGM&: *this, record: Record, asCompleteObject: false);
2940}
2941