Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/CodeGen/CGExprConstant.cpp
Warning:line 721, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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