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