blob: 0138edbb9df89a57259b35bef76268d393e3fafb [file] [log] [blame]
Anders Carlsson610ee712008-01-26 01:36:00 +00001//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Anders Carlsson610ee712008-01-26 01:36:00 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Constant Expr nodes as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
John McCall5d865c322010-08-31 07:33:07 +000013#include "CGCXXABI.h"
Daniel Dunbar89da6ad2008-08-13 00:59:25 +000014#include "CGObjCRuntime.h"
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000015#include "CGRecordLayout.h"
Reid Kleckner98031782019-12-09 16:11:56 -080016#include "CodeGenFunction.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "CodeGenModule.h"
John McCallde0fe072017-08-15 21:42:52 +000018#include "ConstantEmitter.h"
Yaxun Liu402804b2016-12-15 08:09:08 +000019#include "TargetInfo.h"
Chris Lattnere50e9012008-10-06 05:59:01 +000020#include "clang/AST/APValue.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000021#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080022#include "clang/AST/Attr.h"
Anders Carlssone1d5ca52009-07-24 15:20:52 +000023#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/StmtVisitor.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000025#include "clang/Basic/Builtins.h"
Richard Smith5745feb2019-06-17 21:08:30 +000026#include "llvm/ADT/STLExtras.h"
Reid Kleckner98031782019-12-09 16:11:56 -080027#include "llvm/ADT/Sequence.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000028#include "llvm/IR/Constants.h"
29#include "llvm/IR/DataLayout.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalVariable.h"
Anders Carlsson610ee712008-01-26 01:36:00 +000032using namespace clang;
33using namespace CodeGen;
34
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000035//===----------------------------------------------------------------------===//
Richard Smith5745feb2019-06-17 21:08:30 +000036// ConstantAggregateBuilder
Chris Lattnercfa3e7a2010-04-13 17:45:57 +000037//===----------------------------------------------------------------------===//
38
39namespace {
Yunzhong Gaocb779302015-06-10 00:27:52 +000040class ConstExprEmitter;
Richard Smith5745feb2019-06-17 21:08:30 +000041
42struct ConstantAggregateBuilderUtils {
Anders Carlssone1d5ca52009-07-24 15:20:52 +000043 CodeGenModule &CGM;
Anders Carlssone1d5ca52009-07-24 15:20:52 +000044
Richard Smith5745feb2019-06-17 21:08:30 +000045 ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {}
Mike Stump11289f42009-09-09 15:08:12 +000046
Ken Dycka1b35102011-03-18 01:26:17 +000047 CharUnits getAlignment(const llvm::Constant *C) const {
Ken Dycka1b35102011-03-18 01:26:17 +000048 return CharUnits::fromQuantity(
Micah Villmowdd31ca12012-10-08 16:25:52 +000049 CGM.getDataLayout().getABITypeAlignment(C->getType()));
Anders Carlssone1d5ca52009-07-24 15:20:52 +000050 }
Mike Stump11289f42009-09-09 15:08:12 +000051
Richard Smith5745feb2019-06-17 21:08:30 +000052 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.Int8Ty;
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.Int8Ty, ZeroSize.getQuantity());
69 return llvm::ConstantAggregateZero::get(Ty);
Anders Carlssone1d5ca52009-07-24 15:20:52 +000070 }
Anders Carlssone1d5ca52009-07-24 15:20:52 +000071};
Mike Stump11289f42009-09-09 15:08:12 +000072
Richard Smith5745feb2019-06-17 21:08:30 +000073/// 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");
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) &&
171 "unexpectedly overwriting field");
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.
Richard Smith780c3742019-06-22 20:41:57 +0000191 for (CharUnits OffsetInChars =
192 Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar);
Richard Smith5745feb2019-06-17 21:08:30 +0000193 /**/; ++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 &&
233 "should have at most one element covering one byte");
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");
260 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) &&
261 "unexpectedly overwriting bitfield");
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) {
Fangrui Song7264a472019-07-03 08:13:17 +0000292 auto FirstAfterPos = llvm::upper_bound(Offsets, Pos);
Richard Smith5745feb2019-06-17 21:08:30 +0000293 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)) {
Eli Friedman68b03ae2020-04-06 17:03:49 -0700321 // Expand the sequence into its contained elements.
322 // FIXME: This assumes vector elements are byte-sized.
Richard Smith5745feb2019-06-17 21:08:30 +0000323 replace(Elems, Index, Index + 1,
324 llvm::map_range(llvm::seq(0u, CA->getNumOperands()),
325 [&](unsigned Op) { return CA->getOperand(Op); }));
Eli Friedman68b03ae2020-04-06 17:03:49 -0700326 if (isa<llvm::ArrayType>(CA->getType()) ||
327 isa<llvm::VectorType>(CA->getType())) {
Richard Smith5745feb2019-06-17 21:08:30 +0000328 // Array or vector.
Eli Friedman68b03ae2020-04-06 17:03:49 -0700329 llvm::Type *ElemTy =
330 llvm::GetElementPtrInst::getTypeAtIndex(CA->getType(), (uint64_t)0);
331 CharUnits ElemSize = getSize(ElemTy);
Richard Smith5745feb2019-06-17 21:08:30 +0000332 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)) {
Eli Friedman68b03ae2020-04-06 17:03:49 -0700352 // Expand the sequence into its contained elements.
353 // FIXME: This assumes vector elements are byte-sized.
Richard Smith5745feb2019-06-17 21:08:30 +0000354 // 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
Mikael Holmen5136ea42019-06-18 06:41:56 +0000368 if (isa<llvm::ConstantAggregateZero>(C)) {
Eli Friedman68b03ae2020-04-06 17:03:49 -0700369 // Split into two zeros at the hinted offset.
Richard Smith5745feb2019-06-17 21:08:30 +0000370 CharUnits ElemSize = getSize(C);
371 assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split");
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)) {
Eli Friedman68b03ae2020-04-06 17:03:49 -0700379 // Drop undef; it doesn't contribute to the final layout.
Richard Smith5745feb2019-06-17 21:08:30 +0000380 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");
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 CharUnits DesiredSize = Utils.getSize(DesiredTy);
443 CharUnits Align = CharUnits::One();
444 for (llvm::Constant *C : Elems)
445 Align = std::max(Align, Utils.getAlignment(C));
446 CharUnits AlignedSize = Size.alignTo(Align);
447
448 bool Packed = false;
449 ArrayRef<llvm::Constant*> UnpackedElems = Elems;
450 llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage;
451 if ((DesiredSize < AlignedSize && !AllowOversized) ||
452 DesiredSize.alignTo(Align) != DesiredSize) {
453 // The natural layout would be the wrong size; force use of a packed layout.
454 NaturalLayout = false;
455 Packed = true;
456 } else if (DesiredSize > AlignedSize) {
457 // The constant would be too small. Add padding to fix it.
458 UnpackedElemStorage.assign(Elems.begin(), Elems.end());
459 UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size));
460 UnpackedElems = UnpackedElemStorage;
461 }
462
463 // If we don't have a natural layout, insert padding as necessary.
464 // As we go, double-check to see if we can actually just emit Elems
465 // as a non-packed struct and do so opportunistically if possible.
466 llvm::SmallVector<llvm::Constant*, 32> PackedElems;
467 if (!NaturalLayout) {
468 CharUnits SizeSoFar = CharUnits::Zero();
469 for (size_t I = 0; I != Elems.size(); ++I) {
470 CharUnits Align = Utils.getAlignment(Elems[I]);
471 CharUnits NaturalOffset = SizeSoFar.alignTo(Align);
472 CharUnits DesiredOffset = Offset(I);
473 assert(DesiredOffset >= SizeSoFar && "elements out of order");
474
475 if (DesiredOffset != NaturalOffset)
476 Packed = true;
477 if (DesiredOffset != SizeSoFar)
478 PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar));
479 PackedElems.push_back(Elems[I]);
480 SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]);
481 }
482 // If we're using the packed layout, pad it out to the desired size if
483 // necessary.
484 if (Packed) {
485 assert((SizeSoFar <= DesiredSize || AllowOversized) &&
486 "requested size is too small for contents");
487 if (SizeSoFar < DesiredSize)
488 PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar));
489 }
490 }
491
492 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements(
493 CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed);
494
495 // Pick the type to use. If the type is layout identical to the desired
496 // type then use it, otherwise use whatever the builder produced for us.
497 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) {
498 if (DesiredSTy->isLayoutIdentical(STy))
499 STy = DesiredSTy;
500 }
501
502 return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems);
503}
504
505void ConstantAggregateBuilder::condense(CharUnits Offset,
506 llvm::Type *DesiredTy) {
507 CharUnits Size = getSize(DesiredTy);
508
509 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset);
510 if (!FirstElemToReplace)
511 return;
512 size_t First = *FirstElemToReplace;
513
514 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size);
515 if (!LastElemToReplace)
516 return;
517 size_t Last = *LastElemToReplace;
518
519 size_t Length = Last - First;
520 if (Length == 0)
521 return;
522
523 if (Length == 1 && Offsets[First] == Offset &&
524 getSize(Elems[First]) == Size) {
525 // Re-wrap single element structs if necessary. Otherwise, leave any single
526 // element constant of the right size alone even if it has the wrong type.
527 auto *STy = dyn_cast<llvm::StructType>(DesiredTy);
528 if (STy && STy->getNumElements() == 1 &&
529 STy->getElementType(0) == Elems[First]->getType())
530 Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]);
531 return;
532 }
533
534 llvm::Constant *Replacement = buildFrom(
535 CGM, makeArrayRef(Elems).slice(First, Length),
536 makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy),
537 /*known to have natural layout=*/false, DesiredTy, false);
538 replace(Elems, First, Last, {Replacement});
539 replace(Offsets, First, Last, {Offset});
540}
541
542//===----------------------------------------------------------------------===//
543// ConstStructBuilder
544//===----------------------------------------------------------------------===//
545
546class ConstStructBuilder {
547 CodeGenModule &CGM;
548 ConstantEmitter &Emitter;
549 ConstantAggregateBuilder &Builder;
550 CharUnits StartOffset;
551
552public:
553 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
554 InitListExpr *ILE, QualType StructTy);
555 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter,
556 const APValue &Value, QualType ValTy);
557 static bool UpdateStruct(ConstantEmitter &Emitter,
558 ConstantAggregateBuilder &Const, CharUnits Offset,
559 InitListExpr *Updater);
560
561private:
562 ConstStructBuilder(ConstantEmitter &Emitter,
563 ConstantAggregateBuilder &Builder, CharUnits StartOffset)
564 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder),
565 StartOffset(StartOffset) {}
566
567 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset,
568 llvm::Constant *InitExpr, bool AllowOverwrite = false);
569
570 bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst,
571 bool AllowOverwrite = false);
572
573 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset,
574 llvm::ConstantInt *InitExpr, bool AllowOverwrite = false);
575
576 bool Build(InitListExpr *ILE, bool AllowOverwrite);
577 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase,
578 const CXXRecordDecl *VTableClass, CharUnits BaseOffset);
579 llvm::Constant *Finalize(QualType Ty);
580};
581
582bool ConstStructBuilder::AppendField(
583 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst,
584 bool AllowOverwrite) {
Ken Dyck1c80fd12011-03-15 01:09:02 +0000585 const ASTContext &Context = CGM.getContext();
586
587 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000588
Richard Smith5745feb2019-06-17 21:08:30 +0000589 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite);
Richard Smithc8998922012-02-23 08:33:23 +0000590}
591
Richard Smith5745feb2019-06-17 21:08:30 +0000592bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars,
593 llvm::Constant *InitCst,
594 bool AllowOverwrite) {
595 return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000596}
597
Richard Smith5745feb2019-06-17 21:08:30 +0000598bool ConstStructBuilder::AppendBitField(
599 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI,
600 bool AllowOverwrite) {
Lucas Pratese6cb4b62020-03-27 11:53:49 +0000601 const CGRecordLayout &RL =
602 CGM.getTypes().getCGRecordLayout(Field->getParent());
603 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000604 llvm::APInt FieldValue = CI->getValue();
605
606 // Promote the size of FieldValue if necessary
607 // FIXME: This should never occur, but currently it can because initializer
608 // constants are cast to bool, and because clang is not enforcing bitfield
609 // width limits.
Lucas Pratese6cb4b62020-03-27 11:53:49 +0000610 if (Info.Size > FieldValue.getBitWidth())
611 FieldValue = FieldValue.zext(Info.Size);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000612
613 // Truncate the size of FieldValue to the bit field size.
Lucas Pratese6cb4b62020-03-27 11:53:49 +0000614 if (Info.Size < FieldValue.getBitWidth())
615 FieldValue = FieldValue.trunc(Info.Size);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000616
Richard Smith5745feb2019-06-17 21:08:30 +0000617 return Builder.addBits(FieldValue,
618 CGM.getContext().toBits(StartOffset) + FieldOffset,
619 AllowOverwrite);
620}
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000621
Richard Smith5745feb2019-06-17 21:08:30 +0000622static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter,
623 ConstantAggregateBuilder &Const,
624 CharUnits Offset, QualType Type,
625 InitListExpr *Updater) {
626 if (Type->isRecordType())
627 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000628
Richard Smith5745feb2019-06-17 21:08:30 +0000629 auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type);
630 if (!CAT)
631 return false;
632 QualType ElemType = CAT->getElementType();
633 CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType);
634 llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000635
Richard Smith5745feb2019-06-17 21:08:30 +0000636 llvm::Constant *FillC = nullptr;
637 if (Expr *Filler = Updater->getArrayFiller()) {
638 if (!isa<NoInitExpr>(Filler)) {
639 FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType);
640 if (!FillC)
641 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000642 }
Richard Smith5745feb2019-06-17 21:08:30 +0000643 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000644
Richard Smith5745feb2019-06-17 21:08:30 +0000645 unsigned NumElementsToUpdate =
646 FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits();
647 for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) {
648 Expr *Init = nullptr;
649 if (I < Updater->getNumInits())
650 Init = Updater->getInit(I);
651
652 if (!Init && FillC) {
653 if (!Const.add(FillC, Offset, true))
654 return false;
655 } else if (!Init || isa<NoInitExpr>(Init)) {
656 continue;
657 } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) {
658 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType,
659 ChildILE))
660 return false;
661 // Attempt to reduce the array element to a single constant if necessary.
662 Const.condense(Offset, ElemTy);
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000663 } else {
Richard Smith5745feb2019-06-17 21:08:30 +0000664 llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType);
665 if (!Const.add(Val, Offset, true))
666 return false;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000667 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000668 }
669
Richard Smith5745feb2019-06-17 21:08:30 +0000670 return true;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000671}
672
Richard Smith5745feb2019-06-17 21:08:30 +0000673bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000674 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000675 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
676
Richard Smith5745feb2019-06-17 21:08:30 +0000677 unsigned FieldNo = -1;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000678 unsigned ElementNo = 0;
Richard Smith872307e2016-03-08 22:17:41 +0000679
680 // Bail out if we have base classes. We could support these, but they only
681 // arise in C++1z where we will have already constant folded most interesting
682 // cases. FIXME: There are still a few more cases we can handle this way.
683 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
684 if (CXXRD->getNumBases())
685 return false;
686
Richard Smith5745feb2019-06-17 21:08:30 +0000687 for (FieldDecl *Field : RD->fields()) {
688 ++FieldNo;
689
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000690 // If this is a union, skip all the fields that aren't being initialized.
Richard Smith78b239e2019-06-20 20:44:45 +0000691 if (RD->isUnion() &&
692 !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field))
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000693 continue;
694
Richard Smith78b239e2019-06-20 20:44:45 +0000695 // Don't emit anonymous bitfields or zero-sized fields.
696 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000697 continue;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000698
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000699 // Get the initializer. A struct can include fields without initializers,
700 // we just use explicit null values for them.
Richard Smith5745feb2019-06-17 21:08:30 +0000701 Expr *Init = nullptr;
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000702 if (ElementNo < ILE->getNumInits())
Richard Smith5745feb2019-06-17 21:08:30 +0000703 Init = ILE->getInit(ElementNo++);
704 if (Init && isa<NoInitExpr>(Init))
705 continue;
Eli Friedman3ee10222010-07-17 23:55:01 +0000706
Richard Smith5745feb2019-06-17 21:08:30 +0000707 // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr
708 // represents additional overwriting of our current constant value, and not
709 // a new constant to emit independently.
710 if (AllowOverwrite &&
711 (Field->getType()->isArrayType() || Field->getType()->isRecordType())) {
712 if (auto *SubILE = dyn_cast<InitListExpr>(Init)) {
713 CharUnits Offset = CGM.getContext().toCharUnitsFromBits(
714 Layout.getFieldOffset(FieldNo));
715 if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset,
716 Field->getType(), SubILE))
717 return false;
718 // If we split apart the field's value, try to collapse it down to a
719 // single value now.
720 Builder.condense(StartOffset + Offset,
721 CGM.getTypes().ConvertTypeForMem(Field->getType()));
722 continue;
723 }
724 }
725
726 llvm::Constant *EltInit =
727 Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType())
728 : Emitter.emitNullForMemory(Field->getType());
Eli Friedman3ee10222010-07-17 23:55:01 +0000729 if (!EltInit)
730 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000731
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000732 if (!Field->isBitField()) {
733 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000734 if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit,
735 AllowOverwrite))
736 return false;
Richard Smith78b239e2019-06-20 20:44:45 +0000737 // After emitting a non-empty field with [[no_unique_address]], we may
738 // need to overwrite its tail padding.
739 if (Field->hasAttr<NoUniqueAddressAttr>())
740 AllowOverwrite = true;
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000741 } else {
Chris Lattnerff0e2a32010-04-13 18:16:19 +0000742 // Otherwise we have a bitfield.
David Majnemer8062eb62015-03-14 22:24:38 +0000743 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) {
Richard Smith5745feb2019-06-17 21:08:30 +0000744 if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI,
745 AllowOverwrite))
746 return false;
David Majnemer8062eb62015-03-14 22:24:38 +0000747 } else {
748 // We are trying to initialize a bitfield with a non-trivial constant,
749 // this must require run-time code.
750 return false;
751 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000752 }
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000753 }
754
Richard Smithdafff942012-01-14 04:30:29 +0000755 return true;
756}
757
Richard Smithc8998922012-02-23 08:33:23 +0000758namespace {
759struct BaseInfo {
760 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index)
761 : Decl(Decl), Offset(Offset), Index(Index) {
762 }
763
764 const CXXRecordDecl *Decl;
765 CharUnits Offset;
766 unsigned Index;
767
768 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; }
769};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000770}
Richard Smithc8998922012-02-23 08:33:23 +0000771
John McCallde0fe072017-08-15 21:42:52 +0000772bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000773 bool IsPrimaryBase,
Richard Smithc8998922012-02-23 08:33:23 +0000774 const CXXRecordDecl *VTableClass,
775 CharUnits Offset) {
Richard Smithdafff942012-01-14 04:30:29 +0000776 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD);
777
Richard Smithc8998922012-02-23 08:33:23 +0000778 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
779 // Add a vtable pointer, if we need one and it hasn't already been added.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000780 if (CD->isDynamicClass() && !IsPrimaryBase) {
781 llvm::Constant *VTableAddressPoint =
782 CGM.getCXXABI().getVTableAddressPointForConstExpr(
783 BaseSubobject(CD, Offset), VTableClass);
Richard Smith5745feb2019-06-17 21:08:30 +0000784 if (!AppendBytes(Offset, VTableAddressPoint))
785 return false;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000786 }
Richard Smithc8998922012-02-23 08:33:23 +0000787
788 // Accumulate and sort bases, in order to visit them in address order, which
789 // may not be the same as declaration order.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000790 SmallVector<BaseInfo, 8> Bases;
Richard Smithc8998922012-02-23 08:33:23 +0000791 Bases.reserve(CD->getNumBases());
Richard Smithdafff942012-01-14 04:30:29 +0000792 unsigned BaseNo = 0;
Richard Smithc8998922012-02-23 08:33:23 +0000793 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(),
Richard Smithdafff942012-01-14 04:30:29 +0000794 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) {
Richard Smithc8998922012-02-23 08:33:23 +0000795 assert(!Base->isVirtual() && "should not have virtual bases here");
Richard Smithdafff942012-01-14 04:30:29 +0000796 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl();
797 CharUnits BaseOffset = Layout.getBaseClassOffset(BD);
Richard Smithc8998922012-02-23 08:33:23 +0000798 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo));
799 }
Fangrui Song899d1392019-04-24 14:43:05 +0000800 llvm::stable_sort(Bases);
Richard Smithdafff942012-01-14 04:30:29 +0000801
Richard Smithc8998922012-02-23 08:33:23 +0000802 for (unsigned I = 0, N = Bases.size(); I != N; ++I) {
803 BaseInfo &Base = Bases[I];
Richard Smithdafff942012-01-14 04:30:29 +0000804
Richard Smithc8998922012-02-23 08:33:23 +0000805 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl;
806 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase,
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000807 VTableClass, Offset + Base.Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000808 }
809 }
810
811 unsigned FieldNo = 0;
Eli Friedmana154dd52012-03-30 03:55:31 +0000812 uint64_t OffsetBits = CGM.getContext().toBits(Offset);
Richard Smithdafff942012-01-14 04:30:29 +0000813
Richard Smith78b239e2019-06-20 20:44:45 +0000814 bool AllowOverwrite = false;
Richard Smithdafff942012-01-14 04:30:29 +0000815 for (RecordDecl::field_iterator Field = RD->field_begin(),
816 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
Richard Smithdafff942012-01-14 04:30:29 +0000817 // If this is a union, skip all the fields that aren't being initialized.
David Blaikie275a55c2019-05-22 20:36:06 +0000818 if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field))
Richard Smithdafff942012-01-14 04:30:29 +0000819 continue;
820
Richard Smith78b239e2019-06-20 20:44:45 +0000821 // Don't emit anonymous bitfields or zero-sized fields.
822 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext()))
Richard Smithdafff942012-01-14 04:30:29 +0000823 continue;
Richard Smithdafff942012-01-14 04:30:29 +0000824
825 // Emit the value of the initializer.
826 const APValue &FieldValue =
827 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo);
828 llvm::Constant *EltInit =
John McCallde0fe072017-08-15 21:42:52 +0000829 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType());
830 if (!EltInit)
831 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000832
833 if (!Field->isBitField()) {
834 // Handle non-bitfield members.
Richard Smith5745feb2019-06-17 21:08:30 +0000835 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smith78b239e2019-06-20 20:44:45 +0000836 EltInit, AllowOverwrite))
Richard Smith5745feb2019-06-17 21:08:30 +0000837 return false;
Richard Smith78b239e2019-06-20 20:44:45 +0000838 // After emitting a non-empty field with [[no_unique_address]], we may
839 // need to overwrite its tail padding.
840 if (Field->hasAttr<NoUniqueAddressAttr>())
841 AllowOverwrite = true;
Richard Smithdafff942012-01-14 04:30:29 +0000842 } else {
843 // Otherwise we have a bitfield.
Richard Smith5745feb2019-06-17 21:08:30 +0000844 if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits,
Richard Smith78b239e2019-06-20 20:44:45 +0000845 cast<llvm::ConstantInt>(EltInit), AllowOverwrite))
Richard Smith5745feb2019-06-17 21:08:30 +0000846 return false;
Richard Smithdafff942012-01-14 04:30:29 +0000847 }
848 }
John McCallde0fe072017-08-15 21:42:52 +0000849
850 return true;
Richard Smithdafff942012-01-14 04:30:29 +0000851}
852
Richard Smith5745feb2019-06-17 21:08:30 +0000853llvm::Constant *ConstStructBuilder::Finalize(QualType Type) {
Simon Pilgrim1cd399c2019-10-03 11:22:48 +0000854 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
Richard Smith5745feb2019-06-17 21:08:30 +0000855 llvm::Type *ValTy = CGM.getTypes().ConvertType(Type);
856 return Builder.build(ValTy, RD->hasFlexibleArrayMember());
Yunzhong Gaocb779302015-06-10 00:27:52 +0000857}
858
John McCallde0fe072017-08-15 21:42:52 +0000859llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
860 InitListExpr *ILE,
861 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000862 ConstantAggregateBuilder Const(Emitter.CGM);
863 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithdafff942012-01-14 04:30:29 +0000864
Richard Smith5745feb2019-06-17 21:08:30 +0000865 if (!Builder.Build(ILE, /*AllowOverwrite*/false))
Craig Topper8a13c412014-05-21 05:09:00 +0000866 return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +0000867
John McCallde0fe072017-08-15 21:42:52 +0000868 return Builder.Finalize(ValTy);
Richard Smithdafff942012-01-14 04:30:29 +0000869}
870
John McCallde0fe072017-08-15 21:42:52 +0000871llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter,
Richard Smithdafff942012-01-14 04:30:29 +0000872 const APValue &Val,
873 QualType ValTy) {
Richard Smith5745feb2019-06-17 21:08:30 +0000874 ConstantAggregateBuilder Const(Emitter.CGM);
875 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero());
Richard Smithc8998922012-02-23 08:33:23 +0000876
877 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl();
878 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
John McCallde0fe072017-08-15 21:42:52 +0000879 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero()))
880 return nullptr;
Richard Smithc8998922012-02-23 08:33:23 +0000881
Richard Smithdafff942012-01-14 04:30:29 +0000882 return Builder.Finalize(ValTy);
883}
884
Richard Smith5745feb2019-06-17 21:08:30 +0000885bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter,
886 ConstantAggregateBuilder &Const,
887 CharUnits Offset, InitListExpr *Updater) {
888 return ConstStructBuilder(Emitter, Const, Offset)
889 .Build(Updater, /*AllowOverwrite*/ true);
890}
Richard Smithdafff942012-01-14 04:30:29 +0000891
Chris Lattnercfa3e7a2010-04-13 17:45:57 +0000892//===----------------------------------------------------------------------===//
893// ConstExprEmitter
894//===----------------------------------------------------------------------===//
Richard Smithdd5bdd82012-01-17 21:42:19 +0000895
John McCallde0fe072017-08-15 21:42:52 +0000896static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM,
897 CodeGenFunction *CGF,
898 const CompoundLiteralExpr *E) {
899 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType());
900 if (llvm::GlobalVariable *Addr =
901 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E))
902 return ConstantAddress(Addr, Align);
903
Alexander Richardson6d989432017-10-15 18:48:14 +0000904 LangAS addressSpace = E->getType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +0000905
906 ConstantEmitter emitter(CGM, CGF);
907 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(),
908 addressSpace, E->getType());
909 if (!C) {
910 assert(!E->isFileScope() &&
911 "file-scope compound literal did not have constant initializer!");
912 return ConstantAddress::invalid();
913 }
914
915 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(),
916 CGM.isTypeConstant(E->getType(), true),
917 llvm::GlobalValue::InternalLinkage,
918 C, ".compoundliteral", nullptr,
919 llvm::GlobalVariable::NotThreadLocal,
920 CGM.getContext().getTargetAddressSpace(addressSpace));
921 emitter.finalize(GV);
Guillaume Chateletc79099e2019-10-03 13:00:29 +0000922 GV->setAlignment(Align.getAsAlign());
John McCallde0fe072017-08-15 21:42:52 +0000923 CGM.setAddrOfConstantCompoundLiteral(E, GV);
924 return ConstantAddress(GV, Align);
925}
926
Richard Smith3e268632018-05-23 23:41:38 +0000927static llvm::Constant *
Richard Smith5745feb2019-06-17 21:08:30 +0000928EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType,
Richard Smith3e268632018-05-23 23:41:38 +0000929 llvm::Type *CommonElementType, unsigned ArrayBound,
930 SmallVectorImpl<llvm::Constant *> &Elements,
931 llvm::Constant *Filler) {
932 // Figure out how long the initial prefix of non-zero elements is.
933 unsigned NonzeroLength = ArrayBound;
934 if (Elements.size() < NonzeroLength && Filler->isNullValue())
935 NonzeroLength = Elements.size();
936 if (NonzeroLength == Elements.size()) {
937 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue())
938 --NonzeroLength;
939 }
940
Richard Smith5745feb2019-06-17 21:08:30 +0000941 if (NonzeroLength == 0)
942 return llvm::ConstantAggregateZero::get(DesiredType);
Richard Smith3e268632018-05-23 23:41:38 +0000943
944 // Add a zeroinitializer array filler if we have lots of trailing zeroes.
945 unsigned TrailingZeroes = ArrayBound - NonzeroLength;
946 if (TrailingZeroes >= 8) {
947 assert(Elements.size() >= NonzeroLength &&
948 "missing initializer for non-zero element");
Richard Smith83497d92018-07-19 21:38:56 +0000949
950 // If all the elements had the same type up to the trailing zeroes, emit a
951 // struct of two arrays (the nonzero data and the zeroinitializer).
952 if (CommonElementType && NonzeroLength >= 8) {
953 llvm::Constant *Initial = llvm::ConstantArray::get(
Richard Smith4c656882018-07-19 23:24:41 +0000954 llvm::ArrayType::get(CommonElementType, NonzeroLength),
Richard Smith83497d92018-07-19 21:38:56 +0000955 makeArrayRef(Elements).take_front(NonzeroLength));
956 Elements.resize(2);
957 Elements[0] = Initial;
958 } else {
959 Elements.resize(NonzeroLength + 1);
960 }
961
Richard Smith3e268632018-05-23 23:41:38 +0000962 auto *FillerType =
Richard Smith5745feb2019-06-17 21:08:30 +0000963 CommonElementType ? CommonElementType : DesiredType->getElementType();
Richard Smith3e268632018-05-23 23:41:38 +0000964 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes);
965 Elements.back() = llvm::ConstantAggregateZero::get(FillerType);
966 CommonElementType = nullptr;
967 } else if (Elements.size() != ArrayBound) {
968 // Otherwise pad to the right size with the filler if necessary.
969 Elements.resize(ArrayBound, Filler);
970 if (Filler->getType() != CommonElementType)
971 CommonElementType = nullptr;
972 }
973
974 // If all elements have the same type, just emit an array constant.
975 if (CommonElementType)
976 return llvm::ConstantArray::get(
977 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements);
978
979 // We have mixed types. Use a packed struct.
980 llvm::SmallVector<llvm::Type *, 16> Types;
981 Types.reserve(Elements.size());
982 for (llvm::Constant *Elt : Elements)
983 Types.push_back(Elt->getType());
984 llvm::StructType *SType =
985 llvm::StructType::get(CGM.getLLVMContext(), Types, true);
986 return llvm::ConstantStruct::get(SType, Elements);
987}
988
Eli Friedman7f98e3c2019-02-08 21:36:04 +0000989// This class only needs to handle arrays, structs and unions. Outside C++11
990// mode, we don't currently constant fold those types. All other types are
991// handled by constant folding.
992//
993// Constant folding is currently missing support for a few features supported
994// here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr.
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000995class ConstExprEmitter :
John McCallde0fe072017-08-15 21:42:52 +0000996 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> {
Anders Carlsson610ee712008-01-26 01:36:00 +0000997 CodeGenModule &CGM;
John McCallde0fe072017-08-15 21:42:52 +0000998 ConstantEmitter &Emitter;
Owen Anderson170229f2009-07-14 23:10:40 +0000999 llvm::LLVMContext &VMContext;
Anders Carlsson610ee712008-01-26 01:36:00 +00001000public:
John McCallde0fe072017-08-15 21:42:52 +00001001 ConstExprEmitter(ConstantEmitter &emitter)
1002 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) {
Anders Carlsson610ee712008-01-26 01:36:00 +00001003 }
Mike Stump11289f42009-09-09 15:08:12 +00001004
Anders Carlsson610ee712008-01-26 01:36:00 +00001005 //===--------------------------------------------------------------------===//
1006 // Visitor Methods
1007 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +00001008
John McCallde0fe072017-08-15 21:42:52 +00001009 llvm::Constant *VisitStmt(Stmt *S, QualType T) {
Craig Topper8a13c412014-05-21 05:09:00 +00001010 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +00001011 }
Mike Stump11289f42009-09-09 15:08:12 +00001012
Bill Wendling8003edc2018-11-09 00:41:36 +00001013 llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) {
1014 return Visit(CE->getSubExpr(), T);
1015 }
1016
John McCallde0fe072017-08-15 21:42:52 +00001017 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) {
1018 return Visit(PE->getSubExpr(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +00001019 }
Mike Stump11289f42009-09-09 15:08:12 +00001020
John McCall7c454bb2011-07-15 05:09:51 +00001021 llvm::Constant *
John McCallde0fe072017-08-15 21:42:52 +00001022 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE,
1023 QualType T) {
1024 return Visit(PE->getReplacement(), T);
John McCall7c454bb2011-07-15 05:09:51 +00001025 }
1026
John McCallde0fe072017-08-15 21:42:52 +00001027 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE,
1028 QualType T) {
1029 return Visit(GE->getResultExpr(), T);
Peter Collingbourne91147592011-04-15 00:35:48 +00001030 }
1031
John McCallde0fe072017-08-15 21:42:52 +00001032 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) {
1033 return Visit(CE->getChosenSubExpr(), T);
Eli Friedman4c27ac22013-07-16 22:40:53 +00001034 }
1035
John McCallde0fe072017-08-15 21:42:52 +00001036 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) {
1037 return Visit(E->getInitializer(), T);
Anders Carlsson610ee712008-01-26 01:36:00 +00001038 }
John McCallf3a88602011-02-03 08:15:49 +00001039
John McCallde0fe072017-08-15 21:42:52 +00001040 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +00001041 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E))
John McCallde0fe072017-08-15 21:42:52 +00001042 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF);
John McCall2de87f62011-03-15 21:17:48 +00001043 Expr *subExpr = E->getSubExpr();
John McCall2de87f62011-03-15 21:17:48 +00001044
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001045 switch (E->getCastKind()) {
John McCalle3027922010-08-25 11:45:40 +00001046 case CK_ToUnion: {
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001047 // GCC cast to union extension
1048 assert(E->getType()->isUnionType() &&
1049 "Destination type is not union type!");
Mike Stump11289f42009-09-09 15:08:12 +00001050
John McCallde0fe072017-08-15 21:42:52 +00001051 auto field = E->getTargetUnionField();
1052
1053 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType());
1054 if (!C) return nullptr;
1055
1056 auto destTy = ConvertType(destType);
1057 if (C->getType() == destTy) return C;
1058
Anders Carlssond65ab042009-07-31 21:38:39 +00001059 // Build a struct with the union sub-element as the first member,
John McCallde0fe072017-08-15 21:42:52 +00001060 // and padded to the appropriate size.
Bill Wendling99729582012-02-07 00:13:27 +00001061 SmallVector<llvm::Constant*, 2> Elts;
1062 SmallVector<llvm::Type*, 2> Types;
Anders Carlssond65ab042009-07-31 21:38:39 +00001063 Elts.push_back(C);
1064 Types.push_back(C->getType());
Micah Villmowdd31ca12012-10-08 16:25:52 +00001065 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType());
John McCallde0fe072017-08-15 21:42:52 +00001066 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy);
Mike Stump11289f42009-09-09 15:08:12 +00001067
Anders Carlssond65ab042009-07-31 21:38:39 +00001068 assert(CurSize <= TotalSize && "Union size mismatch!");
1069 if (unsigned NumPadBytes = TotalSize - CurSize) {
Chris Lattnerece04092012-02-07 00:39:47 +00001070 llvm::Type *Ty = CGM.Int8Ty;
Anders Carlssond65ab042009-07-31 21:38:39 +00001071 if (NumPadBytes > 1)
1072 Ty = llvm::ArrayType::get(Ty, NumPadBytes);
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001073
Nuno Lopes5863c992010-04-16 20:56:35 +00001074 Elts.push_back(llvm::UndefValue::get(Ty));
Anders Carlssond65ab042009-07-31 21:38:39 +00001075 Types.push_back(Ty);
1076 }
Mike Stump11289f42009-09-09 15:08:12 +00001077
John McCallde0fe072017-08-15 21:42:52 +00001078 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false);
Anders Carlssond65ab042009-07-31 21:38:39 +00001079 return llvm::ConstantStruct::get(STy, Elts);
Nuno Lopes4d78cf02009-01-17 00:48:48 +00001080 }
Anders Carlsson9500ad12009-10-18 20:31:03 +00001081
John McCallde0fe072017-08-15 21:42:52 +00001082 case CK_AddressSpaceConversion: {
1083 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1084 if (!C) return nullptr;
Alexander Richardson6d989432017-10-15 18:48:14 +00001085 LangAS destAS = E->getType()->getPointeeType().getAddressSpace();
1086 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace();
John McCallde0fe072017-08-15 21:42:52 +00001087 llvm::Type *destTy = ConvertType(E->getType());
1088 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS,
1089 destAS, destTy);
1090 }
David Tweede1468322013-12-11 13:39:46 +00001091
John McCall2de87f62011-03-15 21:17:48 +00001092 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00001093 case CK_AtomicToNonAtomic:
1094 case CK_NonAtomicToAtomic:
John McCall2de87f62011-03-15 21:17:48 +00001095 case CK_NoOp:
Eli Friedman4c27ac22013-07-16 22:40:53 +00001096 case CK_ConstructorConversion:
John McCallde0fe072017-08-15 21:42:52 +00001097 return Visit(subExpr, destType);
Anders Carlsson9500ad12009-10-18 20:31:03 +00001098
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00001099 case CK_IntToOCLSampler:
1100 llvm_unreachable("global sampler variables are not generated");
1101
John McCall2de87f62011-03-15 21:17:48 +00001102 case CK_Dependent: llvm_unreachable("saw dependent cast!");
1103
Eli Friedman34866c72012-08-31 00:14:07 +00001104 case CK_BuiltinFnToFnPtr:
1105 llvm_unreachable("builtin functions are handled elsewhere");
1106
John McCallc62bb392012-02-15 01:22:51 +00001107 case CK_ReinterpretMemberPointer:
1108 case CK_DerivedToBaseMemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00001109 case CK_BaseToDerivedMemberPointer: {
1110 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType());
1111 if (!C) return nullptr;
John McCallc62bb392012-02-15 01:22:51 +00001112 return CGM.getCXXABI().EmitMemberPointerConversion(E, C);
John McCallde0fe072017-08-15 21:42:52 +00001113 }
John McCallc62bb392012-02-15 01:22:51 +00001114
John McCall2de87f62011-03-15 21:17:48 +00001115 // These will never be supported.
1116 case CK_ObjCObjectLValueCast:
John McCall2d637d22011-09-10 06:18:15 +00001117 case CK_ARCProduceObject:
1118 case CK_ARCConsumeObject:
1119 case CK_ARCReclaimReturnedObject:
1120 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00001121 case CK_CopyAndAutoreleaseBlockObject:
Craig Topper8a13c412014-05-21 05:09:00 +00001122 return nullptr;
John McCall2de87f62011-03-15 21:17:48 +00001123
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001124 // These don't need to be handled here because Evaluate knows how to
Richard Smithdd5bdd82012-01-17 21:42:19 +00001125 // evaluate them in the cases where they can be folded.
John McCallc62bb392012-02-15 01:22:51 +00001126 case CK_BitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001127 case CK_ToVoid:
1128 case CK_Dynamic:
1129 case CK_LValueBitCast:
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00001130 case CK_LValueToRValueBitCast:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001131 case CK_NullToMemberPointer:
Richard Smithdd5bdd82012-01-17 21:42:19 +00001132 case CK_UserDefinedConversion:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001133 case CK_CPointerToObjCPointerCast:
1134 case CK_BlockPointerToObjCPointerCast:
1135 case CK_AnyPointerToBlockPointerCast:
John McCall2de87f62011-03-15 21:17:48 +00001136 case CK_ArrayToPointerDecay:
1137 case CK_FunctionToPointerDecay:
1138 case CK_BaseToDerived:
1139 case CK_DerivedToBase:
1140 case CK_UncheckedDerivedToBase:
1141 case CK_MemberPointerToBoolean:
1142 case CK_VectorSplat:
1143 case CK_FloatingRealToComplex:
1144 case CK_FloatingComplexToReal:
1145 case CK_FloatingComplexToBoolean:
1146 case CK_FloatingComplexCast:
1147 case CK_FloatingComplexToIntegralComplex:
1148 case CK_IntegralRealToComplex:
1149 case CK_IntegralComplexToReal:
1150 case CK_IntegralComplexToBoolean:
1151 case CK_IntegralComplexCast:
1152 case CK_IntegralComplexToFloatingComplex:
John McCall2de87f62011-03-15 21:17:48 +00001153 case CK_PointerToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001154 case CK_PointerToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001155 case CK_NullToPointer:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001156 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00001157 case CK_BooleanToSignedIntegral:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001158 case CK_IntegralToPointer:
John McCall2de87f62011-03-15 21:17:48 +00001159 case CK_IntegralToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001160 case CK_IntegralToFloating:
John McCall2de87f62011-03-15 21:17:48 +00001161 case CK_FloatingToIntegral:
John McCall2de87f62011-03-15 21:17:48 +00001162 case CK_FloatingToBoolean:
John McCall2de87f62011-03-15 21:17:48 +00001163 case CK_FloatingCast:
Leonard Chan99bda372018-10-15 16:07:02 +00001164 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00001165 case CK_FixedPointToBoolean:
Leonard Chan8f7caae2019-03-06 00:28:43 +00001166 case CK_FixedPointToIntegral:
1167 case CK_IntegralToFixedPoint:
Andrew Savonichevb555b762018-10-23 15:19:20 +00001168 case CK_ZeroToOCLOpaqueType:
Craig Topper8a13c412014-05-21 05:09:00 +00001169 return nullptr;
Anders Carlsson3b0c5dc2009-08-22 23:54:44 +00001170 }
Matt Beaumont-Gay145e2eb2011-03-17 00:46:34 +00001171 llvm_unreachable("Invalid CastKind");
Anders Carlsson610ee712008-01-26 01:36:00 +00001172 }
Devang Patela703a672008-02-05 02:39:50 +00001173
John McCallde0fe072017-08-15 21:42:52 +00001174 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) {
Richard Smith852c9db2013-04-20 22:23:05 +00001175 // No need for a DefaultInitExprScope: we don't handle 'this' in a
1176 // constant expression.
John McCallde0fe072017-08-15 21:42:52 +00001177 return Visit(DIE->getExpr(), T);
Richard Smith852c9db2013-04-20 22:23:05 +00001178 }
1179
John McCallde0fe072017-08-15 21:42:52 +00001180 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) {
Akira Hatanakad35a4542019-11-20 18:13:44 -08001181 return Visit(E->getSubExpr(), T);
Tim Shen4a05bb82016-06-21 20:29:17 +00001182 }
1183
John McCallde0fe072017-08-15 21:42:52 +00001184 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E,
1185 QualType T) {
Tykerb0561b32019-11-17 11:41:55 +01001186 return Visit(E->getSubExpr(), T);
Douglas Gregorfe314812011-06-21 17:03:29 +00001187 }
1188
John McCallde0fe072017-08-15 21:42:52 +00001189 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) {
Richard Smith3e268632018-05-23 23:41:38 +00001190 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType());
1191 assert(CAT && "can't emit array init for non-constant-bound array");
Richard Smith9ec1e482012-04-15 02:50:59 +00001192 unsigned NumInitElements = ILE->getNumInits();
Richard Smith3e268632018-05-23 23:41:38 +00001193 unsigned NumElements = CAT->getSize().getZExtValue();
Devang Patela703a672008-02-05 02:39:50 +00001194
Mike Stump11289f42009-09-09 15:08:12 +00001195 // Initialising an array requires us to automatically
Devang Patela703a672008-02-05 02:39:50 +00001196 // initialise any elements that have not been initialised explicitly
1197 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
1198
Richard Smith3e268632018-05-23 23:41:38 +00001199 QualType EltType = CAT->getElementType();
John McCallde0fe072017-08-15 21:42:52 +00001200
David Majnemer90d85442014-12-28 23:46:59 +00001201 // Initialize remaining array elements.
Richard Smith3e268632018-05-23 23:41:38 +00001202 llvm::Constant *fillC = nullptr;
1203 if (Expr *filler = ILE->getArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00001204 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType);
Richard Smith3e268632018-05-23 23:41:38 +00001205 if (!fillC)
1206 return nullptr;
1207 }
David Majnemer90d85442014-12-28 23:46:59 +00001208
Devang Patela703a672008-02-05 02:39:50 +00001209 // Copy initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00001210 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00001211 if (fillC && fillC->isNullValue())
1212 Elts.reserve(NumInitableElts + 1);
1213 else
1214 Elts.reserve(NumElements);
Benjamin Kramer8001f742012-02-14 12:06:21 +00001215
Richard Smith3e268632018-05-23 23:41:38 +00001216 llvm::Type *CommonElementType = nullptr;
Benjamin Kramer8001f742012-02-14 12:06:21 +00001217 for (unsigned i = 0; i < NumInitableElts; ++i) {
Anders Carlsson80f97ab2009-04-08 04:48:15 +00001218 Expr *Init = ILE->getInit(i);
John McCallde0fe072017-08-15 21:42:52 +00001219 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType);
Daniel Dunbar38ad1e62009-02-17 18:43:32 +00001220 if (!C)
Craig Topper8a13c412014-05-21 05:09:00 +00001221 return nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00001222 if (i == 0)
1223 CommonElementType = C->getType();
1224 else if (C->getType() != CommonElementType)
1225 CommonElementType = nullptr;
Devang Patela703a672008-02-05 02:39:50 +00001226 Elts.push_back(C);
1227 }
Eli Friedman34994cb2008-05-30 19:58:50 +00001228
Richard Smith5745feb2019-06-17 21:08:30 +00001229 llvm::ArrayType *Desired =
1230 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType()));
1231 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00001232 fillC);
Devang Patela703a672008-02-05 02:39:50 +00001233 }
1234
John McCallde0fe072017-08-15 21:42:52 +00001235 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) {
1236 return ConstStructBuilder::BuildStruct(Emitter, ILE, T);
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001237 }
1238
John McCallde0fe072017-08-15 21:42:52 +00001239 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E,
1240 QualType T) {
1241 return CGM.EmitNullConstant(T);
Anders Carlsson02714ed2009-01-30 06:13:25 +00001242 }
Mike Stump11289f42009-09-09 15:08:12 +00001243
John McCallde0fe072017-08-15 21:42:52 +00001244 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) {
Richard Smith122f88d2016-12-06 23:52:28 +00001245 if (ILE->isTransparent())
John McCallde0fe072017-08-15 21:42:52 +00001246 return Visit(ILE->getInit(0), T);
Richard Smith122f88d2016-12-06 23:52:28 +00001247
Eli Friedmana2eaffc2008-05-30 10:24:46 +00001248 if (ILE->getType()->isArrayType())
John McCallde0fe072017-08-15 21:42:52 +00001249 return EmitArrayInitialization(ILE, T);
Devang Patel45a65d22008-01-29 23:23:18 +00001250
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001251 if (ILE->getType()->isRecordType())
John McCallde0fe072017-08-15 21:42:52 +00001252 return EmitRecordInitialization(ILE, T);
Jin-Gu Kang1a5e4232012-09-05 08:37:43 +00001253
Craig Topper8a13c412014-05-21 05:09:00 +00001254 return nullptr;
Anders Carlsson610ee712008-01-26 01:36:00 +00001255 }
Eli Friedmana2433112008-02-21 17:57:49 +00001256
John McCallde0fe072017-08-15 21:42:52 +00001257 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E,
1258 QualType destType) {
1259 auto C = Visit(E->getBase(), destType);
Richard Smith5745feb2019-06-17 21:08:30 +00001260 if (!C)
1261 return nullptr;
1262
1263 ConstantAggregateBuilder Const(CGM);
1264 Const.add(C, CharUnits::Zero(), false);
1265
1266 if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType,
1267 E->getUpdater()))
1268 return nullptr;
1269
1270 llvm::Type *ValTy = CGM.getTypes().ConvertType(destType);
1271 bool HasFlexibleArray = false;
1272 if (auto *RT = destType->getAs<RecordType>())
1273 HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember();
1274 return Const.build(ValTy, HasFlexibleArray);
Fangrui Song6907ce22018-07-30 19:24:48 +00001275 }
Yunzhong Gaocb779302015-06-10 00:27:52 +00001276
John McCallde0fe072017-08-15 21:42:52 +00001277 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) {
John McCall49786a62010-02-02 08:02:49 +00001278 if (!E->getConstructor()->isTrivial())
Craig Topper8a13c412014-05-21 05:09:00 +00001279 return nullptr;
John McCall49786a62010-02-02 08:02:49 +00001280
Richard Smith96c89942020-02-06 16:19:37 -08001281 // Only default and copy/move constructors can be trivial.
John McCall49786a62010-02-02 08:02:49 +00001282 if (E->getNumArgs()) {
1283 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001284 assert(E->getConstructor()->isCopyOrMoveConstructor() &&
1285 "trivial ctor has argument but isn't a copy/move ctor");
John McCall49786a62010-02-02 08:02:49 +00001286
1287 Expr *Arg = E->getArg(0);
1288 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) &&
1289 "argument to copy ctor is of wrong type");
1290
John McCallde0fe072017-08-15 21:42:52 +00001291 return Visit(Arg, Ty);
John McCall49786a62010-02-02 08:02:49 +00001292 }
1293
1294 return CGM.EmitNullConstant(Ty);
1295 }
1296
John McCallde0fe072017-08-15 21:42:52 +00001297 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) {
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001298 // This is a string literal initializing an array in an initializer.
Eli Friedmanfcec6302011-11-01 02:23:42 +00001299 return CGM.GetConstantArrayFromStringLiteral(E);
Anders Carlsson610ee712008-01-26 01:36:00 +00001300 }
1301
John McCallde0fe072017-08-15 21:42:52 +00001302 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) {
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001303 // This must be an @encode initializing an array in a static initializer.
1304 // Don't emit it as the address of the string, emit the string data itself
1305 // as an inline array.
1306 std::string Str;
1307 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str);
John McCallde0fe072017-08-15 21:42:52 +00001308 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T);
Mike Stump11289f42009-09-09 15:08:12 +00001309
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001310 // Resize the string to the right size, adding zeros at the end, or
1311 // truncating as needed.
1312 Str.resize(CAT->getSize().getZExtValue(), '\0');
Chris Lattner9c818332012-02-05 02:30:40 +00001313 return llvm::ConstantDataArray::getString(VMContext, Str, false);
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +00001314 }
Mike Stump11289f42009-09-09 15:08:12 +00001315
John McCallde0fe072017-08-15 21:42:52 +00001316 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) {
1317 return Visit(E->getSubExpr(), T);
Eli Friedman045bf4f2008-05-29 11:22:45 +00001318 }
Mike Stumpa6703322009-02-19 22:01:56 +00001319
Anders Carlsson610ee712008-01-26 01:36:00 +00001320 // Utility methods
Chris Lattner2192fe52011-07-18 04:24:23 +00001321 llvm::Type *ConvertType(QualType T) {
Anders Carlsson610ee712008-01-26 01:36:00 +00001322 return CGM.getTypes().ConvertType(T);
1323 }
Anders Carlssona4139112008-01-26 02:08:50 +00001324};
Mike Stump11289f42009-09-09 15:08:12 +00001325
Anders Carlsson610ee712008-01-26 01:36:00 +00001326} // end anonymous namespace.
1327
John McCallde0fe072017-08-15 21:42:52 +00001328llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C,
1329 AbstractState saved) {
1330 Abstract = saved.OldValue;
1331
1332 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() &&
1333 "created a placeholder while doing an abstract emission?");
1334
1335 // No validation necessary for now.
1336 // No cleanup to do for now.
1337 return C;
1338}
1339
1340llvm::Constant *
1341ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) {
1342 auto state = pushAbstract();
1343 auto C = tryEmitPrivateForVarInit(D);
1344 return validateAndPopAbstract(C, state);
1345}
1346
1347llvm::Constant *
1348ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) {
1349 auto state = pushAbstract();
1350 auto C = tryEmitPrivate(E, destType);
1351 return validateAndPopAbstract(C, state);
1352}
1353
1354llvm::Constant *
1355ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) {
1356 auto state = pushAbstract();
1357 auto C = tryEmitPrivate(value, destType);
1358 return validateAndPopAbstract(C, state);
1359}
1360
1361llvm::Constant *
1362ConstantEmitter::emitAbstract(const Expr *E, QualType destType) {
1363 auto state = pushAbstract();
1364 auto C = tryEmitPrivate(E, destType);
1365 C = validateAndPopAbstract(C, state);
1366 if (!C) {
1367 CGM.Error(E->getExprLoc(),
1368 "internal error: could not emit constant value \"abstractly\"");
1369 C = CGM.EmitNullConstant(destType);
1370 }
1371 return C;
1372}
1373
1374llvm::Constant *
1375ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value,
1376 QualType destType) {
1377 auto state = pushAbstract();
1378 auto C = tryEmitPrivate(value, destType);
1379 C = validateAndPopAbstract(C, state);
1380 if (!C) {
1381 CGM.Error(loc,
1382 "internal error: could not emit constant value \"abstractly\"");
1383 C = CGM.EmitNullConstant(destType);
1384 }
1385 return C;
1386}
1387
1388llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) {
1389 initializeNonAbstract(D.getType().getAddressSpace());
1390 return markIfFailed(tryEmitPrivateForVarInit(D));
1391}
1392
1393llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E,
Alexander Richardson6d989432017-10-15 18:48:14 +00001394 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001395 QualType destType) {
1396 initializeNonAbstract(destAddrSpace);
1397 return markIfFailed(tryEmitPrivateForMemory(E, destType));
1398}
1399
1400llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value,
Alexander Richardson6d989432017-10-15 18:48:14 +00001401 LangAS destAddrSpace,
John McCallde0fe072017-08-15 21:42:52 +00001402 QualType destType) {
1403 initializeNonAbstract(destAddrSpace);
1404 auto C = tryEmitPrivateForMemory(value, destType);
1405 assert(C && "couldn't emit constant value non-abstractly?");
1406 return C;
1407}
1408
1409llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() {
1410 assert(!Abstract && "cannot get current address for abstract constant");
1411
1412
1413
1414 // Make an obviously ill-formed global that should blow up compilation
1415 // if it survives.
1416 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true,
1417 llvm::GlobalValue::PrivateLinkage,
1418 /*init*/ nullptr,
1419 /*name*/ "",
1420 /*before*/ nullptr,
1421 llvm::GlobalVariable::NotThreadLocal,
1422 CGM.getContext().getTargetAddressSpace(DestAddressSpace));
1423
1424 PlaceholderAddresses.push_back(std::make_pair(nullptr, global));
1425
1426 return global;
1427}
1428
1429void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal,
1430 llvm::GlobalValue *placeholder) {
1431 assert(!PlaceholderAddresses.empty());
1432 assert(PlaceholderAddresses.back().first == nullptr);
1433 assert(PlaceholderAddresses.back().second == placeholder);
1434 PlaceholderAddresses.back().first = signal;
1435}
1436
1437namespace {
1438 struct ReplacePlaceholders {
1439 CodeGenModule &CGM;
1440
1441 /// The base address of the global.
1442 llvm::Constant *Base;
1443 llvm::Type *BaseValueTy = nullptr;
1444
1445 /// The placeholder addresses that were registered during emission.
1446 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses;
1447
1448 /// The locations of the placeholder signals.
1449 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations;
1450
1451 /// The current index stack. We use a simple unsigned stack because
1452 /// we assume that placeholders will be relatively sparse in the
1453 /// initializer, but we cache the index values we find just in case.
1454 llvm::SmallVector<unsigned, 8> Indices;
1455 llvm::SmallVector<llvm::Constant*, 8> IndexValues;
1456
1457 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base,
1458 ArrayRef<std::pair<llvm::Constant*,
1459 llvm::GlobalVariable*>> addresses)
1460 : CGM(CGM), Base(base),
1461 PlaceholderAddresses(addresses.begin(), addresses.end()) {
1462 }
1463
1464 void replaceInInitializer(llvm::Constant *init) {
1465 // Remember the type of the top-most initializer.
1466 BaseValueTy = init->getType();
1467
1468 // Initialize the stack.
1469 Indices.push_back(0);
1470 IndexValues.push_back(nullptr);
1471
1472 // Recurse into the initializer.
1473 findLocations(init);
1474
1475 // Check invariants.
1476 assert(IndexValues.size() == Indices.size() && "mismatch");
1477 assert(Indices.size() == 1 && "didn't pop all indices");
1478
1479 // Do the replacement; this basically invalidates 'init'.
1480 assert(Locations.size() == PlaceholderAddresses.size() &&
1481 "missed a placeholder?");
1482
1483 // We're iterating over a hashtable, so this would be a source of
1484 // non-determinism in compiler output *except* that we're just
1485 // messing around with llvm::Constant structures, which never itself
1486 // does anything that should be visible in compiler output.
1487 for (auto &entry : Locations) {
1488 assert(entry.first->getParent() == nullptr && "not a placeholder!");
1489 entry.first->replaceAllUsesWith(entry.second);
1490 entry.first->eraseFromParent();
1491 }
1492 }
1493
1494 private:
1495 void findLocations(llvm::Constant *init) {
1496 // Recurse into aggregates.
1497 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) {
1498 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) {
1499 Indices.push_back(i);
1500 IndexValues.push_back(nullptr);
1501
1502 findLocations(agg->getOperand(i));
1503
1504 IndexValues.pop_back();
1505 Indices.pop_back();
1506 }
1507 return;
1508 }
1509
1510 // Otherwise, check for registered constants.
1511 while (true) {
1512 auto it = PlaceholderAddresses.find(init);
1513 if (it != PlaceholderAddresses.end()) {
1514 setLocation(it->second);
1515 break;
1516 }
1517
1518 // Look through bitcasts or other expressions.
1519 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) {
1520 init = expr->getOperand(0);
1521 } else {
1522 break;
1523 }
1524 }
1525 }
1526
1527 void setLocation(llvm::GlobalVariable *placeholder) {
1528 assert(Locations.find(placeholder) == Locations.end() &&
1529 "already found location for placeholder!");
1530
1531 // Lazily fill in IndexValues with the values from Indices.
1532 // We do this in reverse because we should always have a strict
1533 // prefix of indices from the start.
1534 assert(Indices.size() == IndexValues.size());
1535 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) {
1536 if (IndexValues[i]) {
1537#ifndef NDEBUG
1538 for (size_t j = 0; j != i + 1; ++j) {
1539 assert(IndexValues[j] &&
1540 isa<llvm::ConstantInt>(IndexValues[j]) &&
1541 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue()
1542 == Indices[j]);
1543 }
1544#endif
1545 break;
1546 }
1547
1548 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]);
1549 }
1550
1551 // Form a GEP and then bitcast to the placeholder type so that the
1552 // replacement will succeed.
1553 llvm::Constant *location =
1554 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy,
1555 Base, IndexValues);
1556 location = llvm::ConstantExpr::getBitCast(location,
1557 placeholder->getType());
1558
1559 Locations.insert({placeholder, location});
1560 }
1561 };
1562}
1563
1564void ConstantEmitter::finalize(llvm::GlobalVariable *global) {
1565 assert(InitializedNonAbstract &&
1566 "finalizing emitter that was used for abstract emission?");
1567 assert(!Finalized && "finalizing emitter multiple times");
1568 assert(global->getInitializer());
1569
1570 // Note that we might also be Failed.
1571 Finalized = true;
1572
1573 if (!PlaceholderAddresses.empty()) {
1574 ReplacePlaceholders(CGM, global, PlaceholderAddresses)
1575 .replaceInInitializer(global->getInitializer());
1576 PlaceholderAddresses.clear(); // satisfy
1577 }
1578}
1579
1580ConstantEmitter::~ConstantEmitter() {
1581 assert((!InitializedNonAbstract || Finalized || Failed) &&
1582 "not finalized after being initialized for non-abstract emission");
1583 assert(PlaceholderAddresses.empty() && "unhandled placeholders");
1584}
1585
1586static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) {
1587 if (auto AT = type->getAs<AtomicType>()) {
1588 return CGM.getContext().getQualifiedType(AT->getValueType(),
1589 type.getQualifiers());
1590 }
1591 return type;
1592}
1593
1594llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
Fariborz Jahaniancc7f0082013-01-10 23:28:43 +00001595 // Make a quick check if variable can be default NULL initialized
1596 // and avoid going through rest of code which may do, for c++11,
1597 // initialization of memory to all NULLs.
Richard Smith3f1d6de2018-05-21 20:36:58 +00001598 if (!D.hasLocalStorage()) {
1599 QualType Ty = CGM.getContext().getBaseElementType(D.getType());
1600 if (Ty->isRecordType())
1601 if (const CXXConstructExpr *E =
1602 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) {
1603 const CXXConstructorDecl *CD = E->getConstructor();
1604 if (CD->isTrivial() && CD->isDefaultConstructor())
1605 return CGM.EmitNullConstant(D.getType());
1606 }
Bill Wendling958b94d2018-12-01 09:06:26 +00001607 InConstantContext = true;
Richard Smith3f1d6de2018-05-21 20:36:58 +00001608 }
John McCallde0fe072017-08-15 21:42:52 +00001609
1610 QualType destType = D.getType();
1611
1612 // Try to emit the initializer. Note that this can allow some things that
1613 // are not allowed by tryEmitPrivateForMemory alone.
1614 if (auto value = D.evaluateValue()) {
1615 return tryEmitPrivateForMemory(*value, destType);
1616 }
Richard Smithdafff942012-01-14 04:30:29 +00001617
Richard Smith6331c402012-02-13 22:16:19 +00001618 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a
1619 // reference is a constant expression, and the reference binds to a temporary,
1620 // then constant initialization is performed. ConstExprEmitter will
1621 // incorrectly emit a prvalue constant in this case, and the calling code
1622 // interprets that as the (pointer) value of the reference, rather than the
1623 // desired value of the referee.
John McCallde0fe072017-08-15 21:42:52 +00001624 if (destType->isReferenceType())
Craig Topper8a13c412014-05-21 05:09:00 +00001625 return nullptr;
Richard Smith6331c402012-02-13 22:16:19 +00001626
Richard Smithdafff942012-01-14 04:30:29 +00001627 const Expr *E = D.getInit();
1628 assert(E && "No initializer to emit");
1629
John McCallde0fe072017-08-15 21:42:52 +00001630 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1631 auto C =
1632 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType);
1633 return (C ? emitForMemory(C, destType) : nullptr);
1634}
1635
1636llvm::Constant *
1637ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) {
1638 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1639 auto C = tryEmitAbstract(E, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001640 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001641}
1642
1643llvm::Constant *
1644ConstantEmitter::tryEmitAbstractForMemory(const APValue &value,
1645 QualType destType) {
1646 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1647 auto C = tryEmitAbstract(value, nonMemoryDestType);
Fangrui Song6907ce22018-07-30 19:24:48 +00001648 return (C ? emitForMemory(C, destType) : nullptr);
John McCallde0fe072017-08-15 21:42:52 +00001649}
1650
1651llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E,
1652 QualType destType) {
1653 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1654 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType);
1655 return (C ? emitForMemory(C, destType) : nullptr);
1656}
1657
1658llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value,
1659 QualType destType) {
1660 auto nonMemoryDestType = getNonMemoryType(CGM, destType);
1661 auto C = tryEmitPrivate(value, nonMemoryDestType);
1662 return (C ? emitForMemory(C, destType) : nullptr);
1663}
1664
1665llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM,
1666 llvm::Constant *C,
1667 QualType destType) {
1668 // For an _Atomic-qualified constant, we may need to add tail padding.
1669 if (auto AT = destType->getAs<AtomicType>()) {
1670 QualType destValueType = AT->getValueType();
1671 C = emitForMemory(CGM, C, destValueType);
1672
1673 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType);
1674 uint64_t outerSize = CGM.getContext().getTypeSize(destType);
1675 if (innerSize == outerSize)
1676 return C;
1677
1678 assert(innerSize < outerSize && "emitted over-large constant for atomic");
1679 llvm::Constant *elts[] = {
1680 C,
1681 llvm::ConstantAggregateZero::get(
1682 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8))
1683 };
1684 return llvm::ConstantStruct::getAnon(elts);
Richard Smithdafff942012-01-14 04:30:29 +00001685 }
John McCallde0fe072017-08-15 21:42:52 +00001686
1687 // Zero-extend bool.
1688 if (C->getType()->isIntegerTy(1)) {
1689 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType);
1690 return llvm::ConstantExpr::getZExt(C, boolTy);
1691 }
1692
Richard Smithdafff942012-01-14 04:30:29 +00001693 return C;
1694}
1695
John McCallde0fe072017-08-15 21:42:52 +00001696llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E,
1697 QualType destType) {
Anders Carlsson38eef1d2008-12-01 02:42:14 +00001698 Expr::EvalResult Result;
Mike Stump11289f42009-09-09 15:08:12 +00001699
Anders Carlssond8e39bb2009-04-11 01:08:03 +00001700 bool Success = false;
Mike Stump11289f42009-09-09 15:08:12 +00001701
John McCallde0fe072017-08-15 21:42:52 +00001702 if (destType->isReferenceType())
1703 Success = E->EvaluateAsLValue(Result, CGM.getContext());
Mike Stump11289f42009-09-09 15:08:12 +00001704 else
Bill Wendling2a81f662018-12-01 08:29:36 +00001705 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext);
Mike Stump11289f42009-09-09 15:08:12 +00001706
John McCallde0fe072017-08-15 21:42:52 +00001707 llvm::Constant *C;
Richard Smithdafff942012-01-14 04:30:29 +00001708 if (Success && !Result.HasSideEffects)
John McCallde0fe072017-08-15 21:42:52 +00001709 C = tryEmitPrivate(Result.Val, destType);
Richard Smithbc6387672012-03-02 23:27:11 +00001710 else
John McCallde0fe072017-08-15 21:42:52 +00001711 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType);
Eli Friedman10c24172008-06-01 15:31:44 +00001712
Eli Friedman10c24172008-06-01 15:31:44 +00001713 return C;
Anders Carlsson610ee712008-01-26 01:36:00 +00001714}
Eli Friedman20bb5e02009-04-13 21:47:26 +00001715
Yaxun Liu402804b2016-12-15 08:09:08 +00001716llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) {
1717 return getTargetCodeGenInfo().getNullPointer(*this, T, QT);
1718}
1719
John McCall99e5e982017-08-17 05:03:55 +00001720namespace {
1721/// A struct which can be used to peephole certain kinds of finalization
1722/// that normally happen during l-value emission.
1723struct ConstantLValue {
1724 llvm::Constant *Value;
1725 bool HasOffsetApplied;
1726
1727 /*implicit*/ ConstantLValue(llvm::Constant *value,
1728 bool hasOffsetApplied = false)
Akira Hatanakaa6d57a82019-12-18 13:54:30 -08001729 : Value(value), HasOffsetApplied(hasOffsetApplied) {}
John McCall99e5e982017-08-17 05:03:55 +00001730
1731 /*implicit*/ ConstantLValue(ConstantAddress address)
1732 : ConstantLValue(address.getPointer()) {}
1733};
1734
1735/// A helper class for emitting constant l-values.
1736class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter,
1737 ConstantLValue> {
1738 CodeGenModule &CGM;
1739 ConstantEmitter &Emitter;
1740 const APValue &Value;
1741 QualType DestType;
1742
1743 // Befriend StmtVisitorBase so that we don't have to expose Visit*.
1744 friend StmtVisitorBase;
1745
1746public:
1747 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value,
1748 QualType destType)
1749 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {}
1750
1751 llvm::Constant *tryEmit();
1752
1753private:
1754 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy);
1755 ConstantLValue tryEmitBase(const APValue::LValueBase &base);
1756
1757 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; }
Bill Wendling8003edc2018-11-09 00:41:36 +00001758 ConstantLValue VisitConstantExpr(const ConstantExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001759 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1760 ConstantLValue VisitStringLiteral(const StringLiteral *E);
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001761 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001762 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
1763 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E);
1764 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E);
1765 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E);
1766 ConstantLValue VisitCallExpr(const CallExpr *E);
1767 ConstantLValue VisitBlockExpr(const BlockExpr *E);
1768 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E);
John McCall99e5e982017-08-17 05:03:55 +00001769 ConstantLValue VisitMaterializeTemporaryExpr(
1770 const MaterializeTemporaryExpr *E);
1771
1772 bool hasNonZeroOffset() const {
1773 return !Value.getLValueOffset().isZero();
1774 }
1775
1776 /// Return the value offset.
1777 llvm::Constant *getOffset() {
1778 return llvm::ConstantInt::get(CGM.Int64Ty,
1779 Value.getLValueOffset().getQuantity());
1780 }
1781
1782 /// Apply the value offset to the given constant.
1783 llvm::Constant *applyOffset(llvm::Constant *C) {
1784 if (!hasNonZeroOffset())
1785 return C;
1786
1787 llvm::Type *origPtrTy = C->getType();
1788 unsigned AS = origPtrTy->getPointerAddressSpace();
1789 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS);
1790 C = llvm::ConstantExpr::getBitCast(C, charPtrTy);
1791 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset());
1792 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy);
1793 return C;
1794 }
1795};
1796
1797}
1798
1799llvm::Constant *ConstantLValueEmitter::tryEmit() {
1800 const APValue::LValueBase &base = Value.getLValueBase();
1801
Eli Friedman7f98e3c2019-02-08 21:36:04 +00001802 // The destination type should be a pointer or reference
John McCall99e5e982017-08-17 05:03:55 +00001803 // type, but it might also be a cast thereof.
1804 //
1805 // FIXME: the chain of casts required should be reflected in the APValue.
1806 // We need this in order to correctly handle things like a ptrtoint of a
1807 // non-zero null pointer and addrspace casts that aren't trivially
1808 // represented in LLVM IR.
1809 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType);
1810 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy));
1811
1812 // If there's no base at all, this is a null or absolute pointer,
1813 // possibly cast back to an integer type.
1814 if (!base) {
1815 return tryEmitAbsolute(destTy);
1816 }
1817
1818 // Otherwise, try to emit the base.
1819 ConstantLValue result = tryEmitBase(base);
1820
1821 // If that failed, we're done.
1822 llvm::Constant *value = result.Value;
1823 if (!value) return nullptr;
1824
1825 // Apply the offset if necessary and not already done.
1826 if (!result.HasOffsetApplied) {
1827 value = applyOffset(value);
1828 }
1829
1830 // Convert to the appropriate type; this could be an lvalue for
1831 // an integer. FIXME: performAddrSpaceCast
1832 if (isa<llvm::PointerType>(destTy))
1833 return llvm::ConstantExpr::getPointerCast(value, destTy);
1834
1835 return llvm::ConstantExpr::getPtrToInt(value, destTy);
1836}
1837
1838/// Try to emit an absolute l-value, such as a null pointer or an integer
1839/// bitcast to pointer type.
1840llvm::Constant *
1841ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) {
John McCall99e5e982017-08-17 05:03:55 +00001842 // If we're producing a pointer, this is easy.
Don Hintonf170dff2019-03-19 06:14:14 +00001843 auto destPtrTy = cast<llvm::PointerType>(destTy);
1844 if (Value.isNullPointer()) {
1845 // FIXME: integer offsets from non-zero null pointers.
1846 return CGM.getNullPointer(destPtrTy, DestType);
John McCall99e5e982017-08-17 05:03:55 +00001847 }
1848
Don Hintonf170dff2019-03-19 06:14:14 +00001849 // Convert the integer to a pointer-sized integer before converting it
1850 // to a pointer.
1851 // FIXME: signedness depends on the original integer type.
1852 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy);
Simon Pilgrim3ff9c512019-05-11 11:01:46 +00001853 llvm::Constant *C;
Don Hintonf170dff2019-03-19 06:14:14 +00001854 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy,
1855 /*isSigned*/ false);
1856 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy);
John McCall99e5e982017-08-17 05:03:55 +00001857 return C;
1858}
1859
1860ConstantLValue
1861ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) {
1862 // Handle values.
1863 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) {
1864 if (D->hasAttr<WeakRefAttr>())
1865 return CGM.GetWeakRefReference(D).getPointer();
1866
1867 if (auto FD = dyn_cast<FunctionDecl>(D))
1868 return CGM.GetAddrOfFunction(FD);
1869
1870 if (auto VD = dyn_cast<VarDecl>(D)) {
1871 // We can never refer to a variable with local storage.
1872 if (!VD->hasLocalStorage()) {
1873 if (VD->isFileVarDecl() || VD->hasExternalStorage())
1874 return CGM.GetAddrOfGlobalVar(VD);
1875
1876 if (VD->isLocalVarDecl()) {
1877 return CGM.getOrCreateStaticVarDecl(
Rui Ueyama49a3ad22019-07-16 04:46:31 +00001878 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false));
John McCall99e5e982017-08-17 05:03:55 +00001879 }
1880 }
1881 }
1882
Richard Smithbab6df82020-04-11 22:15:29 -07001883 if (auto *GD = dyn_cast<MSGuidDecl>(D))
1884 return CGM.GetAddrOfMSGuidDecl(GD);
1885
John McCall99e5e982017-08-17 05:03:55 +00001886 return nullptr;
1887 }
1888
Richard Smithee0ce3022019-05-17 07:06:46 +00001889 // Handle typeid(T).
1890 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) {
1891 llvm::Type *StdTypeInfoPtrTy =
1892 CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo();
1893 llvm::Constant *TypeInfo =
1894 CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0));
1895 if (TypeInfo->getType() != StdTypeInfoPtrTy)
1896 TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy);
1897 return TypeInfo;
1898 }
1899
John McCall99e5e982017-08-17 05:03:55 +00001900 // Otherwise, it must be an expression.
1901 return Visit(base.get<const Expr*>());
1902}
1903
1904ConstantLValue
Bill Wendling8003edc2018-11-09 00:41:36 +00001905ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) {
1906 return Visit(E->getSubExpr());
1907}
1908
1909ConstantLValue
John McCall99e5e982017-08-17 05:03:55 +00001910ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1911 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E);
1912}
1913
1914ConstantLValue
1915ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) {
1916 return CGM.GetAddrOfConstantStringFromLiteral(E);
1917}
1918
1919ConstantLValue
1920ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1921 return CGM.GetAddrOfConstantStringFromObjCEncode(E);
1922}
1923
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001924static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S,
1925 QualType T,
1926 CodeGenModule &CGM) {
1927 auto C = CGM.getObjCRuntime().GenerateConstantString(S);
1928 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T));
1929}
1930
John McCall99e5e982017-08-17 05:03:55 +00001931ConstantLValue
1932ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
Akira Hatanaka1488ee42019-03-08 04:45:37 +00001933 return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM);
1934}
1935
1936ConstantLValue
1937ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
1938 assert(E->isExpressibleAsConstantInitializer() &&
1939 "this boxed expression can't be emitted as a compile-time constant");
1940 auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts());
1941 return emitConstantObjCStringLiteral(SL, E->getType(), CGM);
John McCall99e5e982017-08-17 05:03:55 +00001942}
1943
1944ConstantLValue
1945ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) {
Eli Friedman3f82f9e2019-01-22 00:11:17 +00001946 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName());
John McCall99e5e982017-08-17 05:03:55 +00001947}
1948
1949ConstantLValue
1950ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) {
1951 assert(Emitter.CGF && "Invalid address of label expression outside function");
1952 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel());
1953 Ptr = llvm::ConstantExpr::getBitCast(Ptr,
1954 CGM.getTypes().ConvertType(E->getType()));
1955 return Ptr;
1956}
1957
1958ConstantLValue
1959ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) {
1960 unsigned builtin = E->getBuiltinCallee();
1961 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString &&
1962 builtin != Builtin::BI__builtin___NSStringMakeConstantString)
1963 return nullptr;
1964
1965 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts());
1966 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) {
1967 return CGM.getObjCRuntime().GenerateConstantString(literal);
1968 } else {
1969 // FIXME: need to deal with UCN conversion issues.
1970 return CGM.GetAddrOfConstantCFString(literal);
1971 }
1972}
1973
1974ConstantLValue
1975ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) {
1976 StringRef functionName;
1977 if (auto CGF = Emitter.CGF)
1978 functionName = CGF->CurFn->getName();
1979 else
1980 functionName = "global";
1981
1982 return CGM.GetAddrOfGlobalBlock(E, functionName);
1983}
1984
1985ConstantLValue
1986ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
1987 QualType T;
1988 if (E->isTypeOperand())
1989 T = E->getTypeOperand(CGM.getContext());
1990 else
1991 T = E->getExprOperand()->getType();
1992 return CGM.GetAddrOfRTTIDescriptor(T);
1993}
1994
1995ConstantLValue
John McCall99e5e982017-08-17 05:03:55 +00001996ConstantLValueEmitter::VisitMaterializeTemporaryExpr(
1997 const MaterializeTemporaryExpr *E) {
1998 assert(E->getStorageDuration() == SD_Static);
1999 SmallVector<const Expr *, 2> CommaLHSs;
2000 SmallVector<SubobjectAdjustment, 2> Adjustments;
Tykerb0561b32019-11-17 11:41:55 +01002001 const Expr *Inner =
2002 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
John McCall99e5e982017-08-17 05:03:55 +00002003 return CGM.GetAddrOfGlobalTemporary(E, Inner);
2004}
2005
John McCallde0fe072017-08-15 21:42:52 +00002006llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value,
2007 QualType DestType) {
Richard Smithdafff942012-01-14 04:30:29 +00002008 switch (Value.getKind()) {
Richard Smithe637cbe2019-05-21 23:15:18 +00002009 case APValue::None:
2010 case APValue::Indeterminate:
2011 // Out-of-lifetime and indeterminate values can be modeled as 'undef'.
2012 return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType));
John McCall99e5e982017-08-17 05:03:55 +00002013 case APValue::LValue:
2014 return ConstantLValueEmitter(*this, Value, DestType).tryEmit();
Richard Smithbc6387672012-03-02 23:27:11 +00002015 case APValue::Int:
John McCallde0fe072017-08-15 21:42:52 +00002016 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt());
Leonard Chan86285d22019-01-16 18:53:05 +00002017 case APValue::FixedPoint:
2018 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2019 Value.getFixedPoint().getValue());
Richard Smithdafff942012-01-14 04:30:29 +00002020 case APValue::ComplexInt: {
2021 llvm::Constant *Complex[2];
2022
John McCallde0fe072017-08-15 21:42:52 +00002023 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002024 Value.getComplexIntReal());
John McCallde0fe072017-08-15 21:42:52 +00002025 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002026 Value.getComplexIntImag());
2027
2028 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002029 llvm::StructType *STy =
2030 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002031 return llvm::ConstantStruct::get(STy, Complex);
2032 }
2033 case APValue::Float: {
2034 const llvm::APFloat &Init = Value.getFloat();
Stephan Bergmann17c7f702016-12-14 11:57:17 +00002035 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() &&
John McCallde0fe072017-08-15 21:42:52 +00002036 !CGM.getContext().getLangOpts().NativeHalfType &&
Akira Hatanaka502775a2017-12-09 00:02:37 +00002037 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics())
John McCallde0fe072017-08-15 21:42:52 +00002038 return llvm::ConstantInt::get(CGM.getLLVMContext(),
2039 Init.bitcastToAPInt());
Richard Smithdafff942012-01-14 04:30:29 +00002040 else
John McCallde0fe072017-08-15 21:42:52 +00002041 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init);
Richard Smithdafff942012-01-14 04:30:29 +00002042 }
2043 case APValue::ComplexFloat: {
2044 llvm::Constant *Complex[2];
2045
John McCallde0fe072017-08-15 21:42:52 +00002046 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002047 Value.getComplexFloatReal());
John McCallde0fe072017-08-15 21:42:52 +00002048 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(),
Richard Smithdafff942012-01-14 04:30:29 +00002049 Value.getComplexFloatImag());
2050
2051 // FIXME: the target may want to specify that this is packed.
Serge Guelton1d993272017-05-09 19:31:30 +00002052 llvm::StructType *STy =
2053 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType());
Richard Smithdafff942012-01-14 04:30:29 +00002054 return llvm::ConstantStruct::get(STy, Complex);
2055 }
2056 case APValue::Vector: {
Richard Smithdafff942012-01-14 04:30:29 +00002057 unsigned NumElts = Value.getVectorLength();
George Burgess IV533ff002015-12-11 00:23:35 +00002058 SmallVector<llvm::Constant *, 4> Inits(NumElts);
Richard Smithdafff942012-01-14 04:30:29 +00002059
George Burgess IV533ff002015-12-11 00:23:35 +00002060 for (unsigned I = 0; I != NumElts; ++I) {
2061 const APValue &Elt = Value.getVectorElt(I);
Richard Smithdafff942012-01-14 04:30:29 +00002062 if (Elt.isInt())
John McCallde0fe072017-08-15 21:42:52 +00002063 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt());
George Burgess IV533ff002015-12-11 00:23:35 +00002064 else if (Elt.isFloat())
John McCallde0fe072017-08-15 21:42:52 +00002065 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat());
Richard Smithdafff942012-01-14 04:30:29 +00002066 else
George Burgess IV533ff002015-12-11 00:23:35 +00002067 llvm_unreachable("unsupported vector element type");
Richard Smithdafff942012-01-14 04:30:29 +00002068 }
2069 return llvm::ConstantVector::get(Inits);
2070 }
2071 case APValue::AddrLabelDiff: {
2072 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS();
2073 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS();
John McCallde0fe072017-08-15 21:42:52 +00002074 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType());
2075 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType());
2076 if (!LHS || !RHS) return nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002077
2078 // Compute difference
John McCallde0fe072017-08-15 21:42:52 +00002079 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType);
2080 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy);
2081 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy);
Richard Smithdafff942012-01-14 04:30:29 +00002082 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS);
2083
2084 // LLVM is a bit sensitive about the exact format of the
2085 // address-of-label difference; make sure to truncate after
2086 // the subtraction.
2087 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType);
2088 }
2089 case APValue::Struct:
2090 case APValue::Union:
John McCallde0fe072017-08-15 21:42:52 +00002091 return ConstStructBuilder::BuildStruct(*this, Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002092 case APValue::Array: {
Richard Smith3e268632018-05-23 23:41:38 +00002093 const ConstantArrayType *CAT =
2094 CGM.getContext().getAsConstantArrayType(DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002095 unsigned NumElements = Value.getArraySize();
2096 unsigned NumInitElts = Value.getArrayInitializedElts();
2097
Richard Smithdafff942012-01-14 04:30:29 +00002098 // Emit array filler, if there is one.
Craig Topper8a13c412014-05-21 05:09:00 +00002099 llvm::Constant *Filler = nullptr;
Richard Smith3e268632018-05-23 23:41:38 +00002100 if (Value.hasArrayFiller()) {
John McCallde0fe072017-08-15 21:42:52 +00002101 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(),
2102 CAT->getElementType());
Richard Smith3e268632018-05-23 23:41:38 +00002103 if (!Filler)
2104 return nullptr;
Hans Wennborg156349f2018-05-23 08:24:01 +00002105 }
David Majnemer90d85442014-12-28 23:46:59 +00002106
Richard Smith3e268632018-05-23 23:41:38 +00002107 // Emit initializer elements.
John McCallde0fe072017-08-15 21:42:52 +00002108 SmallVector<llvm::Constant*, 16> Elts;
Richard Smith3e268632018-05-23 23:41:38 +00002109 if (Filler && Filler->isNullValue())
2110 Elts.reserve(NumInitElts + 1);
2111 else
2112 Elts.reserve(NumElements);
2113
2114 llvm::Type *CommonElementType = nullptr;
2115 for (unsigned I = 0; I < NumInitElts; ++I) {
2116 llvm::Constant *C = tryEmitPrivateForMemory(
2117 Value.getArrayInitializedElt(I), CAT->getElementType());
John McCallde0fe072017-08-15 21:42:52 +00002118 if (!C) return nullptr;
2119
Richard Smithdafff942012-01-14 04:30:29 +00002120 if (I == 0)
2121 CommonElementType = C->getType();
2122 else if (C->getType() != CommonElementType)
Craig Topper8a13c412014-05-21 05:09:00 +00002123 CommonElementType = nullptr;
Richard Smithdafff942012-01-14 04:30:29 +00002124 Elts.push_back(C);
2125 }
2126
Balaji V. Iyer749e8282018-08-08 00:01:21 +00002127 // This means that the array type is probably "IncompleteType" or some
2128 // type that is not ConstantArray.
2129 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) {
2130 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType);
2131 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType());
2132 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType,
2133 NumElements);
2134 return llvm::ConstantAggregateZero::get(AType);
2135 }
2136
Richard Smith5745feb2019-06-17 21:08:30 +00002137 llvm::ArrayType *Desired =
2138 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType));
2139 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts,
Richard Smith3e268632018-05-23 23:41:38 +00002140 Filler);
Richard Smithdafff942012-01-14 04:30:29 +00002141 }
2142 case APValue::MemberPointer:
John McCallde0fe072017-08-15 21:42:52 +00002143 return CGM.getCXXABI().EmitMemberPointer(Value, DestType);
Richard Smithdafff942012-01-14 04:30:29 +00002144 }
2145 llvm_unreachable("Unknown APValue kind");
2146}
2147
George Burgess IV1a39b862016-12-28 07:27:40 +00002148llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted(
2149 const CompoundLiteralExpr *E) {
2150 return EmittedCompoundLiterals.lookup(E);
2151}
2152
2153void CodeGenModule::setAddrOfConstantCompoundLiteral(
2154 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) {
2155 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second;
2156 (void)Ok;
2157 assert(Ok && "CLE has already been emitted!");
2158}
2159
John McCall7f416cc2015-09-08 08:05:57 +00002160ConstantAddress
Richard Smith2d988f02011-11-22 22:48:32 +00002161CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) {
2162 assert(E->isFileScope() && "not a file-scope compound literal expr");
John McCallde0fe072017-08-15 21:42:52 +00002163 return tryEmitGlobalCompoundLiteral(*this, nullptr, E);
Richard Smith2d988f02011-11-22 22:48:32 +00002164}
2165
John McCallf3a88602011-02-03 08:15:49 +00002166llvm::Constant *
2167CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) {
2168 // Member pointer constants always have a very particular form.
2169 const MemberPointerType *type = cast<MemberPointerType>(uo->getType());
2170 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl();
2171
2172 // A member function pointer.
2173 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl))
David Majnemere2be95b2015-06-23 07:31:01 +00002174 return getCXXABI().EmitMemberFunctionPointer(method);
John McCallf3a88602011-02-03 08:15:49 +00002175
2176 // Otherwise, a member data pointer.
Richard Smithdafff942012-01-14 04:30:29 +00002177 uint64_t fieldOffset = getContext().getFieldOffset(decl);
John McCallf3a88602011-02-03 08:15:49 +00002178 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset);
2179 return getCXXABI().EmitMemberDataPointer(type, chars);
2180}
2181
John McCall0217dfc22011-02-15 06:40:56 +00002182static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002183 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002184 const CXXRecordDecl *base);
2185
Anders Carlsson849ea412010-11-22 18:42:14 +00002186static llvm::Constant *EmitNullConstant(CodeGenModule &CGM,
Yaxun Liu402804b2016-12-15 08:09:08 +00002187 const RecordDecl *record,
John McCall0217dfc22011-02-15 06:40:56 +00002188 bool asCompleteObject) {
2189 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record);
Chris Lattner2192fe52011-07-18 04:24:23 +00002190 llvm::StructType *structure =
John McCall0217dfc22011-02-15 06:40:56 +00002191 (asCompleteObject ? layout.getLLVMType()
2192 : layout.getBaseSubobjectLLVMType());
Anders Carlsson849ea412010-11-22 18:42:14 +00002193
John McCall0217dfc22011-02-15 06:40:56 +00002194 unsigned numElements = structure->getNumElements();
2195 std::vector<llvm::Constant *> elements(numElements);
Anders Carlsson849ea412010-11-22 18:42:14 +00002196
Yaxun Liu402804b2016-12-15 08:09:08 +00002197 auto CXXR = dyn_cast<CXXRecordDecl>(record);
John McCall0217dfc22011-02-15 06:40:56 +00002198 // Fill in all the bases.
Yaxun Liu402804b2016-12-15 08:09:08 +00002199 if (CXXR) {
2200 for (const auto &I : CXXR->bases()) {
2201 if (I.isVirtual()) {
2202 // Ignore virtual bases; if we're laying out for a complete
2203 // object, we'll lay these out later.
2204 continue;
2205 }
2206
2207 const CXXRecordDecl *base =
2208 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2209
2210 // Ignore empty bases.
2211 if (base->isEmpty() ||
2212 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize()
2213 .isZero())
2214 continue;
2215
2216 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base);
2217 llvm::Type *baseType = structure->getElementType(fieldIndex);
2218 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
Anders Carlsson849ea412010-11-22 18:42:14 +00002219 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002220 }
2221
John McCall0217dfc22011-02-15 06:40:56 +00002222 // Fill in all the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002223 for (const auto *Field : record->fields()) {
Eli Friedmandae858a2011-12-07 01:30:11 +00002224 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we
2225 // will fill in later.)
Richard Smith78b239e2019-06-20 20:44:45 +00002226 if (!Field->isBitField() && !Field->isZeroSize(CGM.getContext())) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002227 unsigned fieldIndex = layout.getLLVMFieldNo(Field);
2228 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType());
Eli Friedmandae858a2011-12-07 01:30:11 +00002229 }
2230
2231 // For unions, stop after the first named field.
David Majnemer4e51dfc2015-05-30 09:12:07 +00002232 if (record->isUnion()) {
2233 if (Field->getIdentifier())
2234 break;
George Karpenkov39e51372018-07-28 02:16:13 +00002235 if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
David Majnemer4e51dfc2015-05-30 09:12:07 +00002236 if (FieldRD->findFirstNamedDataMember())
2237 break;
2238 }
John McCall0217dfc22011-02-15 06:40:56 +00002239 }
2240
2241 // Fill in the virtual bases, if we're working with the complete object.
Yaxun Liu402804b2016-12-15 08:09:08 +00002242 if (CXXR && asCompleteObject) {
2243 for (const auto &I : CXXR->vbases()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002244 const CXXRecordDecl *base =
Aaron Ballman445a9392014-03-13 16:15:17 +00002245 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
John McCall0217dfc22011-02-15 06:40:56 +00002246
2247 // Ignore empty bases.
2248 if (base->isEmpty())
2249 continue;
2250
2251 unsigned fieldIndex = layout.getVirtualBaseIndex(base);
2252
2253 // We might have already laid this field out.
2254 if (elements[fieldIndex]) continue;
2255
Chris Lattner2192fe52011-07-18 04:24:23 +00002256 llvm::Type *baseType = structure->getElementType(fieldIndex);
John McCall0217dfc22011-02-15 06:40:56 +00002257 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base);
2258 }
Anders Carlsson849ea412010-11-22 18:42:14 +00002259 }
2260
2261 // Now go through all other fields and zero them out.
John McCall0217dfc22011-02-15 06:40:56 +00002262 for (unsigned i = 0; i != numElements; ++i) {
2263 if (!elements[i])
2264 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i));
Anders Carlsson849ea412010-11-22 18:42:14 +00002265 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002266
John McCall0217dfc22011-02-15 06:40:56 +00002267 return llvm::ConstantStruct::get(structure, elements);
2268}
2269
2270/// Emit the null constant for a base subobject.
2271static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00002272 llvm::Type *baseType,
John McCall0217dfc22011-02-15 06:40:56 +00002273 const CXXRecordDecl *base) {
2274 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base);
2275
2276 // Just zero out bases that don't have any pointer to data members.
2277 if (baseLayout.isZeroInitializableAsBase())
2278 return llvm::Constant::getNullValue(baseType);
2279
David Majnemer2213bfe2014-10-17 01:00:43 +00002280 // Otherwise, we can just use its null constant.
2281 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false);
Anders Carlsson849ea412010-11-22 18:42:14 +00002282}
2283
John McCallde0fe072017-08-15 21:42:52 +00002284llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM,
2285 QualType T) {
2286 return emitForMemory(CGM, CGM.EmitNullConstant(T), T);
2287}
2288
Eli Friedman20bb5e02009-04-13 21:47:26 +00002289llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) {
Yaxun Liu402804b2016-12-15 08:09:08 +00002290 if (T->getAs<PointerType>())
2291 return getNullPointer(
2292 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T);
2293
John McCall614dbdc2010-08-22 21:01:12 +00002294 if (getTypes().isZeroInitializable(T))
Anders Carlsson867b48f2009-08-24 17:16:23 +00002295 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T));
Fangrui Song6907ce22018-07-30 19:24:48 +00002296
Anders Carlssonf48123b2009-08-09 18:26:27 +00002297 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) {
Chris Lattner72977a12012-02-06 22:00:56 +00002298 llvm::ArrayType *ATy =
2299 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T));
Mike Stump11289f42009-09-09 15:08:12 +00002300
Anders Carlssonf48123b2009-08-09 18:26:27 +00002301 QualType ElementTy = CAT->getElementType();
2302
John McCallde0fe072017-08-15 21:42:52 +00002303 llvm::Constant *Element =
2304 ConstantEmitter::emitNullForMemory(*this, ElementTy);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002305 unsigned NumElements = CAT->getSize().getZExtValue();
Chris Lattner72977a12012-02-06 22:00:56 +00002306 SmallVector<llvm::Constant *, 8> Array(NumElements, Element);
Anders Carlssone8bfe412010-02-02 05:17:25 +00002307 return llvm::ConstantArray::get(ATy, Array);
Anders Carlssonf48123b2009-08-09 18:26:27 +00002308 }
Anders Carlssond606de72009-08-23 01:25:01 +00002309
Yaxun Liu402804b2016-12-15 08:09:08 +00002310 if (const RecordType *RT = T->getAs<RecordType>())
2311 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true);
Mike Stump11289f42009-09-09 15:08:12 +00002312
David Majnemer5fd33e02015-04-24 01:25:08 +00002313 assert(T->isMemberDataPointerType() &&
Anders Carlssone8bfe412010-02-02 05:17:25 +00002314 "Should only see pointers to data members here!");
David Majnemer2213bfe2014-10-17 01:00:43 +00002315
John McCallf3a88602011-02-03 08:15:49 +00002316 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>());
Eli Friedman20bb5e02009-04-13 21:47:26 +00002317}
Eli Friedmanfde961d2011-10-14 02:27:24 +00002318
2319llvm::Constant *
2320CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) {
2321 return ::EmitNullConstant(*this, Record, false);
2322}